tightbeam-rs 0.9.0

A secure, high-performance messaging protocol library
Documentation
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(all(
	not(feature = "std"),
	any(feature = "aead", feature = "signature", feature = "compress")
))]
use alloc::boxed::Box;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::time::SystemTime;

use crate::builder::{MetadataBuilder, TypeBuilder};
use crate::der::oid::ObjectIdentifier;
use crate::error::Result;
use crate::error::{ReceivedExpectedError, TightBeamError};
use crate::matrix::{IntoMatrixDyn, MatrixDyn};
use crate::{Frame, Message, Version};

#[cfg(feature = "compress")]
use crate::compress::Compressor;
#[cfg(feature = "aead")]
use crate::crypto::aead::Aead;
#[cfg(feature = "aead")]
use crate::crypto::aead::Encryptor;
#[cfg(feature = "digest")]
use crate::crypto::hash::Digest;
#[cfg(any(feature = "aead", feature = "digest", feature = "signature"))]
use crate::crypto::profiles::SecurityProfile;
#[cfg(feature = "signature")]
use crate::crypto::sign::SignatureEncoding;
#[cfg(feature = "signature")]
use crate::crypto::sign::{Signatory, SignatureAlgorithmIdentifier};
#[cfg(any(feature = "digest", feature = "aead", feature = "ecdh"))]
use crate::der::oid::AssociatedOid;
#[cfg(feature = "digest")]
use crate::helpers::Digestor;

#[cfg(feature = "aead")]
type EncryptorFn = Box<dyn FnOnce(&[u8]) -> Result<crate::EncryptedContentInfo>>;

#[cfg(feature = "signature")]
type SignerFn = Box<dyn FnOnce(&[u8]) -> Result<crate::SignerInfo>>;

/// Sealed trait pattern for compile-time OID validation
/// Prevents external impls while allowing conditional enforcement
#[doc(hidden)]
pub mod private {
	#[cfg(any(feature = "digest", feature = "aead", feature = "ecdh", feature = "signature"))]
	use super::*;

	#[cfg(feature = "digest")]
	pub trait SealedDigestOid<D: AssociatedOid> {}

	#[cfg(feature = "aead")]
	pub trait SealedAeadOid<C: AssociatedOid> {}

	#[cfg(feature = "ecdh")]
	pub trait SealedCurveOid<C: AssociatedOid> {}

	#[cfg(feature = "signature")]
	pub trait SealedSignatureOid<S: SignatureAlgorithmIdentifier> {}
}

/// Checker traits for compile-time OID validation
/// Uses sealed trait pattern to prevent external impls and enable conditional enforcement
#[cfg(feature = "digest")]
pub trait CheckDigestOid<D: AssociatedOid>: private::SealedDigestOid<D> {
	const RESULT: ();
}

#[cfg(feature = "aead")]
pub trait CheckAeadOid<C: AssociatedOid>: private::SealedAeadOid<C> {
	const RESULT: ();
}

#[cfg(feature = "ecdh")]
pub trait CheckCurveOid<C: AssociatedOid>: private::SealedCurveOid<C> {
	const RESULT: ();
}

#[cfg(feature = "signature")]
pub trait CheckSignatureOid<S: SignatureAlgorithmIdentifier>: private::SealedSignatureOid<S> {
	const RESULT: ();
}

/// Zero-allocation error accumulator for FrameBuilder.
/// Stores up to 5 errors inline, which covers the common case of one
/// deferred error per builder method; spills to a Vec beyond that.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Default)]
enum ErrorAccumulator {
	/// No errors (zero allocation)
	#[default]
	None,
	/// 1 error stored inline (zero allocation)
	One(TightBeamError),
	/// 2-5 errors stored inline (zero allocation)
	Many([Option<TightBeamError>; 5], u8),
	/// 6+ errors (heap allocation)
	Heap(Vec<TightBeamError>),
}

impl ErrorAccumulator {
	fn push(&mut self, error: TightBeamError) {
		match core::mem::replace(self, Self::None) {
			Self::None => *self = Self::One(error),
			Self::One(first) => {
				let mut arr = [None, None, None, None, None];
				arr[0] = Some(first);
				arr[1] = Some(error);
				*self = Self::Many(arr, 2);
			}
			Self::Many(mut arr, len) => {
				let len_usize = len as usize;
				if len_usize < 5 {
					arr[len_usize] = Some(error);
					*self = Self::Many(arr, len + 1);
				} else {
					// Convert to heap storage
					let mut vec = Vec::with_capacity(6);
					for item in arr.iter_mut().take(len_usize) {
						if let Some(err) = core::mem::take(item) {
							vec.push(err);
						}
					}

					vec.push(error);
					*self = Self::Heap(vec);
				}
			}
			Self::Heap(mut errors) => {
				errors.push(error);
				*self = Self::Heap(errors);
			}
		}
	}

	/// Collapse into the terminal build error: a single deferred error
	/// surfaces bare so callers can match on it directly; only genuinely
	/// multiple errors are wrapped in `Sequence`.
	fn into_error(self) -> Option<TightBeamError> {
		match self {
			Self::None => None,
			Self::One(error) => Some(error),
			other => Some(TightBeamError::Sequence(other.into())),
		}
	}
}

impl From<ErrorAccumulator> for Vec<TightBeamError> {
	fn from(accumulator: ErrorAccumulator) -> Self {
		match accumulator {
			ErrorAccumulator::None => Vec::new(),
			ErrorAccumulator::One(error) => vec![error],
			ErrorAccumulator::Many(mut arr, len) => {
				let len = len as usize;
				let mut vec = Vec::with_capacity(len);
				for item in arr.iter_mut().take(len) {
					if let Some(err) = core::mem::take(item) {
						vec.push(err);
					}
				}
				vec
			}
			ErrorAccumulator::Heap(errors) => errors,
		}
	}
}

/// A fluent builder for creating tightbeam messages with metadata generation
pub struct FrameBuilder<T: Message> {
	version: Version,
	message: Option<T>,
	message_oid: Option<ObjectIdentifier>,
	metadata_builder: MetadataBuilder,
	errors: ErrorAccumulator,
	#[cfg(feature = "compress")]
	compressor: Option<Box<dyn Compressor>>,
	#[cfg(feature = "aead")]
	#[allow(clippy::type_complexity)]
	encryptor: Option<Box<dyn FnOnce(&[u8]) -> Result<crate::EncryptedContentInfo>>>,
	#[cfg(feature = "aead")]
	rng: Option<Box<dyn rand_core::CryptoRngCore>>,
	#[cfg(feature = "digest")]
	witness: Option<Digestor>,
	#[cfg(feature = "signature")]
	#[allow(clippy::type_complexity)]
	signer: Option<Box<dyn FnOnce(&[u8]) -> Result<crate::SignerInfo>>>,
}

impl<T: Message> From<Version> for FrameBuilder<T> {
	fn from(version: Version) -> Self {
		Self {
			version,
			message: None,
			message_oid: None,
			metadata_builder: MetadataBuilder::from(version),
			errors: ErrorAccumulator::default(),
			#[cfg(feature = "compress")]
			compressor: None,
			#[cfg(feature = "aead")]
			encryptor: None,
			#[cfg(feature = "aead")]
			rng: None,
			#[cfg(feature = "digest")]
			witness: None,
			#[cfg(feature = "signature")]
			signer: None,
		}
	}
}

impl<T: Message> FrameBuilder<T> {
	/// Set the message ID
	pub fn with_id(mut self, id: impl AsRef<[u8]>) -> Self {
		self.metadata_builder = self.metadata_builder.with_id(id);
		self
	}

	pub fn with_content_oid(mut self, oid: ObjectIdentifier) -> Self {
		self.message_oid = Some(oid);
		self
	}

	/// Set the order (Unix order in seconds)
	pub fn with_order(mut self, seconds: u64) -> Self {
		self.metadata_builder = self.metadata_builder.with_order(seconds);
		self
	}

	/// Set the message body
	pub fn with_message(mut self, message: T) -> Self {
		self.message = Some(message);
		self
	}

	/// Set the message priority (V2+ only)
	pub fn with_priority(mut self, priority: crate::MessagePriority) -> Self {
		self.metadata_builder = self.metadata_builder.with_priority(priority);
		self
	}

	/// Set the TTL in seconds (V2+ only)
	pub fn with_lifetime(mut self, seconds: u64) -> Self {
		self.metadata_builder = self.metadata_builder.with_lifetime(seconds);
		self
	}

	/// Set the parent message hash (V2+ only)
	/// Links this message to a parent message by including the parent's
	/// message hash. This creates a cryptographic chain of messages where
	/// each message references the hash of its parent's content.
	pub fn with_previous_hash(mut self, parent_hash: crate::DigestInfo) -> Self {
		self.metadata_builder = self.metadata_builder.previous_frame(parent_hash);
		self
	}

	/// Set the routing matrix (V3+ only)
	pub fn with_matrix<M>(mut self, matrix: M) -> Self
	where
		M: IntoMatrixDyn,
	{
		match matrix.into_matrix_dyn() {
			Ok(matrix_dyn) => {
				self.metadata_builder = self.metadata_builder.with_matrix(matrix_dyn);
			}
			Err(e) => {
				self.errors.push(TightBeamError::MatrixError(e));
			}
		}

		self
	}

	/// Set the routing matrix (V3+ only) - convenience method for MatrixDyn
	pub fn with_matrix_dyn(mut self, matrix: MatrixDyn) -> Self {
		self.metadata_builder = self.metadata_builder.with_matrix(matrix);
		self
	}

	fn validate(&self) -> Result<()> {
		// Check minimum version requirement
		if self.version < T::MIN_VERSION {
			return Err(TightBeamError::UnsupportedVersion(ReceivedExpectedError::from((
				self.version,
				T::MIN_VERSION,
			))));
		}

		// Check if encryption is set when required
		#[cfg(feature = "aead")]
		if T::MUST_BE_CONFIDENTIAL && self.encryptor.is_none() {
			return Err(TightBeamError::MissingEncryptionInfo);
		}

		// Check if signature is set when required
		#[cfg(feature = "signature")]
		if T::MUST_BE_NON_REPUDIABLE && self.signer.is_none() {
			return Err(TightBeamError::MissingSignatureInfo);
		}

		// Check if compression is set when required
		#[cfg(feature = "compress")]
		if T::MUST_BE_COMPRESSED && self.compressor.is_none() {
			return Err(TightBeamError::MissingCompressedData);
		}

		#[cfg(feature = "digest")]
		{
			let has_message_integrity = self.metadata_builder.has_integrity();
			if T::MUST_HAVE_MESSAGE_INTEGRITY && !has_message_integrity {
				return Err(TightBeamError::MissingDigestInfo);
			}
		}

		#[cfg(feature = "digest")]
		if T::MUST_HAVE_FRAME_INTEGRITY && self.witness.is_none() {
			return Err(TightBeamError::MissingDigestInfo);
		}

		// Check if priority is set when required
		if T::MUST_BE_PRIORITIZED && !self.metadata_builder.has_priority() {
			return Err(TightBeamError::MissingPriority);
		}

		Ok(())
	}
}

#[cfg(feature = "compress")]
impl<T: Message> FrameBuilder<T> {
	/// Set the compression algorithm (all versions)
	pub fn with_compression(mut self, compressor: impl Compressor + 'static) -> Self {
		self.compressor = Some(Box::new(compressor));
		self
	}
}

#[cfg(feature = "aead")]
impl<T: Message> FrameBuilder<T> {
	pub fn with_rng(mut self, rng: Box<dyn rand_core::CryptoRngCore>) -> Self {
		self.rng = Some(rng);
		self
	}

	/// Set the AEAD cipher for symmetric encryption
	pub fn with_aead<C, Cipher>(mut self, cipher: Cipher) -> Self
	where
		C: AssociatedOid,
		Cipher: Aead + 'static,
		T: CheckAeadOid<C>,
	{
		// Runtime fallback validation
		if T::HAS_PROFILE && C::OID != <T::Profile as SecurityProfile>::AeadOid::OID {
			self.errors
				.push(TightBeamError::UnexpectedAlgorithm(ReceivedExpectedError::from((
					C::OID,
					<T::Profile as SecurityProfile>::AeadOid::OID,
				))));
			return self;
		}

		// The nonce is generated inside the closure so it is bound to the
		// encryption, not to the builder configuration: a builder that is
		// ever made reusable must not reuse a captured nonce.
		let rng = self.rng.take();
		let message_oid = self.message_oid;
		self.encryptor = Some(Box::new(move |plaintext: &[u8]| {
			let mut rng = rng;
			let rng: &mut dyn rand_core::CryptoRngCore = match rng.as_mut() {
				Some(boxed_rng) => &mut **boxed_rng,
				None => &mut rand_core::OsRng,
			};
			let nonce = Cipher::generate_nonce(rng);
			let encrypted_content = <Cipher as Encryptor<C>>::encrypt_content(&cipher, plaintext, &nonce, message_oid)?;
			Ok(encrypted_content)
		}));

		self
	}

	/// Use a custom encryptor for asymmetric encryption (e.g., ECIES).
	pub fn with_encryptor<C, E>(mut self, encryptor: E) -> Self
	where
		C: AssociatedOid,
		E: Encryptor<C> + 'static,
	{
		// Runtime validation: check either AEAD OID or Curve OID
		if T::HAS_PROFILE {
			let aead_match = C::OID == <T::Profile as SecurityProfile>::AeadOid::OID;
			#[cfg(feature = "ecdh")]
			let curve_match = C::OID == <T::Profile as SecurityProfile>::CurveOid::OID;
			#[cfg(not(feature = "ecdh"))]
			let curve_match = false;

			if !aead_match && !curve_match {
				self.errors
					.push(TightBeamError::UnexpectedAlgorithm(ReceivedExpectedError::from((
						C::OID,
						<T::Profile as SecurityProfile>::AeadOid::OID,
					))));
				return self;
			}
		}

		let message_oid = self.message_oid;
		self.encryptor = Some(Box::new(move |plaintext: &[u8]| {
			// Encryptor handles nonce generation internally (e.g., ECIES)
			encryptor.encrypt_content(plaintext, [], message_oid)
		}));

		self
	}
}

#[cfg(feature = "digest")]
impl<T: Message> FrameBuilder<T> {
	/// Commit to the message body using the specified digest algorithm.
	///
	/// Computes `H(salt || DER(message))` and stores it as the integrity value.
	pub fn with_message_hasher<D>(mut self, salt: impl AsRef<[u8]>) -> Self
	where
		D: Digest + AssociatedOid,
		T: CheckDigestOid<D>,
	{
		// Runtime fallback validation
		if T::HAS_PROFILE && D::OID != <T::Profile as SecurityProfile>::DigestOid::OID {
			self.errors
				.push(TightBeamError::UnexpectedAlgorithm(ReceivedExpectedError::from((
					D::OID,
					<T::Profile as SecurityProfile>::DigestOid::OID,
				))));
			return self;
		}

		let message = match self.message.as_ref() {
			Some(m) => m,
			None => {
				self.errors.push(TightBeamError::InvalidBody);
				return self;
			}
		};

		let encoded = match crate::encode(message) {
			Ok(e) => e,
			Err(e) => {
				self.errors.push(e);
				return self;
			}
		};

		match crate::crypto::commitment::commit_digest::<D>(salt.as_ref(), &encoded) {
			Ok(hash_info) => {
				self.metadata_builder = self.metadata_builder.with_integrity_info(hash_info);
			}
			Err(e) => {
				self.errors.push(e);
			}
		}
		self
	}

	pub fn with_witness_hasher<D>(mut self) -> Self
	where
		D: Digest + AssociatedOid + 'static,
		T: CheckDigestOid<D>,
	{
		// Runtime fallback validation
		if T::HAS_PROFILE && D::OID != <T::Profile as SecurityProfile>::DigestOid::OID {
			self.errors
				.push(TightBeamError::UnexpectedAlgorithm(ReceivedExpectedError::from((
					D::OID,
					<T::Profile as SecurityProfile>::DigestOid::OID,
				))));
			return self;
		}

		self.witness = Some(Box::new(|tbs_der: &[u8]| crate::utils::digest::<D>(tbs_der)));
		self
	}
}

#[cfg(feature = "signature")]
impl<T: Message> FrameBuilder<T> {
	/// Set the signer for message signing
	///
	/// The signature will be computed during `build()` over the complete
	/// message structure. This method captures the signer and signing
	/// algorithm to be used later.
	pub fn with_signer<S, X>(mut self, signer: X) -> Self
	where
		S: SignatureEncoding + SignatureAlgorithmIdentifier,
		X: Signatory<S> + 'static,
		T: CheckSignatureOid<S>,
	{
		// Runtime fallback validation
		if T::HAS_PROFILE && S::ALGORITHM_OID != <T::Profile as SecurityProfile>::SignatureAlg::ALGORITHM_OID {
			self.errors
				.push(TightBeamError::UnexpectedAlgorithm(ReceivedExpectedError::from((
					S::ALGORITHM_OID,
					<T::Profile as SecurityProfile>::SignatureAlg::ALGORITHM_OID,
				))));
			return self;
		}

		self.signer = Some(Box::new(move |data: &[u8]| signer.to_signer_info(data)));
		self
	}
}

impl<T: Message> TypeBuilder<Frame> for FrameBuilder<T> {
	type Error = TightBeamError;

	/// Build the final TightBeam message
	///
	/// If a signer was provided via `with_signer()`, the entire message
	/// structure (version + metadata + body) will be signed after
	/// construction. The signature is computed over the DER-encoded TightBeam
	/// structure minus the signature field.
	///
	/// # Errors
	/// Returns an error if:
	/// - Any validation errors occurred during building
	/// - Required fields are missing
	/// - Metadata validation fails
	/// - Signing fails (if signer was provided)
	fn build(mut self) -> Result<Frame> {
		if let Some(error) = core::mem::take(&mut self.errors).into_error() {
			return Err(error);
		}

		// 0. Validate message restrictions
		self.validate()?;

		let version = self.version;
		let message = self.message.ok_or(TightBeamError::InvalidBody)?;
		let metadata_builder = self.metadata_builder;

		// Delegate to helper methods for better organization

		FrameBuilder::build_impl(
			version,
			message,
			metadata_builder,
			#[cfg(feature = "compress")]
			self.compressor,
			#[cfg(feature = "aead")]
			self.encryptor,
			#[cfg(feature = "digest")]
			self.witness,
			#[cfg(feature = "signature")]
			self.signer,
		)
	}
}

impl<T: Message> FrameBuilder<T> {
	/// Internal build implementation - extracted for cognitive complexity reduction.
	fn build_impl(
		version: Version,
		message: T,
		mut metadata_builder: MetadataBuilder,
		#[cfg(feature = "compress")] compressor: Option<Box<dyn Compressor>>,
		#[cfg(feature = "aead")] encryptor: Option<EncryptorFn>,
		#[cfg(feature = "digest")] witness: Option<Digestor>,
		#[cfg(feature = "signature")] signer: Option<SignerFn>,
	) -> Result<Frame> {
		// Auto-set current time if order is omitted
		metadata_builder = Self::ensure_order_set(metadata_builder)?;

		// 1-3. Build message bytes (encode, compress, encrypt)
		let (message_bytes, metadata_builder) = Self::build_message_bytes(
			message,
			metadata_builder,
			#[cfg(feature = "compress")]
			compressor,
			#[cfg(feature = "aead")]
			encryptor,
		)?;

		// Final assembled frame
		let metadata = metadata_builder.build()?;
		let mut tbs = Frame { version, metadata, message: message_bytes, integrity: None, nonrepudiation: None };

		// Runtime validation: ensure version is compatible with metadata fields
		if !tbs.validate_version_compatibility() {
			return Err(TightBeamError::UnsupportedVersion(ReceivedExpectedError::from((
				version, version,
			))));
		}

		// 4. Optional witness: compute FI over envelope only (version + metadata; excludes message)
		Self::build_frame_integrity(
			&mut tbs,
			#[cfg(feature = "digest")]
			witness,
		)?;

		// 5. Optional signing
		Self::build_signature(
			tbs,
			#[cfg(feature = "signature")]
			signer,
		)
	}

	/// Ensure order is set in metadata builder, auto-setting current time if omitted.
	#[cfg(feature = "std")]
	fn ensure_order_set(mut metadata_builder: MetadataBuilder) -> Result<MetadataBuilder> {
		if !metadata_builder.has_order() {
			match SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
				Ok(duration) => {
					metadata_builder = metadata_builder.with_order(duration.as_secs());
				}
				Err(_) => return Err(TightBeamError::InvalidOrder),
			}
		}
		Ok(metadata_builder)
	}

	#[cfg(not(feature = "std"))]
	fn ensure_order_set(metadata_builder: MetadataBuilder) -> Result<MetadataBuilder> {
		Ok(metadata_builder)
	}

	/// Build message bytes through encoding, compression, and encryption pipeline.
	fn build_message_bytes(
		message: T,
		metadata_builder: MetadataBuilder,
		#[cfg(feature = "compress")] compressor: Option<Box<dyn Compressor>>,
		#[cfg(feature = "aead")] encryptor: Option<EncryptorFn>,
	) -> Result<(Vec<u8>, MetadataBuilder)> {
		// Reassigned only by the compression/encryption stages below.
		#[cfg(any(feature = "compress", feature = "aead"))]
		let mut metadata_builder = metadata_builder;

		// 1. Encode ASN.1
		let bytes = crate::encode(&message)?;

		// 2. Optional compression
		#[cfg(feature = "compress")]
		let bytes = if let Some(compressor) = compressor {
			let (compressed, compression_info) = compressor.compress(&bytes, None)?;
			metadata_builder = metadata_builder.with_compactness_info(compression_info);
			compressed
		} else {
			bytes
		};

		// 3. Optional encryption
		#[cfg(feature = "aead")]
		let message_bytes = if let Some(enc) = encryptor {
			let mut encrypted_content = enc(&bytes)?;
			let encrypted_bytes = encrypted_content
				.encrypted_content
				.take()
				.ok_or(TightBeamError::MissingEncryptionInfo)?;
			metadata_builder = metadata_builder.with_confidentiality_info(encrypted_content);
			encrypted_bytes.into_bytes()
		} else {
			bytes
		};

		#[cfg(not(feature = "aead"))]
		let message_bytes = bytes;

		Ok((message_bytes, metadata_builder))
	}

	/// Build frame integrity (FI) over envelope if witness is provided.
	#[cfg(feature = "digest")]
	fn build_frame_integrity(tbs: &mut Frame, witness: Option<Digestor>) -> Result<()> {
		if let Some(witness_fn) = witness {
			let scaffold = crate::frame::FrameIntegrityScaffold { version: &tbs.version, metadata: &tbs.metadata };
			let scaffold_der = crate::encode(&scaffold)?;
			let witness_info = witness_fn(&scaffold_der)?;
			tbs.integrity = Some(witness_info);
		}
		Ok(())
	}

	#[cfg(not(feature = "digest"))]
	fn build_frame_integrity(_tbs: &mut Frame) -> Result<()> {
		Ok(())
	}

	/// Build signature (nonrepudiation) if signer is provided.
	#[cfg(feature = "signature")]
	fn build_signature(tbs: Frame, signer: Option<SignerFn>) -> Result<Frame> {
		let tbs = tbs;
		if let Some(signer) = signer {
			crate::notarize! {
				tbs: tbs,
				position: nonrepudiation,
				signer: signer
			}
		} else {
			Ok(tbs)
		}
	}

	#[cfg(not(feature = "signature"))]
	fn build_signature(tbs: Frame) -> Result<Frame> {
		Ok(tbs)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::test_builder;
	use crate::testing::{create_test_cipher_key, create_test_message, create_test_signing_key, TestMessage};

	#[cfg(feature = "compress")]
	use crate::compress::ZstdCompression;
	#[cfg(all(feature = "aes-gcm", feature = "sha3"))]
	use crate::crypto::hash::Sha3_256;

	#[cfg(feature = "sha3")]
	test_builder! {
		name: test_v0_basic,
		builder_type: FrameBuilder<TestMessage>,
		version: Version::V0,
		message: create_test_message(None),
		setup: |builder, msg| {
			builder
				.with_message(msg)
				.with_id("test_v0_basic")
				.with_order(1696521600)
				.build()
		},
		assertions: |_msg, result| {
			let tightbeam  = result?;
			assert_eq!(tightbeam.version, Version::V0);
			assert_eq!(str::from_utf8(&tightbeam.metadata.id), Ok("test_v0_basic"));
			Ok(())
		}
	}

	#[cfg(all(feature = "aes-gcm", feature = "sha3", feature = "secp256k1"))]
	test_builder! {
		name: test_v1_with_encryption,
		builder_type: FrameBuilder<TestMessage>,
		version: Version::V1,
		message: create_test_message(None),
		setup: |builder, msg| {
			use crate::crypto::aead::{Aes256Gcm, Aes256GcmOid};
			use crate::crypto::sign::ecdsa::Secp256k1Signature;

			let (_, cipher) = create_test_cipher_key();
			let signing_key = create_test_signing_key();

		builder
			.with_message(msg)
			.with_id("test_v1_with_encryption")
			.with_order(1696521600)
			.with_aead::<Aes256GcmOid, Aes256Gcm>(cipher)
			.with_signer::<Secp256k1Signature, _>(signing_key)
			.build()
		},
		assertions: |message, result| {
			let tightbeam  = result?;
			assert_eq!(tightbeam.version, Version::V1);
			assert!(tightbeam.metadata.confidentiality.is_some());
			assert!(tightbeam.nonrepudiation.is_some());

			// Body should be encrypted (not directly decodable)
			let decode_result: Result<TestMessage> = crate::decode(&tightbeam.message);
			assert!(decode_result.is_err(), "Body should be encrypted");

			// Decrypt and verify
			let (_, cipher) = create_test_cipher_key();
			let decrypted = tightbeam.decrypt::<TestMessage>(&cipher, None)?;
			assert_eq!(decrypted, message);

			Ok(())
		}
	}

	#[cfg(all(
		feature = "compress",
		feature = "aes-gcm",
		feature = "sha3",
		feature = "secp256k1"
	))]
	test_builder! {
		name: test_v1_with_compression,
		builder_type: FrameBuilder<TestMessage>,
		version: Version::V1,
		message: create_test_message(None),
		setup: |builder, msg| {
			use crate::crypto::aead::{Aes256Gcm, Aes256GcmOid};
			use crate::crypto::sign::ecdsa::Secp256k1Signature;
			use crate::compress::ZstdCompression;

			let (_, cipher) = create_test_cipher_key();
			let signing_key = create_test_signing_key();

		builder
			.with_message(msg)
			.with_id("test_v1_with_compression")
			.with_order(1696521600)
			.with_compression(ZstdCompression::default())
			.with_aead::<Aes256GcmOid, Aes256Gcm>(cipher)
			.with_signer::<Secp256k1Signature, _>(signing_key)
			.build()
		},
		assertions: |message, result| {
			let tightbeam = result?;
			assert_eq!(tightbeam.version, Version::V1);
			assert!(tightbeam.metadata.compactness.is_some());
			assert!(tightbeam.metadata.confidentiality.is_some());

			// Body should be encrypted+compressed (not directly decodable)
			let decode_result: Result<TestMessage> = crate::decode(&tightbeam.message);
			assert!(decode_result.is_err(), "Body should be encrypted/compressed");

			// Decrypt (automatically decompresses) and verify
			let (_, cipher) = create_test_cipher_key();
			let decrypted = tightbeam.decrypt::<TestMessage>(&cipher, Some(&ZstdCompression::default()))?;
			assert_eq!(decrypted, message);

			Ok(())
		}
	}

	#[cfg(all(
		feature = "compress",
		feature = "aes-gcm",
		feature = "sha3",
		feature = "secp256k1",
		feature = "random"
	))]
	test_builder! {
		name: test_v2_full,
		builder_type: FrameBuilder<TestMessage>,
		version: Version::V2,
		message: || {
			create_test_message(None)
		},
		setup: |builder, msg| {
			use crate::crypto::aead::{Aes256Gcm, Aes256GcmOid};
			use crate::crypto::sign::ecdsa::Secp256k1Signature;

			let (_, cipher) = create_test_cipher_key();
			let signing_key = create_test_signing_key();

			// Create a previous message hash for linking
			let previous_hash = crate::utils::digest::<Sha3_256>(b"previous-message-data")?;
			let rng = rand_core::OsRng;
			let rng = Box::new(rng);

			builder
				.with_message(msg)
				.with_id("test_v2_full")
				.with_order(1696521600)
				.with_message_hasher::<Sha3_256>([])
				.with_witness_hasher::<Sha3_256>()
				.with_compression(ZstdCompression::default())
				.with_rng(rng)
				.with_aead::<Aes256GcmOid, Aes256Gcm>(cipher)
				.with_signer::<Secp256k1Signature, _>(signing_key)
				.with_priority(crate::MessagePriority::LowLatency)
				.with_lifetime(3600)
				.with_previous_hash(previous_hash)
				// Matrix removed - V2 doesn't support it (V3+ only)
				.build()
		},
		assertions: |message, result| {
			use crate::crypto::sign::ecdsa::Secp256k1Signature;

			let tightbeam = result?;
			assert_eq!(tightbeam.version, Version::V2);
			assert_eq!(tightbeam.metadata.id, b"test_v2_full");
			assert_eq!(tightbeam.metadata.priority, Some(crate::MessagePriority::LowLatency));
			assert_eq!(tightbeam.metadata.lifetime, Some(3600));
			assert!(tightbeam.metadata.confidentiality.is_some());
			assert!(tightbeam.metadata.compactness.is_some());
			assert!(tightbeam.metadata.previous_frame.is_some());
			assert!(tightbeam.metadata.matrix.is_none()); // Matrix is V3+ only
			assert!(tightbeam.integrity.is_some());
			assert!(tightbeam.nonrepudiation.is_some());

			// Verify Message Integrity (MI): compute hash over original message and compare
			let message_der = crate::encode(&message)?;
			let expected_mi = crate::utils::digest::<Sha3_256>(&message_der)?;
			let actual_mi = tightbeam.metadata.integrity.as_ref().ok_or(TightBeamError::MissingDigestInfo)?;
			assert_eq!(actual_mi.digest.as_bytes(), expected_mi.digest.as_bytes());

			// Verify Frame Integrity (FI): compute hash over envelope (version + metadata) and compare
			let scaffold = crate::frame::FrameIntegrityScaffold {
				version: &tightbeam.version,
				metadata: &tightbeam.metadata,
			};
			let scaffold_der = crate::encode(&scaffold)?;
			let expected_fi = crate::utils::digest::<Sha3_256>(&scaffold_der)?;
			let actual_fi = tightbeam.integrity.as_ref().ok_or(TightBeamError::MissingDigestInfo)?;
			assert_eq!(actual_fi.digest.as_bytes(), expected_fi.digest.as_bytes());

			// Body should be encrypted+compressed (not directly decodable)
			let decode_result: Result<TestMessage> = crate::decode(&tightbeam.message);
			assert!(decode_result.is_err());

			// Verify signature before decrypting (decrypt consumes the frame)
			let signing_key = create_test_signing_key();
			let verifying_key = signing_key.verifying_key();
			assert!(tightbeam.verify::<Secp256k1Signature, Sha3_256>(verifying_key).is_ok());

			// Decrypt (automatically decompresses) and verify
			let (_, cipher) = create_test_cipher_key();
			let decrypted = tightbeam.decrypt::<TestMessage>(&cipher, Some(&ZstdCompression::default()))?;
			assert_eq!(decrypted, message);

			Ok(())
		}
	}

	#[test]
	#[cfg(feature = "sha3")]
	fn test_missing_message() {
		let result = FrameBuilder::<TestMessage>::from(Version::V0)
			.with_id("no-message")
			.with_order(1696521600)
			.with_message_hasher::<Sha3_256>([])
			.build();
		assert!(result.is_err());
	}

	// Hashing before the message is set defers an `InvalidBody` error; a
	// single deferred error surfaces bare rather than as a one-element
	// `Sequence`.
	#[test]
	#[cfg(feature = "sha3")]
	fn test_single_deferred_error_surfaces_bare() {
		let message = create_test_message(None);
		let result = FrameBuilder::from(Version::V0)
			.with_id("error-test")
			.with_order(1696521600)
			.with_message_hasher::<Sha3_256>([])
			.with_message(message)
			.build();
		assert!(matches!(result, Err(TightBeamError::InvalidBody)));
	}

	#[test]
	#[cfg(feature = "sha3")]
	fn test_multiple_deferred_errors_surface_as_sequence() {
		let message = create_test_message(None);
		let result = FrameBuilder::from(Version::V0)
			.with_id("error-test")
			.with_order(1696521600)
			.with_message_hasher::<Sha3_256>([])
			.with_message_hasher::<Sha3_256>([])
			.with_message(message)
			.build();
		assert!(matches!(result, Err(TightBeamError::Sequence(ref errors)) if errors.len() == 2));
	}

	// V1 is the first version whose metadata carries integrity info; V0 with
	// `message_integrity` is rejected by `MetadataBuilder::build`.
	#[test]
	#[cfg(feature = "derive")]
	fn test_compose_macro() -> Result<()> {
		let message = create_test_message(None);
		let frame = compose! {
			V1:
				id: "test-id",
				order: 1696521600,
				message: message,
				message_integrity<Sha3_256>: [] // no salt
		}?;
		assert_eq!(frame.version, Version::V1);
		assert_eq!(frame.metadata.id, b"test-id");
		assert_eq!(frame.metadata.order, 1696521600);
		assert!(frame.metadata.integrity.is_some());
		Ok(())
	}

	mod validation {
		use super::*;
		use crate::crypto::aead::{Aes256Gcm, Aes256GcmOid};
		use crate::crypto::hash::Sha3_256;
		use crate::crypto::sign::ecdsa::{Secp256k1Signature, Secp256k1SigningKey};
		use crate::testing::{create_test_cipher_key, create_test_signing_key};
		use crate::Version;

		// Helper macro to run shared test logic after struct definition
		macro_rules! run_tests {
			($name:expr, $confidential:expr, $nonrepudiable:expr, $message_integrity:expr, $frame_integrity:expr, $min_version:expr, $cipher:expr, $signing_key:expr) => {
				let message = TestMsg { content: format!("test {}", $name) };

				// Test 1: Verify constants match derive macro attributes
				assert_eq!(TestMsg::MUST_BE_CONFIDENTIAL, $confidential);
				assert_eq!(TestMsg::MUST_BE_NON_REPUDIABLE, $nonrepudiable);
				assert_eq!(TestMsg::MUST_HAVE_MESSAGE_INTEGRITY, $message_integrity);
				assert_eq!(TestMsg::MUST_HAVE_FRAME_INTEGRITY, $frame_integrity);
				assert_eq!(TestMsg::MIN_VERSION, $min_version);

				// Test 2: Verify frame composition
				let result = compose_frame(
					$name,
					message.clone(),
					$cipher.clone(),
					$signing_key.clone(),
					$confidential,
					$nonrepudiable,
					$message_integrity,
					$frame_integrity,
				);
				assert!(result.is_ok());

				let frame = result.unwrap();

				// Test 3: Verify README semantics - MUST fields -> Frame fields MUST be present
				// README line 363: MUST_BE_NON_REPUDIABLE=true -> Frame MUST include nonrepudiation field
				assert_eq!(frame.nonrepudiation.is_some(), $nonrepudiable);
				// README line 364: MUST_BE_CONFIDENTIAL=true -> Frame MUST include confidentiality field
				assert_eq!(frame.metadata.confidentiality.is_some(), $confidential);
				// MUST_HAVE_MESSAGE_INTEGRITY=true -> Frame metadata MUST include integrity field
				assert_eq!(frame.metadata.integrity.is_some(), $message_integrity);
				// MUST_HAVE_FRAME_INTEGRITY=true -> Frame MUST include integrity field
				assert_eq!(frame.integrity.is_some(), $frame_integrity);

				// Test 4: Verify version enforcement
				if $min_version > Version::V0 {
					let result_v0 = compose! {
						V0: id: $name, order: 1u64, message: message.clone()
					};
					assert!(result_v0.is_err());
				}
			};
		}

		// Helper macro to generate test message struct with correct attributes
		// Only matches the 4 test cases actually used in the test
		macro_rules! test_msg_struct {
			// BasicMessage: (false, false, false, false, V0)
			(false, false, false, false, V0) => {
				#[cfg(feature = "derive")]
				#[derive($crate::Beamable, Clone, Debug, PartialEq, der::Sequence)]
				#[beam(min_version = "V0")]
				struct TestMsg {
					content: String,
				}
				#[cfg(not(feature = "derive"))]
				#[derive(Clone, Debug, PartialEq, der::Sequence)]
				struct TestMsg {
					content: String,
				}
				#[cfg(not(feature = "derive"))]
				impl $crate::Message for TestMsg {
					const MUST_BE_CONFIDENTIAL: bool = false;
					const MUST_BE_NON_REPUDIABLE: bool = false;
					const MUST_BE_COMPRESSED: bool = false;
					const MUST_BE_PRIORITIZED: bool = false;
					const MUST_HAVE_MESSAGE_INTEGRITY: bool = false;
					const MUST_HAVE_FRAME_INTEGRITY: bool = false;
					const MIN_VERSION: Version = Version::V0;
					type Profile = $crate::crypto::profiles::TightbeamProfile;
				}
			};
			// ConfidentialMessage: (true, false, false, false, V1)
			(true, false, false, false, V1) => {
				#[cfg(feature = "derive")]
				#[derive($crate::Beamable, Clone, Debug, PartialEq, der::Sequence)]
				#[beam(confidential, min_version = "V1")]
				struct TestMsg {
					content: String,
				}
				#[cfg(not(feature = "derive"))]
				#[derive(Clone, Debug, PartialEq, der::Sequence)]
				struct TestMsg {
					content: String,
				}
				#[cfg(not(feature = "derive"))]
				impl $crate::Message for TestMsg {
					const MUST_BE_CONFIDENTIAL: bool = true;
					const MUST_BE_NON_REPUDIABLE: bool = false;
					const MUST_BE_COMPRESSED: bool = false;
					const MUST_BE_PRIORITIZED: bool = false;
					const MUST_HAVE_MESSAGE_INTEGRITY: bool = false;
					const MUST_HAVE_FRAME_INTEGRITY: bool = false;
					const MIN_VERSION: Version = Version::V1;
					type Profile = $crate::crypto::profiles::TightbeamProfile;
				}
			};
			// NonrepudiableMessage: (false, true, false, false, V1)
			(false, true, false, false, V1) => {
				#[cfg(feature = "derive")]
				#[derive($crate::Beamable, Clone, Debug, PartialEq, der::Sequence)]
				#[beam(nonrepudiable, min_version = "V1")]
				struct TestMsg {
					content: String,
				}
				#[cfg(not(feature = "derive"))]
				#[derive(Clone, Debug, PartialEq, der::Sequence)]
				struct TestMsg {
					content: String,
				}
				#[cfg(not(feature = "derive"))]
				impl $crate::Message for TestMsg {
					const MUST_BE_CONFIDENTIAL: bool = false;
					const MUST_BE_NON_REPUDIABLE: bool = true;
					const MUST_BE_COMPRESSED: bool = false;
					const MUST_BE_PRIORITIZED: bool = false;
					const MUST_HAVE_MESSAGE_INTEGRITY: bool = false;
					const MUST_HAVE_FRAME_INTEGRITY: bool = false;
					const MIN_VERSION: Version = Version::V1;
					type Profile = $crate::crypto::profiles::TightbeamProfile;
				}
			};
			// FullSecurityMessage: (true, true, true, true, V2)
			(true, true, true, true, V2) => {
				#[cfg(feature = "derive")]
				#[derive($crate::Beamable, Clone, Debug, PartialEq, der::Sequence)]
				#[beam(
					confidential,
					nonrepudiable,
					message_integrity,
					frame_integrity,
					min_version = "V2"
				)]
				struct TestMsg {
					content: String,
				}
				#[cfg(not(feature = "derive"))]
				#[derive(Clone, Debug, PartialEq, der::Sequence)]
				struct TestMsg {
					content: String,
				}
				#[cfg(not(feature = "derive"))]
				impl $crate::Message for TestMsg {
					const MUST_BE_CONFIDENTIAL: bool = true;
					const MUST_BE_NON_REPUDIABLE: bool = true;
					const MUST_BE_COMPRESSED: bool = false;
					const MUST_BE_PRIORITIZED: bool = false;
					const MUST_HAVE_MESSAGE_INTEGRITY: bool = true;
					const MUST_HAVE_FRAME_INTEGRITY: bool = true;
					const MIN_VERSION: Version = Version::V2;
					type Profile = $crate::crypto::profiles::TightbeamProfile;
				}
			};
		}

		// Compose a frame satisfying the given security requirements; the
		// requirement tuple selects the matching `compose!` invocation.
		#[allow(clippy::too_many_arguments)]
		fn compose_frame<T>(
			test_name: &str,
			message: T,
			cipher: Aes256Gcm,
			signing_key: Secp256k1SigningKey,
			confidential: bool,
			nonrepudiable: bool,
			message_integrity: bool,
			frame_integrity: bool,
		) -> crate::error::Result<crate::Frame>
		where
			T: crate::Message
				+ crate::builder::CheckAeadOid<Aes256GcmOid>
				+ crate::builder::CheckSignatureOid<Secp256k1Signature>
				+ crate::builder::CheckDigestOid<Sha3_256>
				+ Clone,
		{
			match (confidential, nonrepudiable, message_integrity, frame_integrity) {
				(true, true, true, true) => compose! {
					V2: id: test_name, order: 1u64, message: message.clone(),
					confidentiality<Aes256GcmOid, _>: cipher,
					nonrepudiation<Secp256k1Signature, _>: signing_key,
					message_integrity<Sha3_256>: [],
					frame_integrity: type Sha3_256
				},
				(true, false, true, _) => compose! {
					V1: id: test_name, order: 1u64, message: message.clone(),
					confidentiality<Aes256GcmOid, _>: cipher,
					message_integrity<Sha3_256>: []
				},
				(true, false, false, _) => compose! {
					V1: id: test_name, order: 1u64, message: message.clone(),
					confidentiality<Aes256GcmOid, _>: cipher
				},
				(false, true, true, _) => compose! {
					V1: id: test_name, order: 1u64, message: message.clone(),
					nonrepudiation<Secp256k1Signature, _>: signing_key,
					message_integrity<Sha3_256>: []
				},
				(false, true, false, _) => compose! {
					V1: id: test_name, order: 1u64, message: message.clone(),
					nonrepudiation<Secp256k1Signature, _>: signing_key
				},
				(false, false, true, true) => compose! {
					V1: id: test_name, order: 1u64, message: message.clone(),
					message_integrity<Sha3_256>: [],
					frame_integrity: type Sha3_256
				},
				(false, false, true, false) => compose! {
					V1: id: test_name, order: 1u64, message: message.clone(),
					message_integrity<Sha3_256>: []
				},
				(false, false, false, true) => compose! {
					V1: id: test_name, order: 1u64, message: message.clone(),
					frame_integrity: type Sha3_256
				},
				(false, false, false, false) => compose! {
					V0: id: test_name, order: 1u64, message: message.clone()
				},
				(true, true, true, false) => compose! {
					V2: id: test_name, order: 1u64, message: message.clone(),
					confidentiality<Aes256GcmOid, _>: cipher,
					nonrepudiation<Secp256k1Signature, _>: signing_key,
					message_integrity<Sha3_256>: []
				},
				(true, true, false, true) => compose! {
					V2: id: test_name, order: 1u64, message: message.clone(),
					confidentiality<Aes256GcmOid, _>: cipher,
					nonrepudiation<Secp256k1Signature, _>: signing_key,
					frame_integrity: type Sha3_256
				},
				(true, true, false, false) => compose! {
					V1: id: test_name, order: 1u64, message: message.clone(),
					confidentiality<Aes256GcmOid, _>: cipher,
					nonrepudiation<Secp256k1Signature, _>: signing_key
				},
			}
		}

		// One named test per requirement combination: the struct definition
		// and the shared assertions are both driven by the same flag tuple,
		// so no dispatch logic is needed inside the tests themselves.
		macro_rules! message_trait_test {
			($test:ident, $name:expr, $confidential:tt, $nonrepudiable:tt, $message_integrity:tt, $frame_integrity:tt, $version:ident) => {
				#[test]
				fn $test() {
					let (_, cipher) = create_test_cipher_key();
					let signing_key = create_test_signing_key();

					test_msg_struct!($confidential, $nonrepudiable, $message_integrity, $frame_integrity, $version);
					run_tests!(
						$name,
						$confidential,
						$nonrepudiable,
						$message_integrity,
						$frame_integrity,
						Version::$version,
						&cipher,
						&signing_key
					);
				}
			};
		}

		message_trait_test!(test_basic_message_traits, "BasicMessage", false, false, false, false, V0);
		message_trait_test!(
			test_confidential_message_traits,
			"ConfidentialMessage",
			true,
			false,
			false,
			false,
			V1
		);
		message_trait_test!(
			test_nonrepudiable_message_traits,
			"NonrepudiableMessage",
			false,
			true,
			false,
			false,
			V1
		);
		message_trait_test!(
			test_full_security_message_traits,
			"FullSecurityMessage",
			true,
			true,
			true,
			true,
			V2
		);
	}
}