synta-python-mtc 0.2.6

Python extension module for synta Merkle Tree Certificates types
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
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyList};
use synta::traits::{Decode, Encode};
use synta_mtc::crypto::{HashAlgorithm, MtcProof, MtcSignature};

use super::proof::{PyHashAlgorithm, PyMtcProof};

// ── IssuanceLogBuilder ────────────────────────────────────────────────────────

/// In-memory Merkle Tree Certificate issuance log builder.
///
/// Wraps ``synta_mtc::builder::IssuanceLogBuilder``.  Entries are accumulated
/// with :meth:`add_entry`; the Merkle tree is recomputed on demand by
/// :meth:`compute_leaf_hashes`, :meth:`compute_root`, and
/// :meth:`checkpoint_at_unix`.
///
/// ```python,ignore
/// import synta.mtc as mtc
///
/// builder = mtc.IssuanceLogBuilder()
/// builder.hash_algorithm(mtc.HashAlgorithm.Sha256)
/// builder.add_entry(tbs_cert_der)
///
/// hashes = builder.compute_leaf_hashes()  # list[bytes]
/// root   = builder.compute_root()         # bytes
/// cp_der = builder.checkpoint_at_unix(log_id_der, int(time.time()))  # bytes
///
/// proof  = builder.generate_proof(1)  # list[bytes] — sibling hashes
/// ```
#[pyclass(name = "IssuanceLogBuilder")]
pub struct PyIssuanceLogBuilder {
    /// The wrapped Rust builder.  Always `Some`; temporarily replaced during
    /// consuming operations via `take_inner`.
    inner: Option<synta_mtc::builder::IssuanceLogBuilder<'static>>,
    /// Owns the DER byte buffers that the builder entries borrow from.
    /// Boxes keep heap addresses stable across `Vec` reallocations.
    _entry_bytes: Vec<Box<[u8]>>,
}

impl PyIssuanceLogBuilder {
    /// Extract the inner builder, leaving a fresh default in its place.
    ///
    /// Every method that needs to call a consuming builder method uses this
    /// pattern:
    /// ```ignore
    /// let old = self.take_inner();
    /// self.inner = Some(old.<method>(...));
    /// ```
    fn take_inner(&mut self) -> synta_mtc::builder::IssuanceLogBuilder<'static> {
        self.inner.take().unwrap_or_default()
    }

    /// Borrow the inner builder immutably.
    fn borrow_inner(&self) -> &synta_mtc::builder::IssuanceLogBuilder<'static> {
        self.inner
            .as_ref()
            .expect("IssuanceLogBuilder inner is None — this is a bug")
    }
}

#[pymethods]
impl PyIssuanceLogBuilder {
    /// Create a new ``IssuanceLogBuilder``.
    ///
    /// The builder is pre-populated with the mandatory null entry at index 0.
    #[new]
    fn new() -> Self {
        PyIssuanceLogBuilder {
            inner: Some(synta_mtc::builder::IssuanceLogBuilder::new()),
            _entry_bytes: Vec::new(),
        }
    }

    /// Set the hash algorithm used for all Merkle tree computations.
    ///
    /// :param algo: A :class:`HashAlgorithm` instance (e.g. ``HashAlgorithm.Sha256``).
    fn hash_algorithm(&mut self, algo: &PyHashAlgorithm) {
        let old = self.take_inner();
        self.inner = Some(old.hash_algorithm(algo.inner));
    }

    /// Set the log ID from a DER-encoded ``LogID`` SEQUENCE.
    ///
    /// :param log_id_der: DER bytes of a ``LogID`` structure.
    /// :raises ValueError: if *log_id_der* cannot be decoded as a ``LogID``.
    fn log_id(&mut self, log_id_der: &[u8]) -> PyResult<()> {
        let mut dec = synta::Decoder::new(log_id_der, synta::Encoding::Der);
        let lid = synta_mtc::types::LogID::decode(&mut dec)
            .map_err(|e| PyValueError::new_err(format!("invalid LogID DER: {e}")))?;
        // SAFETY: `lid` borrows from `log_id_der`, which is a Python bytes
        // object that lives at least as long as this call.  We immediately
        // encode the LogID back to owned bytes and store them so that the
        // 'static transmutation below is backed by stable heap memory.
        //
        // Re-encode to owned bytes so the log_id stored in the builder is
        // self-contained and does not depend on the caller's buffer lifetime.
        let mut enc = synta::Encoder::new(synta::Encoding::Der);
        lid.encode(&mut enc)
            .map_err(|e| PyValueError::new_err(format!("failed to re-encode LogID: {e}")))?;
        let owned: Box<[u8]> = enc
            .finish()
            .map_err(|e| PyValueError::new_err(format!("failed to finish LogID encoding: {e}")))?
            .into_boxed_slice();
        // Decode from the newly owned bytes; their heap address is stable
        // because they live in a `Box`.
        let owned_ptr: *const [u8] = &*owned;
        self._entry_bytes.push(owned);
        // SAFETY: `owned_bytes` is kept alive for the entire lifetime of
        // `self` via `self._entry_bytes`.  `Box` heap addresses do not move.
        let static_bytes: &'static [u8] = unsafe { &*owned_ptr };
        let mut dec2 = synta::Decoder::new(static_bytes, synta::Encoding::Der);
        let static_lid = synta_mtc::types::LogID::decode(&mut dec2)
            .map_err(|e| PyValueError::new_err(format!("failed to decode owned LogID: {e}")))?;
        let old = self.take_inner();
        self.inner = Some(old.log_id(static_lid));
        Ok(())
    }

    /// Set the minimum tree index for checkpoints (spec §7.5).
    ///
    /// :param idx: Non-negative integer; entries below this index are
    ///     considered pruned and appear in the checkpoint's
    ///     ``tree_minimum_index`` field.
    fn tree_minimum_index(&mut self, idx: u64) {
        let old = self.take_inner();
        self.inner = Some(old.tree_minimum_index(idx));
    }

    /// Add a ``TBSCertificateLogEntry`` from its DER encoding.
    ///
    /// :param tbs_cert_der: DER-encoded ``TBSCertificateLogEntry`` bytes.
    /// :raises ValueError: if *tbs_cert_der* cannot be decoded.
    fn add_entry(&mut self, tbs_cert_der: &[u8]) -> PyResult<()> {
        // Re-encode to guarantee ownership and alignment independence.
        let entry_tmp = {
            let mut dec = synta::Decoder::new(tbs_cert_der, synta::Encoding::Der);
            synta_mtc::types::TBSCertificateLogEntry::decode(&mut dec).map_err(|e| {
                PyValueError::new_err(format!("invalid TBSCertificateLogEntry DER: {e}"))
            })?
        };
        let mut enc = synta::Encoder::new(synta::Encoding::Der);
        entry_tmp
            .encode(&mut enc)
            .map_err(|e| PyValueError::new_err(format!("re-encode TBSCertificateLogEntry: {e}")))?;
        let owned: Box<[u8]> = enc
            .finish()
            .map_err(|e| {
                PyValueError::new_err(format!("finish TBSCertificateLogEntry encoding: {e}"))
            })?
            .into_boxed_slice();
        let owned_ptr: *const [u8] = &*owned;
        self._entry_bytes.push(owned);
        // SAFETY: `owned` is heap-allocated via Box, whose address is stable
        // (Vec reallocation only moves the pointer-array, not the Boxes).
        // The Box is kept alive in `self._entry_bytes` for the whole lifetime
        // of `self`.
        let static_bytes: &'static [u8] = unsafe { &*owned_ptr };
        let mut dec2 = synta::Decoder::new(static_bytes, synta::Encoding::Der);
        let static_entry =
            synta_mtc::types::TBSCertificateLogEntry::decode(&mut dec2).map_err(|e| {
                PyValueError::new_err(format!("decode owned TBSCertificateLogEntry: {e}"))
            })?;
        let old = self.take_inner();
        self.inner = Some(old.add_entry(static_entry));
        Ok(())
    }

    /// Return the current number of entries (including the mandatory null entry).
    fn tree_size(&self) -> u64 {
        self.borrow_inner().tree_size()
    }

    /// Compute the leaf hash for every entry.
    ///
    /// :returns: List of hash byte strings, one per entry (including index 0).
    /// :raises ValueError: if entry encoding or hashing fails.
    fn compute_leaf_hashes<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyList>> {
        let hashes = self
            .borrow_inner()
            .compute_leaf_hashes()
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        let items: Vec<Bound<'_, PyBytes>> = hashes.iter().map(|h| PyBytes::new(py, h)).collect();
        PyList::new(py, items)
    }

    /// Compute the Merkle tree root hash.
    ///
    /// :returns: Root hash bytes.
    /// :raises ValueError: if computation fails.
    fn compute_root<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        let root = self
            .borrow_inner()
            .compute_root()
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(PyBytes::new(py, &root))
    }

    /// Generate a checkpoint for the current log state using a Unix timestamp.
    ///
    /// A ``LogID`` must have been set via :meth:`log_id` before calling this.
    ///
    /// :param unix_secs: Seconds since 1970-01-01T00:00:00Z.
    /// :returns: DER-encoded ``Checkpoint`` bytes.
    /// :raises ValueError: if log_id is not set, *unix_secs* is out of range,
    ///     or DER encoding fails.
    fn checkpoint_at_unix<'py>(
        &self,
        py: Python<'py>,
        unix_secs: u64,
    ) -> PyResult<Bound<'py, PyBytes>> {
        let cp = self
            .borrow_inner()
            .checkpoint_at_unix(unix_secs)
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        let mut enc = synta::Encoder::new(synta::Encoding::Der);
        cp.encode(&mut enc)
            .map_err(|e| PyValueError::new_err(format!("encode Checkpoint: {e}")))?;
        let der = enc
            .finish()
            .map_err(|e| PyValueError::new_err(format!("finish Checkpoint encoding: {e}")))?;
        Ok(PyBytes::new(py, &der))
    }

    /// Generate an inclusion proof (sibling hash path) for a log entry.
    ///
    /// :param leaf_index: Absolute leaf index to prove (0 = null entry).
    /// :returns: List of sibling hash bytes, one per tree level.
    /// :raises ValueError: if *leaf_index* is out of bounds or hashing fails.
    fn generate_proof<'py>(
        &self,
        py: Python<'py>,
        leaf_index: u64,
    ) -> PyResult<Bound<'py, PyList>> {
        let path = self
            .borrow_inner()
            .generate_proof(leaf_index)
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        let items: Vec<Bound<'_, PyBytes>> = path.iter().map(|h| PyBytes::new(py, h)).collect();
        PyList::new(py, items)
    }

    /// Generate a subtree-relative inclusion proof for a single entry.
    ///
    /// The proof path is relative to the subtree ``[subtree_start, subtree_end)``
    /// rather than the full tree.
    ///
    /// :param leaf_index: Absolute index of the entry in the log.
    /// :param subtree_start: Start of the subtree (inclusive).
    /// :param subtree_end: End of the subtree (exclusive).
    /// :returns: List of sibling hash bytes for the subtree-relative proof.
    /// :raises ValueError: if the range is invalid, *leaf_index* is outside
    ///     the subtree, or hashing fails.
    fn generate_subtree_proof<'py>(
        &self,
        py: Python<'py>,
        leaf_index: u64,
        subtree_start: u64,
        subtree_end: u64,
    ) -> PyResult<Bound<'py, PyList>> {
        let path = self
            .borrow_inner()
            .generate_subtree_proof(leaf_index, subtree_start, subtree_end)
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        let items: Vec<Bound<'_, PyBytes>> = path.iter().map(|h| PyBytes::new(py, h)).collect();
        PyList::new(py, items)
    }

    /// Generate subtree-relative proofs for all entries in a subtree.
    ///
    /// Batch version of :meth:`generate_subtree_proof`.  Returns one proof
    /// (a ``list[bytes]`` of sibling hashes) per entry in
    /// ``[subtree_start, subtree_end)``.
    ///
    /// :param subtree_start: Start of the subtree (inclusive).
    /// :param subtree_end: End of the subtree (exclusive).
    /// :returns: List of proofs, each itself a ``list[bytes]``.
    /// :raises ValueError: if the range is invalid or hashing fails.
    fn generate_all_subtree_proofs<'py>(
        &self,
        py: Python<'py>,
        subtree_start: u64,
        subtree_end: u64,
    ) -> PyResult<Bound<'py, PyList>> {
        let proofs = self
            .borrow_inner()
            .generate_all_subtree_proofs(subtree_start, subtree_end)
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        let outer: Vec<Bound<'_, PyList>> = proofs
            .iter()
            .map(|proof| {
                let inner: Vec<Bound<'_, PyBytes>> =
                    proof.iter().map(|h| PyBytes::new(py, h)).collect();
                PyList::new(py, inner)
            })
            .collect::<PyResult<Vec<_>>>()?;
        PyList::new(py, outer)
    }

    /// Build the log, consuming the builder.
    ///
    /// :returns: The Merkle root hash bytes.  All accumulated entries have
    ///     been validated and the tree structure is finalised.
    /// :raises ValueError: if root computation fails.
    ///
    /// .. note::
    ///
    ///     After calling :meth:`build` the builder is reset to its initial
    ///     state (containing only the mandatory null entry).  Previously
    ///     added entries are no longer accessible.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        let old = self.take_inner();
        let (_entries, root) = old
            .build()
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(PyBytes::new(py, &root))
    }

    fn __repr__(&self) -> String {
        format!(
            "IssuanceLogBuilder(tree_size={})",
            self.inner.as_ref().map(|b| b.tree_size()).unwrap_or(0)
        )
    }
}

// ── MtcX509CertificateBuilder ─────────────────────────────────────────────────

/// Builder for a spec-compliant X.509 MTC certificate (draft-ietf-plants-merkle-tree-certs §5).
///
/// Constructs a standard X.509 ``Certificate`` where:
///
/// - ``signatureAlgorithm`` = ``id-alg-mtcProof`` (experimental OID)
/// - ``signatureValue`` = TLS-encoded ``MTCProof`` (spec §4.3)
/// - ``serialNumber`` = ``(log_number << 48) | log_entry_index`` (spec §6.1)
/// - ``issuer`` = ``LogID`` encoded as a single-attribute DN
///
/// The ``subject``, ``validity``, ``subjectPublicKeyInfo``, and ``extensions``
/// fields are copied from the original ``TBSCertificate`` supplied via
/// :meth:`original_tbs_der`.
///
/// ```python,ignore
/// import synta.mtc as mtc
///
/// proof = mtc.MtcProof.decode(raw_proof_bytes)
///
/// cert_der = (
///     mtc.MtcX509CertificateBuilder.new()
///     .original_tbs_der(tbs_der)
///     .log_id(log_id_der)
///     .log_entry_index(leaf_idx)
///     .log_number(log_num)
///     .mtc_proof(proof)
///     .build()
/// )
/// ```
#[pyclass(name = "MtcX509CertificateBuilder")]
pub struct PyMtcX509CertificateBuilder {
    /// Owned copy of the original TBSCertificate DER bytes.
    original_tbs_der: Option<Box<[u8]>>,
    /// Owned copy of the re-encoded LogID DER bytes.
    log_id_der: Option<Box<[u8]>>,
    /// Log entry index (lower 48 bits of serialNumber).
    log_entry_index: Option<u64>,
    /// Log number (upper 16 bits of serialNumber); defaults to 0.
    log_number: Option<u16>,
    /// Owned MTC proof.
    mtc_proof: Option<MtcProof>,
}

#[pymethods]
impl PyMtcX509CertificateBuilder {
    /// Create a new ``MtcX509CertificateBuilder`` with no fields set.
    #[staticmethod]
    fn new() -> Self {
        PyMtcX509CertificateBuilder {
            original_tbs_der: None,
            log_id_der: None,
            log_entry_index: None,
            log_number: None,
            mtc_proof: None,
        }
    }

    /// Set the DER-encoded original ``TBSCertificate``.
    ///
    /// The ``subject``, ``validity``, ``subjectPublicKeyInfo``, and
    /// ``extensions`` fields are copied from this TBS into the produced
    /// certificate.  All other fields (``issuer``, ``serialNumber``,
    /// ``signatureAlgorithm``) are set by the builder.
    ///
    /// :param tbs: DER-encoded ``TBSCertificate`` bytes.
    fn original_tbs_der<'py>(slf: Bound<'py, Self>, tbs: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().original_tbs_der = Some(tbs.to_vec().into_boxed_slice());
        slf
    }

    /// Set the log identifier (encoded as the ``issuer`` distinguished name).
    ///
    /// :param log_id: DER-encoded ``LogID`` SEQUENCE bytes.
    /// :raises ValueError: if *log_id* cannot be decoded as a ``LogID``.
    fn log_id<'py>(slf: Bound<'py, Self>, log_id: &[u8]) -> PyResult<Bound<'py, Self>> {
        // Decode, then re-encode to guarantee an owned, stable heap buffer.
        let lid = {
            let mut dec = synta::Decoder::new(log_id, synta::Encoding::Der);
            synta_mtc::types::LogID::decode(&mut dec)
                .map_err(|e| PyValueError::new_err(format!("invalid LogID DER: {e}")))?
        };
        let mut enc = synta::Encoder::new(synta::Encoding::Der);
        lid.encode(&mut enc)
            .map_err(|e| PyValueError::new_err(format!("re-encode LogID: {e}")))?;
        let owned: Box<[u8]> = enc
            .finish()
            .map_err(|e| PyValueError::new_err(format!("finish LogID encoding: {e}")))?
            .into_boxed_slice();
        slf.borrow_mut().log_id_der = Some(owned);
        Ok(slf)
    }

    /// Set the log entry index (lower 48 bits of ``serialNumber`` per §6.1).
    ///
    /// :param idx: Non-negative integer leaf index.
    fn log_entry_index<'py>(slf: Bound<'py, Self>, idx: u64) -> Bound<'py, Self> {
        slf.borrow_mut().log_entry_index = Some(idx);
        slf
    }

    /// Set the log number (upper 16 bits of ``serialNumber`` per §6.1).
    ///
    /// Defaults to ``0`` when not set.
    ///
    /// :param num: Log number (0–65535).
    fn log_number<'py>(slf: Bound<'py, Self>, num: u16) -> Bound<'py, Self> {
        slf.borrow_mut().log_number = Some(num);
        slf
    }

    /// Set the MTC proof to embed as ``signatureValue``.
    ///
    /// :param proof: An :class:`MtcProof` instance obtained via
    ///     :meth:`MtcProof.decode`.
    fn mtc_proof<'py>(slf: Bound<'py, Self>, proof: &PyMtcProof) -> PyResult<Bound<'py, Self>> {
        // Reconstruct MtcProof from the Python wrapper's fields.
        let signatures: Vec<MtcSignature> = proof
            .signatures
            .iter()
            .map(|s| {
                let s = s.get();
                MtcSignature {
                    cosigner_id: s.cosigner_id.clone(),
                    signature_value: s.signature_value.clone(),
                }
            })
            .collect();
        let inner_proof = MtcProof {
            extensions: proof.extensions.clone(),
            start: proof.start,
            end: proof.end,
            inclusion_proof: proof.inclusion_proof.clone(),
            signatures,
        };
        slf.borrow_mut().mtc_proof = Some(inner_proof);
        Ok(slf)
    }

    /// Build and DER-encode the spec-compliant X.509 MTC certificate.
    ///
    /// :returns: DER-encoded ``Certificate`` bytes.
    /// :raises ValueError: if any required field (``original_tbs_der``,
    ///     ``log_id``, ``log_entry_index``, ``mtc_proof``) is absent, if the
    ///     original TBS cannot be parsed, or if DER encoding fails.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        let tbs_box = self
            .original_tbs_der
            .as_ref()
            .ok_or_else(|| PyValueError::new_err("original_tbs_der is required"))?;
        let lid_box = self
            .log_id_der
            .as_ref()
            .ok_or_else(|| PyValueError::new_err("log_id is required"))?;
        let log_entry_index = self
            .log_entry_index
            .ok_or_else(|| PyValueError::new_err("log_entry_index is required"))?;
        let mtc_proof = self
            .mtc_proof
            .take()
            .ok_or_else(|| PyValueError::new_err("mtc_proof is required"))?;

        let tbs_bytes: &[u8] = tbs_box;
        let lid_bytes: &[u8] = lid_box;

        // Decode the owned LogID bytes.
        let log_id = {
            // SAFETY: `lid_bytes` points into a Box<[u8]> owned by `self`
            // for the duration of this synchronous call.  The transmutation
            // to 'static is immediately consumed by the builder without
            // escaping this stack frame.
            let static_lid: &'static [u8] = unsafe { &*(lid_bytes as *const [u8]) };
            let mut dec = synta::Decoder::new(static_lid, synta::Encoding::Der);
            synta_mtc::types::LogID::decode(&mut dec)
                .map_err(|e| PyValueError::new_err(format!("decode owned LogID: {e}")))?
        };

        // SAFETY: `tbs_bytes` points into a Box<[u8]> owned by `self` for
        // the duration of this synchronous call.
        let static_tbs: &'static [u8] = unsafe { &*(tbs_bytes as *const [u8]) };

        let mut rust_builder = synta_mtc::builder::MtcX509CertificateBuilder::new()
            .original_tbs_der(static_tbs)
            .log_id(log_id)
            .log_entry_index(log_entry_index)
            .mtc_proof(mtc_proof);

        if let Some(n) = self.log_number {
            rust_builder = rust_builder.log_number(n);
        }

        let der = rust_builder
            .build()
            .map_err(|e| PyValueError::new_err(e.to_string()))?;

        // Restore mtc_proof slot to None (it was consumed).
        // All other fields remain for potential re-use.
        Ok(PyBytes::new(py, &der))
    }

    fn __repr__(&self) -> String {
        "MtcX509CertificateBuilder()".to_string()
    }
}

// ── StandaloneCertificateBuilder ──────────────────────────────────────────────

/// Builder for a ``StandaloneCertificate`` (MTC certificate with a Merkle inclusion proof).
///
/// Constructs a ``StandaloneCertificate`` DER encoding from its constituent parts.
/// Call :meth:`build` to obtain the final DER bytes.
///
/// ```python,ignore
/// import synta.mtc as mtc
///
/// cert_der = (
///     mtc.StandaloneCertificateBuilder()
///     .tbs_certificate(tbs_der)
///     .log_entry_index(leaf_idx)
///     .tree_leaves(leaf_hashes)
///     .hash_algorithm(mtc.HashAlgorithm.Sha256)
///     .signature_algorithm(sig_alg_der)
///     .signature(sig_bytes)
///     .build()
/// )
/// ```
#[pyclass(name = "StandaloneCertificateBuilder")]
pub struct PyStandaloneCertificateBuilder {
    /// Owned DER bytes for the TBSCertificate.
    tbs_der: Option<Box<[u8]>>,
    /// Zero-based index of this certificate in the log.
    log_entry_index: Option<u64>,
    /// Hash algorithm to use for proof generation.
    hash_algorithm: HashAlgorithm,
    /// Pre-computed inclusion proof path (bypasses tree_leaves when set).
    precomputed_proof: Option<Vec<Vec<u8>>>,
    /// Subtree start index for the precomputed proof (default 0).
    precomputed_subtree_start: u64,
    /// Subtree end index (exclusive) for the precomputed proof.
    precomputed_subtree_end: Option<u64>,
    /// All leaf hashes for on-demand proof generation.
    tree_leaves: Vec<Vec<u8>>,
    /// Owned DER bytes for the SubtreeProof (``None`` → default empty proof).
    subtree_proof_der: Option<Box<[u8]>>,
    /// Owned DER bytes for each SubtreeSignature.
    subtree_signatures_der: Vec<Box<[u8]>>,
    /// Owned DER bytes for the outer AlgorithmIdentifier.
    sig_alg_der: Option<Box<[u8]>>,
    /// Raw signature bytes (BIT STRING value; unused-bits byte added automatically).
    signature_bytes: Option<Vec<u8>>,
    /// Keeps heap addresses stable; borrowed by builder entries during `build()`.
    _owned_bufs: Vec<Box<[u8]>>,
}

#[pymethods]
impl PyStandaloneCertificateBuilder {
    /// Create a new ``StandaloneCertificateBuilder`` with default settings.
    #[new]
    fn new() -> Self {
        PyStandaloneCertificateBuilder {
            tbs_der: None,
            log_entry_index: None,
            hash_algorithm: HashAlgorithm::Sha256,
            precomputed_proof: None,
            precomputed_subtree_start: 0,
            precomputed_subtree_end: None,
            tree_leaves: Vec::new(),
            subtree_proof_der: None,
            subtree_signatures_der: Vec::new(),
            sig_alg_der: None,
            signature_bytes: None,
            _owned_bufs: Vec::new(),
        }
    }

    /// Set the DER-encoded ``TBSCertificate``.
    ///
    /// :param tbs: DER-encoded ``TBSCertificate`` bytes.
    fn tbs_certificate<'py>(slf: Bound<'py, Self>, tbs: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().tbs_der = Some(tbs.to_vec().into_boxed_slice());
        slf
    }

    /// Set the zero-based log entry index.
    ///
    /// :param idx: Leaf index of this certificate in the issuance log.
    fn log_entry_index<'py>(slf: Bound<'py, Self>, idx: u64) -> Bound<'py, Self> {
        slf.borrow_mut().log_entry_index = Some(idx);
        slf
    }

    /// Set the hash algorithm used for proof generation.
    ///
    /// Defaults to SHA-256 when not set.
    ///
    /// :param algo: A :class:`HashAlgorithm` instance.
    fn hash_algorithm<'py>(slf: Bound<'py, Self>, algo: &PyHashAlgorithm) -> Bound<'py, Self> {
        slf.borrow_mut().hash_algorithm = algo.inner;
        slf
    }

    /// Provide a pre-computed inclusion proof path with explicit subtree bounds.
    ///
    /// Use when the certificate covers subtree ``[start, end)`` rather than the
    /// full tree.  When this is set, :meth:`tree_leaves` is ignored.
    ///
    /// :param path: List of sibling hash bytes (one per tree level).
    /// :param start: Subtree start index (inclusive).
    /// :param end: Subtree end index (exclusive).
    fn with_proof_path<'py>(
        slf: Bound<'py, Self>,
        path: Vec<Vec<u8>>,
        start: u64,
        end: u64,
    ) -> Bound<'py, Self> {
        let mut inner = slf.borrow_mut();
        inner.precomputed_proof = Some(path);
        inner.precomputed_subtree_start = start;
        inner.precomputed_subtree_end = Some(end);
        drop(inner);
        slf
    }

    /// Provide a pre-computed full-tree inclusion proof.
    ///
    /// Equivalent to ``with_proof_path(path, 0, tree_size)``.
    ///
    /// :param path: List of sibling hash bytes (one per tree level).
    /// :param tree_size: Total number of leaves in the tree.
    fn with_full_tree_proof<'py>(
        slf: Bound<'py, Self>,
        path: Vec<Vec<u8>>,
        tree_size: u64,
    ) -> Bound<'py, Self> {
        let mut inner = slf.borrow_mut();
        inner.precomputed_proof = Some(path);
        inner.precomputed_subtree_start = 0;
        inner.precomputed_subtree_end = Some(tree_size);
        drop(inner);
        slf
    }

    /// Set all leaf hashes used for on-demand inclusion proof generation.
    ///
    /// Ignored when :meth:`with_proof_path` or :meth:`with_full_tree_proof`
    /// has been called.
    ///
    /// :param leaves: List of leaf hash byte strings (one per log entry).
    fn tree_leaves<'py>(slf: Bound<'py, Self>, leaves: Vec<Vec<u8>>) -> Bound<'py, Self> {
        slf.borrow_mut().tree_leaves = leaves;
        slf
    }

    /// Set the DER-encoded ``SubtreeProof``.
    ///
    /// When not set, an empty (default) subtree proof is used.
    ///
    /// :param proof_der: DER-encoded ``SubtreeProof`` SEQUENCE bytes.
    fn subtree_proof<'py>(slf: Bound<'py, Self>, proof_der: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().subtree_proof_der = Some(proof_der.to_vec().into_boxed_slice());
        slf
    }

    /// Add a DER-encoded ``SubtreeSignature`` cosignature.
    ///
    /// May be called multiple times to accumulate signatures.
    ///
    /// :param sig_der: DER-encoded ``SubtreeSignature`` SEQUENCE bytes.
    fn add_subtree_signature<'py>(slf: Bound<'py, Self>, sig_der: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut()
            .subtree_signatures_der
            .push(sig_der.to_vec().into_boxed_slice());
        slf
    }

    /// Set the DER-encoded outer ``AlgorithmIdentifier`` for the signature.
    ///
    /// :param alg_der: DER-encoded ``AlgorithmIdentifier`` SEQUENCE TLV bytes.
    fn signature_algorithm<'py>(slf: Bound<'py, Self>, alg_der: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().sig_alg_der = Some(alg_der.to_vec().into_boxed_slice());
        slf
    }

    /// Set the raw signature bytes.
    ///
    /// :param sig: Raw signature bytes (BIT STRING value; unused-bits byte
    ///     is added automatically).
    fn signature<'py>(slf: Bound<'py, Self>, sig: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().signature_bytes = Some(sig.to_vec());
        slf
    }

    /// Build the DER-encoded ``StandaloneCertificate`` SEQUENCE.
    ///
    /// :returns: DER bytes of the complete ``StandaloneCertificate``.
    /// :raises ValueError: if any required field is absent, DER decoding of a
    ///     supplied field fails, or encoding fails.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        use synta::BitString;
        use synta_certificate::{AlgorithmIdentifier, TBSCertificate};
        use synta_mtc::builder::StandaloneCertificateBuilder;
        use synta_mtc::types::{SubtreeProof, SubtreeSignature};

        // Validate required fields early.
        let tbs_box = self
            .tbs_der
            .as_ref()
            .ok_or_else(|| PyValueError::new_err("tbs_certificate is required"))?;
        let sig_alg_box = self
            .sig_alg_der
            .as_ref()
            .ok_or_else(|| PyValueError::new_err("signature_algorithm is required"))?;
        let sig_bytes = self
            .signature_bytes
            .as_ref()
            .ok_or_else(|| PyValueError::new_err("signature is required"))?;
        if self.log_entry_index.is_none() {
            return Err(PyValueError::new_err("log_entry_index is required"));
        }
        let log_entry_index = self.log_entry_index.unwrap();

        // Decode TBSCertificate from owned stable buffer.
        // SAFETY: `tbs_box` lives in `self` for the duration of this synchronous call.
        let tbs_ptr: *const [u8] = &**tbs_box;
        let static_tbs_bytes: &'static [u8] = unsafe { &*tbs_ptr };
        let tbs_cert = {
            let mut dec = synta::Decoder::new(static_tbs_bytes, synta::Encoding::Der);
            TBSCertificate::decode(&mut dec)
                .map_err(|e| PyValueError::new_err(format!("invalid TBSCertificate DER: {e}")))?
        };

        // Decode AlgorithmIdentifier from owned stable buffer.
        // SAFETY: `sig_alg_box` lives in `self` for the duration of this synchronous call.
        let alg_ptr: *const [u8] = &**sig_alg_box;
        let static_alg_bytes: &'static [u8] = unsafe { &*alg_ptr };
        let sig_alg = {
            let mut dec = synta::Decoder::new(static_alg_bytes, synta::Encoding::Der);
            AlgorithmIdentifier::decode(&mut dec).map_err(|e| {
                PyValueError::new_err(format!("invalid AlgorithmIdentifier DER: {e}"))
            })?
        };

        // Construct BitString for the signature.
        let signature = BitString::new(sig_bytes.clone(), 0)
            .map_err(|e| PyValueError::new_err(format!("invalid signature bytes: {e}")))?;

        // Decode SubtreeProof (default if not provided).
        let subtree_proof = if let Some(ref sp_box) = self.subtree_proof_der {
            let sp_ptr: *const [u8] = &**sp_box;
            let static_sp_bytes: &'static [u8] = unsafe { &*sp_ptr };
            let mut dec = synta::Decoder::new(static_sp_bytes, synta::Encoding::Der);
            SubtreeProof::decode(&mut dec)
                .map_err(|e| PyValueError::new_err(format!("invalid SubtreeProof DER: {e}")))?
        } else {
            SubtreeProof::default()
        };

        // Decode all SubtreeSignatures from their stable owned buffers.
        // Keep the boxes alive on the stack so the decoded 'static refs remain valid.
        let mut subtree_signatures: Vec<SubtreeSignature<'static>> = Vec::new();
        for sig_box in &self.subtree_signatures_der {
            let ss_ptr: *const [u8] = &**sig_box;
            // SAFETY: each `sig_box` lives in `self` for this synchronous call.
            let static_ss_bytes: &'static [u8] = unsafe { &*ss_ptr };
            let mut dec = synta::Decoder::new(static_ss_bytes, synta::Encoding::Der);
            let ss = SubtreeSignature::decode(&mut dec)
                .map_err(|e| PyValueError::new_err(format!("invalid SubtreeSignature DER: {e}")))?;
            subtree_signatures.push(ss);
        }

        // Build the Rust StandaloneCertificateBuilder.
        let mut rust_builder = StandaloneCertificateBuilder::new()
            .tbs_certificate(tbs_cert)
            .log_entry_index(log_entry_index)
            .hash_algorithm(self.hash_algorithm)
            .subtree_proof(subtree_proof)
            .subtree_signatures(subtree_signatures)
            .signature_algorithm(sig_alg)
            .signature(signature);

        if let (Some(path), Some(end)) =
            (self.precomputed_proof.clone(), self.precomputed_subtree_end)
        {
            rust_builder = rust_builder.with_proof_path(path, self.precomputed_subtree_start, end);
        } else {
            rust_builder = rust_builder.tree_leaves(self.tree_leaves.clone());
        }

        let cert = rust_builder
            .build()
            .map_err(|e| PyValueError::new_err(e.to_string()))?;

        let mut enc = synta::Encoder::new(synta::Encoding::Der);
        cert.encode(&mut enc)
            .map_err(|e| PyValueError::new_err(format!("encode StandaloneCertificate: {e}")))?;
        let der = enc
            .finish()
            .map_err(|e| PyValueError::new_err(format!("finish StandaloneCertificate: {e}")))?;

        Ok(PyBytes::new(py, &der))
    }

    fn __repr__(&self) -> String {
        "StandaloneCertificateBuilder()".to_string()
    }
}

// ── LandmarkCertificateBuilder ────────────────────────────────────────────────

/// Builder for a ``LandmarkCertificate`` (MTC landmark certificate).
///
/// Constructs a ``LandmarkCertificate`` DER encoding from its constituent parts.
/// Call :meth:`build` to obtain the final DER bytes.
///
/// ```python,ignore
/// import synta.mtc as mtc
///
/// cert_der = (
///     mtc.LandmarkCertificateBuilder()
///     .tbs_certificate(tbs_der)
///     .log_entry_index(leaf_idx)
///     .tree_leaves(leaf_hashes)
///     .landmark_id(landmark_id_der)
///     .hash_algorithm(mtc.HashAlgorithm.Sha256)
///     .signature_algorithm(sig_alg_der)
///     .signature(sig_bytes)
///     .build()
/// )
/// ```
#[pyclass(name = "LandmarkCertificateBuilder")]
pub struct PyLandmarkCertificateBuilder {
    /// Owned DER bytes for the TBSCertificate.
    tbs_der: Option<Box<[u8]>>,
    /// Zero-based index of this certificate in the log.
    log_entry_index: Option<u64>,
    /// Hash algorithm to use for proof generation.
    hash_algorithm: HashAlgorithm,
    /// All leaf hashes in the tree for on-demand proof generation.
    tree_leaves: Vec<Vec<u8>>,
    /// Owned DER bytes for the LandmarkID.
    landmark_id_der: Option<Box<[u8]>>,
    /// Owned DER bytes for the outer AlgorithmIdentifier.
    sig_alg_der: Option<Box<[u8]>>,
    /// Raw signature bytes (BIT STRING value; unused-bits byte added automatically).
    signature_bytes: Option<Vec<u8>>,
}

#[pymethods]
impl PyLandmarkCertificateBuilder {
    /// Create a new ``LandmarkCertificateBuilder`` with default settings.
    #[new]
    fn new() -> Self {
        PyLandmarkCertificateBuilder {
            tbs_der: None,
            log_entry_index: None,
            hash_algorithm: HashAlgorithm::Sha256,
            tree_leaves: Vec::new(),
            landmark_id_der: None,
            sig_alg_der: None,
            signature_bytes: None,
        }
    }

    /// Set the DER-encoded ``TBSCertificate``.
    ///
    /// :param tbs: DER-encoded ``TBSCertificate`` bytes.
    fn tbs_certificate<'py>(slf: Bound<'py, Self>, tbs: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().tbs_der = Some(tbs.to_vec().into_boxed_slice());
        slf
    }

    /// Set the zero-based log entry index.
    ///
    /// :param idx: Leaf index of this certificate in the issuance log.
    fn log_entry_index<'py>(slf: Bound<'py, Self>, idx: u64) -> Bound<'py, Self> {
        slf.borrow_mut().log_entry_index = Some(idx);
        slf
    }

    /// Set the hash algorithm used for proof generation.
    ///
    /// Defaults to SHA-256 when not set.
    ///
    /// :param algo: A :class:`HashAlgorithm` instance.
    fn hash_algorithm<'py>(slf: Bound<'py, Self>, algo: &PyHashAlgorithm) -> Bound<'py, Self> {
        slf.borrow_mut().hash_algorithm = algo.inner;
        slf
    }

    /// Set all leaf hashes in the tree (used for inclusion proof generation).
    ///
    /// :param leaves: List of leaf hash byte strings (one per log entry).
    fn tree_leaves<'py>(slf: Bound<'py, Self>, leaves: Vec<Vec<u8>>) -> Bound<'py, Self> {
        slf.borrow_mut().tree_leaves = leaves;
        slf
    }

    /// Set the DER-encoded ``LandmarkID``.
    ///
    /// :param landmark_id: DER-encoded ``LandmarkID`` SEQUENCE bytes.
    fn landmark_id<'py>(slf: Bound<'py, Self>, landmark_id: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().landmark_id_der = Some(landmark_id.to_vec().into_boxed_slice());
        slf
    }

    /// Set the DER-encoded outer ``AlgorithmIdentifier`` for the signature.
    ///
    /// :param alg_der: DER-encoded ``AlgorithmIdentifier`` SEQUENCE TLV bytes.
    fn signature_algorithm<'py>(slf: Bound<'py, Self>, alg_der: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().sig_alg_der = Some(alg_der.to_vec().into_boxed_slice());
        slf
    }

    /// Set the raw signature bytes.
    ///
    /// :param sig: Raw signature bytes (BIT STRING value; unused-bits byte
    ///     is added automatically).
    fn signature<'py>(slf: Bound<'py, Self>, sig: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().signature_bytes = Some(sig.to_vec());
        slf
    }

    /// Build the DER-encoded ``LandmarkCertificate`` SEQUENCE.
    ///
    /// :returns: DER bytes of the complete ``LandmarkCertificate``.
    /// :raises ValueError: if any required field is absent, DER decoding of a
    ///     supplied field fails, or encoding fails.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        use synta::BitString;
        use synta_certificate::{AlgorithmIdentifier, TBSCertificate};
        use synta_mtc::builder::LandmarkCertificateBuilder;
        use synta_mtc::types::LandmarkID;

        // Validate required fields early.
        let tbs_box = self
            .tbs_der
            .as_ref()
            .ok_or_else(|| PyValueError::new_err("tbs_certificate is required"))?;
        let sig_alg_box = self
            .sig_alg_der
            .as_ref()
            .ok_or_else(|| PyValueError::new_err("signature_algorithm is required"))?;
        let landmark_id_box = self
            .landmark_id_der
            .as_ref()
            .ok_or_else(|| PyValueError::new_err("landmark_id is required"))?;
        let sig_bytes = self
            .signature_bytes
            .as_ref()
            .ok_or_else(|| PyValueError::new_err("signature is required"))?;
        if self.log_entry_index.is_none() {
            return Err(PyValueError::new_err("log_entry_index is required"));
        }
        let log_entry_index = self.log_entry_index.unwrap();

        // Decode TBSCertificate from owned stable buffer.
        // SAFETY: `tbs_box` lives in `self` for the duration of this synchronous call.
        let tbs_ptr: *const [u8] = &**tbs_box;
        let static_tbs_bytes: &'static [u8] = unsafe { &*tbs_ptr };
        let tbs_cert = {
            let mut dec = synta::Decoder::new(static_tbs_bytes, synta::Encoding::Der);
            TBSCertificate::decode(&mut dec)
                .map_err(|e| PyValueError::new_err(format!("invalid TBSCertificate DER: {e}")))?
        };

        // Decode AlgorithmIdentifier from owned stable buffer.
        // SAFETY: `sig_alg_box` lives in `self` for the duration of this synchronous call.
        let alg_ptr: *const [u8] = &**sig_alg_box;
        let static_alg_bytes: &'static [u8] = unsafe { &*alg_ptr };
        let sig_alg = {
            let mut dec = synta::Decoder::new(static_alg_bytes, synta::Encoding::Der);
            AlgorithmIdentifier::decode(&mut dec).map_err(|e| {
                PyValueError::new_err(format!("invalid AlgorithmIdentifier DER: {e}"))
            })?
        };

        // Decode LandmarkID from owned stable buffer.
        // SAFETY: `landmark_id_box` lives in `self` for the duration of this synchronous call.
        let lid_ptr: *const [u8] = &**landmark_id_box;
        let static_lid_bytes: &'static [u8] = unsafe { &*lid_ptr };
        let landmark_id = {
            let mut dec = synta::Decoder::new(static_lid_bytes, synta::Encoding::Der);
            LandmarkID::decode(&mut dec)
                .map_err(|e| PyValueError::new_err(format!("invalid LandmarkID DER: {e}")))?
        };

        // Construct BitString for the signature.
        let signature = BitString::new(sig_bytes.clone(), 0)
            .map_err(|e| PyValueError::new_err(format!("invalid signature bytes: {e}")))?;

        let cert = LandmarkCertificateBuilder::new()
            .tbs_certificate(tbs_cert)
            .log_entry_index(log_entry_index)
            .tree_leaves(self.tree_leaves.clone())
            .hash_algorithm(self.hash_algorithm)
            .landmark_id(landmark_id)
            .signature_algorithm(sig_alg)
            .signature(signature)
            .build()
            .map_err(|e| PyValueError::new_err(e.to_string()))?;

        let mut enc = synta::Encoder::new(synta::Encoding::Der);
        cert.encode(&mut enc)
            .map_err(|e| PyValueError::new_err(format!("encode LandmarkCertificate: {e}")))?;
        let der = enc
            .finish()
            .map_err(|e| PyValueError::new_err(format!("finish LandmarkCertificate: {e}")))?;

        Ok(PyBytes::new(py, &der))
    }

    fn __repr__(&self) -> String {
        "LandmarkCertificateBuilder()".to_string()
    }
}