synta-python-mtc 0.2.1

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
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
//! Python bindings for synta.mtc — Merkle Tree Certificate (MTC) ASN.1 types.
//!
//! Exposes ``synta.mtc`` — a submodule containing all ASN.1 types from the MTC
//! specification (draft-ietf-plants-merkle-tree-certs), decoded from DER.
//!
//! # Classes
//!
//! | Python name                | Schema type                | Description                         |
//! |----------------------------|----------------------------|-------------------------------------|
//! | `ProofNode`                | `ProofNode`                | Left/right hash in inclusion path   |
//! | `Subtree`                  | `Subtree`                  | Hash subtree range                  |
//! | `SubtreeProof`             | `SubtreeProof`             | Left + right subtrees               |
//! | `InclusionProof`           | `InclusionProof`           | Log inclusion proof                 |
//! | `LogID`                    | `LogID`                    | Log identifier (hash alg + pubkey)  |
//! | `CosignerID`               | `CosignerID`               | Cosigner identity                   |
//! | `Checkpoint`               | `Checkpoint`               | Signed tree checkpoint              |
//! | `SubtreeSignature`         | `SubtreeSignature`         | Cosigner subtree signature          |
//! | `TbsCertificateLogEntry`   | `TBSCertificateLogEntry`   | Log entry for a certificate         |
//! | `MerkleTreeCertEntry`      | `MerkleTreeCertEntry`      | CHOICE: null or TBS entry           |
//! | `LandmarkID`               | `LandmarkID`               | Landmark log identifier             |
//! | `StandaloneCertificate`    | `StandaloneCertificate`    | Full standalone MTC certificate     |
//! | `LandmarkCertificate`      | `LandmarkCertificate`      | Landmark certificate                |

use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyList};
use synta::traits::{Decode, Encode};
use synta_mtc::types::{
    CosignerID, InclusionProof, LandmarkCertificate, LandmarkID, LogID, MerkleTreeCertEntry,
    ProofNode, StandaloneCertificate, Subtree, SubtreeProof, SubtreeSignature,
    TBSCertificateLogEntry,
};
// The local MTC Name type (CHOICE wrapping RDNSequence), aliased to avoid clash.
use synta_mtc::types::Name as MtcName;

use synta_python_common::{opt_py_list, SyntaErr};

// ── Encoding helpers ──────────────────────────────────────────────────────────

/// Encode any ASN.1 value implementing Encode to DER bytes.
fn encode_to_der<T: Encode>(val: &T) -> PyResult<Vec<u8>> {
    let mut enc = synta::Encoder::new(synta::Encoding::Der);
    val.encode(&mut enc).map_err(SyntaErr)?;
    Ok(enc.finish().map_err(SyntaErr)?)
}

/// Extract the dotted-decimal OID string from an AlgorithmIdentifier.
fn alg_oid_str(alg: &synta_certificate::AlgorithmIdentifier<'_>) -> String {
    alg.algorithm.to_string()
}

/// Encode a SubjectPublicKeyInfo to raw DER bytes.
fn spki_to_der(spki: &synta_certificate::SubjectPublicKeyInfo<'_>) -> PyResult<Vec<u8>> {
    encode_to_der(spki)
}

/// Encode a TBSCertificate to raw DER bytes.
fn tbs_cert_to_der(tbs: &synta_certificate::TBSCertificate<'_>) -> PyResult<Vec<u8>> {
    encode_to_der(tbs)
}

/// Format a Validity Time value as a GeneralizedTime string.
fn time_to_str(t: &synta_certificate::Time) -> String {
    match t {
        synta_certificate::Time::UtcTime(t) => t.to_string(),
        synta_certificate::Time::GeneralTime(t) => t.to_string(),
    }
}

/// Convert synta Integer to i64, propagating errors.
fn int_to_i64(i: &synta::Integer) -> PyResult<i64> {
    Ok(i.as_i64().map_err(SyntaErr)?)
}

/// Encode a local MTC Name (CHOICE RDNSequence) to DER bytes.
fn mtc_name_to_der(name: &MtcName) -> PyResult<Vec<u8>> {
    encode_to_der(name)
}

// ── ProofNode ─────────────────────────────────────────────────────────────────

/// A node in a Merkle inclusion proof path.
///
/// Per draft-ietf-plants-merkle-tree-certs §4.3.2, direction is computed
/// from the leaf index at each level; the proof node contains only the
/// sibling hash bytes.  ``hash`` is the raw hash bytes.
///
/// Example:
///
/// ```python,ignore
/// import synta.mtc as mtc
///
/// node = mtc.ProofNode.from_der(der_bytes)
/// print(node.hash.hex())
/// ```
#[pyclass(frozen, name = "ProofNode")]
pub struct PyProofNode {
    hash: Vec<u8>,
}

#[pymethods]
impl PyProofNode {
    /// Parse a DER-encoded ``ProofNode`` OCTET STRING.
    #[staticmethod]
    pub fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let node = ProofNode::decode(&mut dec).map_err(SyntaErr)?;
        Ok(PyProofNode {
            hash: node.as_bytes().to_vec(),
        })
    }

    /// Raw sibling hash bytes at this proof node.
    #[getter]
    fn hash<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.hash)
    }

    fn __repr__(&self) -> String {
        format!("ProofNode(hash_len={})", self.hash.len())
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.hash == other.hash
    }
}

// ── Subtree ───────────────────────────────────────────────────────────────────

/// A hash subtree range in the Merkle tree.
///
/// ``start`` and ``end`` are integer leaf indices; ``value`` is the aggregated
/// hash covering entries ``[start, end)``.
#[pyclass(frozen, name = "Subtree")]
pub struct PySubtree {
    start: i64,
    end: i64,
    value: Vec<u8>,
}

pub(crate) fn make_subtree(py: Python<'_>, s: Subtree) -> PyResult<Py<PySubtree>> {
    Py::new(
        py,
        PySubtree {
            start: int_to_i64(&s.start)?,
            end: int_to_i64(&s.end)?,
            value: s.value.as_bytes().to_vec(),
        },
    )
}

#[pymethods]
impl PySubtree {
    /// Parse a DER-encoded ``Subtree`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let s = Subtree::decode(&mut dec).map_err(SyntaErr)?;
        Ok(PySubtree {
            start: int_to_i64(&s.start)?,
            end: int_to_i64(&s.end)?,
            value: s.value.as_bytes().to_vec(),
        })
    }

    /// Start leaf index (inclusive).
    #[getter]
    fn start(&self) -> i64 {
        self.start
    }

    /// End leaf index (exclusive).
    #[getter]
    fn end(&self) -> i64 {
        self.end
    }

    /// Aggregated hash bytes covering entries ``[start, end)``.
    #[getter]
    fn value<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.value)
    }

    fn __repr__(&self) -> String {
        format!("Subtree(start={}, end={})", self.start, self.end)
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.start == other.start && self.end == other.end && self.value == other.value
    }
}

// ── SubtreeProof ──────────────────────────────────────────────────────────────

/// Proof consisting of optional left and right subtree lists.
///
/// Both ``left_subtrees`` and ``right_subtrees`` may be ``None`` if absent
/// in the encoded structure.
#[pyclass(frozen, name = "SubtreeProof")]
pub struct PySubtreeProof {
    left_subtrees: Option<Vec<Py<PySubtree>>>,
    right_subtrees: Option<Vec<Py<PySubtree>>>,
}

pub(crate) fn make_subtree_proof(py: Python<'_>, sp: SubtreeProof) -> PyResult<Py<PySubtreeProof>> {
    let left_subtrees = sp
        .left_subtrees
        .map(|v| {
            v.into_iter()
                .map(|s| make_subtree(py, s))
                .collect::<PyResult<Vec<_>>>()
        })
        .transpose()?;
    let right_subtrees = sp
        .right_subtrees
        .map(|v| {
            v.into_iter()
                .map(|s| make_subtree(py, s))
                .collect::<PyResult<Vec<_>>>()
        })
        .transpose()?;
    Py::new(
        py,
        PySubtreeProof {
            left_subtrees,
            right_subtrees,
        },
    )
}

#[pymethods]
impl PySubtreeProof {
    /// Parse a DER-encoded ``SubtreeProof`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let sp = SubtreeProof::decode(&mut dec).map_err(SyntaErr)?;
        let left_subtrees = sp
            .left_subtrees
            .map(|v| {
                v.into_iter()
                    .map(|s| make_subtree(py, s))
                    .collect::<PyResult<Vec<_>>>()
            })
            .transpose()?;
        let right_subtrees = sp
            .right_subtrees
            .map(|v| {
                v.into_iter()
                    .map(|s| make_subtree(py, s))
                    .collect::<PyResult<Vec<_>>>()
            })
            .transpose()?;
        Ok(PySubtreeProof {
            left_subtrees,
            right_subtrees,
        })
    }

    /// Left subtrees, or ``None`` if absent.
    #[getter]
    fn left_subtrees<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyList>>> {
        opt_py_list(py, &self.left_subtrees)
    }

    /// Right subtrees, or ``None`` if absent.
    #[getter]
    fn right_subtrees<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyList>>> {
        opt_py_list(py, &self.right_subtrees)
    }

    fn __repr__(&self) -> String {
        let l = self.left_subtrees.as_ref().map(|v| v.len()).unwrap_or(0);
        let r = self.right_subtrees.as_ref().map(|v| v.len()).unwrap_or(0);
        format!("SubtreeProof(left={l}, right={r})")
    }
}

// ── InclusionProof ────────────────────────────────────────────────────────────

/// Merkle tree inclusion proof for a log entry.
///
/// ``log_entry_index`` is the leaf position; ``tree_size`` is the total tree
/// size at the time of the proof; ``subtree_start`` and ``subtree_end`` bound
/// the subtree range (per spec §6.1); ``inclusion_path`` is the ordered list
/// of sibling hashes.
#[pyclass(frozen, name = "InclusionProof")]
pub struct PyInclusionProof {
    log_entry_index: i64,
    tree_size: i64,
    subtree_start: i64,
    subtree_end: i64,
    inclusion_path: Vec<Py<PyProofNode>>,
}

pub(crate) fn make_inclusion_proof(
    py: Python<'_>,
    ip: InclusionProof,
) -> PyResult<Py<PyInclusionProof>> {
    let log_entry_index = int_to_i64(&ip.log_entry_index)?;
    let tree_size = int_to_i64(&ip.tree_size)?;
    let subtree_start = int_to_i64(&ip.subtree_start)?;
    let subtree_end = int_to_i64(&ip.subtree_end)?;
    let inclusion_path = ip
        .inclusion_path
        .into_iter()
        .map(|n| {
            Py::new(
                py,
                PyProofNode {
                    hash: n.as_bytes().to_vec(),
                },
            )
        })
        .collect::<PyResult<Vec<_>>>()?;
    Py::new(
        py,
        PyInclusionProof {
            log_entry_index,
            tree_size,
            subtree_start,
            subtree_end,
            inclusion_path,
        },
    )
}

#[pymethods]
impl PyInclusionProof {
    /// Parse a DER-encoded ``InclusionProof`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let ip = InclusionProof::decode(&mut dec).map_err(SyntaErr)?;
        let log_entry_index = int_to_i64(&ip.log_entry_index)?;
        let tree_size = int_to_i64(&ip.tree_size)?;
        let subtree_start = int_to_i64(&ip.subtree_start)?;
        let subtree_end = int_to_i64(&ip.subtree_end)?;
        let inclusion_path = ip
            .inclusion_path
            .into_iter()
            .map(|n| {
                Py::new(
                    py,
                    PyProofNode {
                        hash: n.as_bytes().to_vec(),
                    },
                )
            })
            .collect::<PyResult<Vec<_>>>()?;
        Ok(PyInclusionProof {
            log_entry_index,
            tree_size,
            subtree_start,
            subtree_end,
            inclusion_path,
        })
    }

    /// Leaf index of the certified entry.
    #[getter]
    fn log_entry_index(&self) -> i64 {
        self.log_entry_index
    }

    /// Total number of leaves in the tree at proof time.
    #[getter]
    fn tree_size(&self) -> i64 {
        self.tree_size
    }

    /// Start of the subtree range (inclusive) per spec §6.1.
    #[getter]
    fn subtree_start(&self) -> i64 {
        self.subtree_start
    }

    /// End of the subtree range (exclusive) per spec §6.1.
    #[getter]
    fn subtree_end(&self) -> i64 {
        self.subtree_end
    }

    /// Ordered list of sibling hashes forming the inclusion path.
    #[getter]
    fn inclusion_path<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyList>> {
        let elems: Vec<Bound<'_, PyProofNode>> = self
            .inclusion_path
            .iter()
            .map(|x| x.clone_ref(py).into_bound(py))
            .collect();
        PyList::new(py, elems)
    }

    fn __repr__(&self) -> String {
        format!(
            "InclusionProof(log_entry_index={}, tree_size={})",
            self.log_entry_index, self.tree_size
        )
    }
}

// ── LogID ─────────────────────────────────────────────────────────────────────

/// Log identifier: the hash algorithm OID and the log's public key DER.
///
/// ``hash_algorithm_oid`` is the dotted-decimal OID (e.g. ``"2.16.840.1.101.3.4.2.1"``
/// for SHA-256).  ``public_key_der`` is the DER-encoded ``SubjectPublicKeyInfo``.
#[pyclass(frozen, name = "LogID")]
pub struct PyLogID {
    hash_algorithm_oid: String,
    public_key_der: Vec<u8>,
}

pub(crate) fn make_log_id(py: Python<'_>, lid: LogID<'_>) -> PyResult<Py<PyLogID>> {
    let hash_algorithm_oid = alg_oid_str(&lid.hash_algorithm);
    let public_key_der = spki_to_der(&lid.public_key)?;
    Py::new(
        py,
        PyLogID {
            hash_algorithm_oid,
            public_key_der,
        },
    )
}

#[pymethods]
impl PyLogID {
    /// Parse a DER-encoded ``LogID`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let lid = LogID::decode(&mut dec).map_err(SyntaErr)?;
        let hash_algorithm_oid = alg_oid_str(&lid.hash_algorithm);
        let public_key_der = spki_to_der(&lid.public_key)?;
        Ok(PyLogID {
            hash_algorithm_oid,
            public_key_der,
        })
    }

    /// Dotted-decimal OID of the hash algorithm used by this log.
    #[getter]
    fn hash_algorithm_oid(&self) -> &str {
        &self.hash_algorithm_oid
    }

    /// DER-encoded ``SubjectPublicKeyInfo`` of the log's signing key.
    #[getter]
    fn public_key_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.public_key_der)
    }

    fn __repr__(&self) -> String {
        format!("LogID(hash_algorithm_oid='{}')", self.hash_algorithm_oid)
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.hash_algorithm_oid == other.hash_algorithm_oid
            && self.public_key_der == other.public_key_der
    }
}

// ── CosignerID ────────────────────────────────────────────────────────────────

/// Cosigner identity: hash algorithm and public key (mirrors LogID).
///
/// ``hash_algorithm_oid`` is the dotted-decimal OID of the hash algorithm.
/// ``public_key_der`` is the DER-encoded SubjectPublicKeyInfo of the cosigner.
#[pyclass(frozen, name = "CosignerID")]
pub struct PyCosignerID {
    hash_algorithm_oid: String,
    public_key_der: Vec<u8>,
}

pub(crate) fn make_cosigner_id(py: Python<'_>, cid: CosignerID) -> PyResult<Py<PyCosignerID>> {
    let hash_algorithm_oid = alg_oid_str(&cid.hash_algorithm);
    let public_key_der = encode_to_der(&cid.public_key)?;
    Py::new(
        py,
        PyCosignerID {
            hash_algorithm_oid,
            public_key_der,
        },
    )
}

#[pymethods]
impl PyCosignerID {
    /// Parse a DER-encoded ``CosignerID`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let cid = CosignerID::decode(&mut dec).map_err(SyntaErr)?;
        let hash_algorithm_oid = alg_oid_str(&cid.hash_algorithm);
        let public_key_der = encode_to_der(&cid.public_key)?;
        Ok(PyCosignerID {
            hash_algorithm_oid,
            public_key_der,
        })
    }

    /// Dotted-decimal OID of the cosigner hash algorithm.
    #[getter]
    fn hash_algorithm_oid(&self) -> &str {
        &self.hash_algorithm_oid
    }

    /// DER-encoded SubjectPublicKeyInfo of the cosigner.
    #[getter]
    fn public_key_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.public_key_der)
    }

    fn __repr__(&self) -> String {
        format!("CosignerID(hash_algorithm_oid={})", self.hash_algorithm_oid)
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.hash_algorithm_oid == other.hash_algorithm_oid
            && self.public_key_der == other.public_key_der
    }
}

// ── Checkpoint ────────────────────────────────────────────────────────────────

/// A signed Merkle tree checkpoint.
///
/// Attributes:
/// - ``log_id`` — :class:`LogID` identifying the log
/// - ``tree_size`` — total leaf count
/// - ``tree_minimum_index`` — optional lower bound on included entries
/// - ``root_value`` — Merkle root hash bytes
/// - ``timestamp`` — GeneralizedTime string
#[pyclass(frozen, name = "Checkpoint")]
pub struct PyCheckpoint {
    log_id: Py<PyLogID>,
    tree_size: i64,
    tree_minimum_index: Option<i64>,
    root_value: Vec<u8>,
    timestamp: String,
}

pub(crate) fn make_checkpoint(
    py: Python<'_>,
    cp: synta_mtc::types::Checkpoint<'_>,
) -> PyResult<Py<PyCheckpoint>> {
    let log_id = make_log_id(py, cp.log_id)?;
    let tree_size = int_to_i64(&cp.tree_size)?;
    let tree_minimum_index = cp.tree_minimum_index.as_ref().map(int_to_i64).transpose()?;
    let root_value = cp.root_value.as_bytes().to_vec();
    let timestamp = cp.timestamp.to_string();
    Py::new(
        py,
        PyCheckpoint {
            log_id,
            tree_size,
            tree_minimum_index,
            root_value,
            timestamp,
        },
    )
}

#[pymethods]
impl PyCheckpoint {
    /// Parse a DER-encoded ``Checkpoint`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let cp = synta_mtc::types::Checkpoint::decode(&mut dec).map_err(SyntaErr)?;
        let log_id = make_log_id(py, cp.log_id)?;
        let tree_size = int_to_i64(&cp.tree_size)?;
        let tree_minimum_index = cp.tree_minimum_index.as_ref().map(int_to_i64).transpose()?;
        let root_value = cp.root_value.as_bytes().to_vec();
        let timestamp = cp.timestamp.to_string();
        Ok(PyCheckpoint {
            log_id,
            tree_size,
            tree_minimum_index,
            root_value,
            timestamp,
        })
    }

    /// :class:`LogID` identifying the log that issued this checkpoint.
    #[getter]
    fn log_id<'py>(&self, py: Python<'py>) -> Bound<'py, PyLogID> {
        self.log_id.clone_ref(py).into_bound(py)
    }

    /// Total number of leaves in the tree.
    #[getter]
    fn tree_size(&self) -> i64 {
        self.tree_size
    }

    /// Minimum leaf index covered by this checkpoint, or ``None``.
    #[getter]
    fn tree_minimum_index(&self) -> Option<i64> {
        self.tree_minimum_index
    }

    /// Merkle root hash bytes.
    #[getter]
    fn root_value<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.root_value)
    }

    /// Timestamp of this checkpoint as a GeneralizedTime string.
    #[getter]
    fn timestamp(&self) -> &str {
        &self.timestamp
    }

    fn __repr__(&self) -> String {
        format!(
            "Checkpoint(tree_size={}, timestamp='{}')",
            self.tree_size, self.timestamp
        )
    }
}

// ── SubtreeSignature ──────────────────────────────────────────────────────────

/// A cosigner's signature over a subtree and checkpoint.
///
/// Contains the cosigner identity, the subtree, the checkpoint being signed,
/// the signature algorithm OID, and the raw signature bytes.
#[pyclass(frozen, name = "SubtreeSignature")]
pub struct PySubtreeSignature {
    cosigner: Py<PyCosignerID>,
    subtree: Py<PySubtree>,
    checkpoint: Py<PyCheckpoint>,
    signature_algorithm_oid: String,
    signature: Vec<u8>,
}

pub(crate) fn make_subtree_signature(
    py: Python<'_>,
    ss: SubtreeSignature<'_>,
) -> PyResult<Py<PySubtreeSignature>> {
    let cosigner = make_cosigner_id(py, ss.cosigner)?;
    let subtree = make_subtree(py, ss.subtree)?;
    let checkpoint = make_checkpoint(py, ss.checkpoint)?;
    let signature_algorithm_oid = alg_oid_str(&ss.signature_algorithm);
    let signature = ss.signature.as_bytes().to_vec();
    Py::new(
        py,
        PySubtreeSignature {
            cosigner,
            subtree,
            checkpoint,
            signature_algorithm_oid,
            signature,
        },
    )
}

#[pymethods]
impl PySubtreeSignature {
    /// Parse a DER-encoded ``SubtreeSignature`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let ss = SubtreeSignature::decode(&mut dec).map_err(SyntaErr)?;
        let cosigner = make_cosigner_id(py, ss.cosigner)?;
        let subtree = make_subtree(py, ss.subtree)?;
        let checkpoint = make_checkpoint(py, ss.checkpoint)?;
        let signature_algorithm_oid = alg_oid_str(&ss.signature_algorithm);
        let signature = ss.signature.as_bytes().to_vec();
        Ok(PySubtreeSignature {
            cosigner,
            subtree,
            checkpoint,
            signature_algorithm_oid,
            signature,
        })
    }

    /// :class:`CosignerID` identifying the cosigner.
    #[getter]
    fn cosigner<'py>(&self, py: Python<'py>) -> Bound<'py, PyCosignerID> {
        self.cosigner.clone_ref(py).into_bound(py)
    }

    /// :class:`Subtree` being signed.
    #[getter]
    fn subtree<'py>(&self, py: Python<'py>) -> Bound<'py, PySubtree> {
        self.subtree.clone_ref(py).into_bound(py)
    }

    /// :class:`Checkpoint` signed along with the subtree.
    #[getter]
    fn checkpoint<'py>(&self, py: Python<'py>) -> Bound<'py, PyCheckpoint> {
        self.checkpoint.clone_ref(py).into_bound(py)
    }

    /// Dotted-decimal OID of the signature algorithm.
    #[getter]
    fn signature_algorithm_oid(&self) -> &str {
        &self.signature_algorithm_oid
    }

    /// Raw signature bytes.
    #[getter]
    fn signature<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.signature)
    }

    fn __repr__(&self) -> String {
        format!(
            "SubtreeSignature(algorithm='{}')",
            self.signature_algorithm_oid
        )
    }
}

// ── TbsCertificateLogEntry ────────────────────────────────────────────────────

/// To-be-signed log entry for a certificate.
///
/// Attributes:
/// - ``issuer_der`` — DER-encoded issuer Name (pass to ``synta.parse_name_attrs()``)
/// - ``validity_not_before`` / ``validity_not_after`` — GeneralizedTime strings
/// - ``subject_der`` — DER-encoded subject Name
/// - ``subject_public_key_algorithm_oid`` — algorithm OID string
/// - ``subject_public_key_info_hash`` — SHA-256 hash of the public key
/// - ``issuer_unique_id`` — optional raw bit-string bytes
/// - ``subject_unique_id`` — optional raw bit-string bytes
/// - ``extensions_der`` — optional DER-encoded SEQUENCE OF Extension
#[pyclass(frozen, name = "TbsCertificateLogEntry")]
pub struct PyTbsCertificateLogEntry {
    issuer_der: Vec<u8>,
    validity_not_before: String,
    validity_not_after: String,
    subject_der: Vec<u8>,
    subject_public_key_algorithm_oid: String,
    subject_public_key_info_hash: Vec<u8>,
    issuer_unique_id: Option<Vec<u8>>,
    subject_unique_id: Option<Vec<u8>>,
    extensions_der: Option<Vec<u8>>,
}

pub(crate) fn make_tbs_log_entry(
    py: Python<'_>,
    entry: TBSCertificateLogEntry<'_>,
) -> PyResult<Py<PyTbsCertificateLogEntry>> {
    let issuer_der = mtc_name_to_der(&entry.issuer)?;
    let validity_not_before = time_to_str(&entry.validity.not_before);
    let validity_not_after = time_to_str(&entry.validity.not_after);
    let subject_der = mtc_name_to_der(&entry.subject)?;
    let subject_public_key_algorithm_oid = alg_oid_str(&entry.subject_public_key_algorithm);
    let subject_public_key_info_hash = entry.subject_public_key_info_hash.as_bytes().to_vec();
    let issuer_unique_id = entry
        .issuer_unique_id
        .as_ref()
        .map(|b| b.as_bytes().to_vec());
    let subject_unique_id = entry
        .subject_unique_id
        .as_ref()
        .map(|b| b.as_bytes().to_vec());
    let extensions_der = entry.extensions.as_ref().map(encode_to_der).transpose()?;
    Py::new(
        py,
        PyTbsCertificateLogEntry {
            issuer_der,
            validity_not_before,
            validity_not_after,
            subject_der,
            subject_public_key_algorithm_oid,
            subject_public_key_info_hash,
            issuer_unique_id,
            subject_unique_id,
            extensions_der,
        },
    )
}

#[pymethods]
impl PyTbsCertificateLogEntry {
    /// Parse a DER-encoded ``TBSCertificateLogEntry`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let entry = TBSCertificateLogEntry::decode(&mut dec).map_err(SyntaErr)?;
        let issuer_der = mtc_name_to_der(&entry.issuer)?;
        let validity_not_before = time_to_str(&entry.validity.not_before);
        let validity_not_after = time_to_str(&entry.validity.not_after);
        let subject_der = mtc_name_to_der(&entry.subject)?;
        let subject_public_key_algorithm_oid = alg_oid_str(&entry.subject_public_key_algorithm);
        let subject_public_key_info_hash = entry.subject_public_key_info_hash.as_bytes().to_vec();
        let issuer_unique_id = entry
            .issuer_unique_id
            .as_ref()
            .map(|b| b.as_bytes().to_vec());
        let subject_unique_id = entry
            .subject_unique_id
            .as_ref()
            .map(|b| b.as_bytes().to_vec());
        let extensions_der = entry.extensions.as_ref().map(encode_to_der).transpose()?;
        Ok(PyTbsCertificateLogEntry {
            issuer_der,
            validity_not_before,
            validity_not_after,
            subject_der,
            subject_public_key_algorithm_oid,
            subject_public_key_info_hash,
            issuer_unique_id,
            subject_unique_id,
            extensions_der,
        })
    }

    /// DER-encoded issuer Name.  Pass to ``synta.parse_name_attrs()`` to decode.
    #[getter]
    fn issuer_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.issuer_der)
    }

    /// Validity start time as a GeneralizedTime string.
    #[getter]
    fn validity_not_before(&self) -> &str {
        &self.validity_not_before
    }

    /// Validity end time as a GeneralizedTime string.
    #[getter]
    fn validity_not_after(&self) -> &str {
        &self.validity_not_after
    }

    /// DER-encoded subject Name.  Pass to ``synta.parse_name_attrs()`` to decode.
    #[getter]
    fn subject_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.subject_der)
    }

    /// Dotted-decimal OID of the subject public key algorithm.
    #[getter]
    fn subject_public_key_algorithm_oid(&self) -> &str {
        &self.subject_public_key_algorithm_oid
    }

    /// SHA-256 hash of the subject public key.
    #[getter]
    fn subject_public_key_info_hash<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.subject_public_key_info_hash)
    }

    /// Issuer unique ID bit-string bytes, or ``None``.
    #[getter]
    fn issuer_unique_id<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.issuer_unique_id.as_ref().map(|b| PyBytes::new(py, b))
    }

    /// Subject unique ID bit-string bytes, or ``None``.
    #[getter]
    fn subject_unique_id<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.subject_unique_id.as_ref().map(|b| PyBytes::new(py, b))
    }

    /// DER-encoded ``SEQUENCE OF Extension``, or ``None`` if absent.
    #[getter]
    fn extensions_der<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.extensions_der.as_ref().map(|b| PyBytes::new(py, b))
    }

    fn __repr__(&self) -> String {
        format!(
            "TbsCertificateLogEntry(algorithm='{}')",
            self.subject_public_key_algorithm_oid
        )
    }
}

// ── MerkleTreeCertEntry ───────────────────────────────────────────────────────

/// CHOICE: a null log entry or a ``TBSCertificateLogEntry``.
///
/// ``variant`` is either ``"NullEntry"`` or ``"TbsCertEntry"``.
/// ``tbs_cert_entry`` is set when ``variant == "TbsCertEntry"``, else ``None``.
#[pyclass(frozen, name = "MerkleTreeCertEntry")]
pub struct PyMerkleTreeCertEntry {
    variant: &'static str,
    tbs_cert_entry: Option<Py<PyTbsCertificateLogEntry>>,
}

#[pymethods]
impl PyMerkleTreeCertEntry {
    /// Parse a DER-encoded ``MerkleTreeCertEntry`` CHOICE.
    #[staticmethod]
    pub fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let entry = MerkleTreeCertEntry::decode(&mut dec).map_err(SyntaErr)?;
        match entry {
            MerkleTreeCertEntry::NullEntry(_) => Ok(PyMerkleTreeCertEntry {
                variant: "NullEntry",
                tbs_cert_entry: None,
            }),
            MerkleTreeCertEntry::TbsCertEntry(e) => {
                let tbs = make_tbs_log_entry(py, e)?;
                Ok(PyMerkleTreeCertEntry {
                    variant: "TbsCertEntry",
                    tbs_cert_entry: Some(tbs),
                })
            }
        }
    }

    /// Active CHOICE variant: ``"NullEntry"`` or ``"TbsCertEntry"``.
    #[getter]
    fn variant(&self) -> &str {
        self.variant
    }

    /// :class:`TbsCertificateLogEntry`, or ``None`` when ``variant == "NullEntry"``.
    #[getter]
    fn tbs_cert_entry<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyTbsCertificateLogEntry>> {
        self.tbs_cert_entry
            .as_ref()
            .map(|x| x.clone_ref(py).into_bound(py))
    }

    fn __repr__(&self) -> String {
        format!("MerkleTreeCertEntry(variant='{}')", self.variant)
    }
}

// ── LandmarkID ────────────────────────────────────────────────────────────────

/// Landmark log identifier: a ``LogID`` plus the tree size at issuance.
#[pyclass(frozen, name = "LandmarkID")]
pub struct PyLandmarkID {
    log_id: Py<PyLogID>,
    tree_size: i64,
}

pub(crate) fn make_landmark_id(py: Python<'_>, lid: LandmarkID<'_>) -> PyResult<Py<PyLandmarkID>> {
    let log_id = make_log_id(py, lid.log_id)?;
    let tree_size = int_to_i64(&lid.tree_size)?;
    Py::new(py, PyLandmarkID { log_id, tree_size })
}

#[pymethods]
impl PyLandmarkID {
    /// Parse a DER-encoded ``LandmarkID`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let lid = LandmarkID::decode(&mut dec).map_err(SyntaErr)?;
        let log_id = make_log_id(py, lid.log_id)?;
        let tree_size = int_to_i64(&lid.tree_size)?;
        Ok(PyLandmarkID { log_id, tree_size })
    }

    /// :class:`LogID` identifying the landmark log.
    #[getter]
    fn log_id<'py>(&self, py: Python<'py>) -> Bound<'py, PyLogID> {
        self.log_id.clone_ref(py).into_bound(py)
    }

    /// Tree size at the time the landmark certificate was issued.
    #[getter]
    fn tree_size(&self) -> i64 {
        self.tree_size
    }

    fn __repr__(&self) -> String {
        format!("LandmarkID(tree_size={})", self.tree_size)
    }
}

// ── StandaloneCertificate ─────────────────────────────────────────────────────

/// A full standalone Merkle Tree Certificate.
///
/// Contains the TBS certificate DER bytes (decodable with
/// ``synta.Certificate``), the inclusion proof, subtree proof, cosigner
/// subtree signatures, the signature algorithm OID, and the raw signature.
#[pyclass(frozen, name = "StandaloneCertificate")]
pub struct PyStandaloneCertificate {
    tbs_certificate_der: Vec<u8>,
    inclusion_proof: Py<PyInclusionProof>,
    subtree_proof: Py<PySubtreeProof>,
    subtree_signatures: Vec<Py<PySubtreeSignature>>,
    signature_algorithm_oid: String,
    signature: Vec<u8>,
}

#[pymethods]
impl PyStandaloneCertificate {
    /// Parse a DER-encoded ``StandaloneCertificate`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let sc = StandaloneCertificate::decode(&mut dec).map_err(SyntaErr)?;
        let tbs_certificate_der = tbs_cert_to_der(&sc.tbs_certificate)?;
        let inclusion_proof = make_inclusion_proof(py, sc.inclusion_proof)?;
        let subtree_proof = make_subtree_proof(py, sc.subtree_proof)?;
        let subtree_signatures = sc
            .subtree_signatures
            .into_iter()
            .map(|ss| make_subtree_signature(py, ss))
            .collect::<PyResult<Vec<_>>>()?;
        let signature_algorithm_oid = alg_oid_str(&sc.signature_algorithm);
        let signature = sc.signature.as_bytes().to_vec();
        Ok(PyStandaloneCertificate {
            tbs_certificate_der,
            inclusion_proof,
            subtree_proof,
            subtree_signatures,
            signature_algorithm_oid,
            signature,
        })
    }

    /// DER-encoded ``TBSCertificate``.  Pass to ``synta.Certificate.from_der()``
    /// (after wrapping in a full certificate) or inspect fields via ``Decoder``.
    #[getter]
    fn tbs_certificate_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.tbs_certificate_der)
    }

    /// :class:`InclusionProof` certifying the log entry.
    #[getter]
    fn inclusion_proof<'py>(&self, py: Python<'py>) -> Bound<'py, PyInclusionProof> {
        self.inclusion_proof.clone_ref(py).into_bound(py)
    }

    /// :class:`SubtreeProof` for log compaction.
    #[getter]
    fn subtree_proof<'py>(&self, py: Python<'py>) -> Bound<'py, PySubtreeProof> {
        self.subtree_proof.clone_ref(py).into_bound(py)
    }

    /// List of :class:`SubtreeSignature` cosignatures.
    #[getter]
    fn subtree_signatures<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyList>> {
        let elems: Vec<Bound<'_, PySubtreeSignature>> = self
            .subtree_signatures
            .iter()
            .map(|x| x.clone_ref(py).into_bound(py))
            .collect();
        PyList::new(py, elems)
    }

    /// Dotted-decimal OID of the signature algorithm.
    #[getter]
    fn signature_algorithm_oid(&self) -> &str {
        &self.signature_algorithm_oid
    }

    /// Raw signature bytes.
    #[getter]
    fn signature<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.signature)
    }

    fn __repr__(&self) -> String {
        format!(
            "StandaloneCertificate(algorithm='{}', sigs={})",
            self.signature_algorithm_oid,
            self.subtree_signatures.len()
        )
    }
}

// ── LandmarkCertificate ───────────────────────────────────────────────────────

/// A Merkle Tree Landmark Certificate.
///
/// Similar to :class:`StandaloneCertificate` but references a landmark log
/// via a :class:`LandmarkID` instead of a subtree proof and cosignatures.
#[pyclass(frozen, name = "LandmarkCertificate")]
pub struct PyLandmarkCertificate {
    tbs_certificate_der: Vec<u8>,
    inclusion_proof: Py<PyInclusionProof>,
    landmark_id: Py<PyLandmarkID>,
    signature_algorithm_oid: String,
    signature: Vec<u8>,
}

#[pymethods]
impl PyLandmarkCertificate {
    /// Parse a DER-encoded ``LandmarkCertificate`` SEQUENCE.
    #[staticmethod]
    pub fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = synta::Decoder::new(data, synta::Encoding::Der);
        let lc = LandmarkCertificate::decode(&mut dec).map_err(SyntaErr)?;
        let tbs_certificate_der = tbs_cert_to_der(&lc.tbs_certificate)?;
        let inclusion_proof = make_inclusion_proof(py, lc.inclusion_proof)?;
        let landmark_id = make_landmark_id(py, lc.landmark_id)?;
        let signature_algorithm_oid = alg_oid_str(&lc.signature_algorithm);
        let signature = lc.signature.as_bytes().to_vec();
        Ok(PyLandmarkCertificate {
            tbs_certificate_der,
            inclusion_proof,
            landmark_id,
            signature_algorithm_oid,
            signature,
        })
    }

    /// DER-encoded ``TBSCertificate``.
    #[getter]
    fn tbs_certificate_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.tbs_certificate_der)
    }

    /// :class:`InclusionProof` certifying the log entry.
    #[getter]
    fn inclusion_proof<'py>(&self, py: Python<'py>) -> Bound<'py, PyInclusionProof> {
        self.inclusion_proof.clone_ref(py).into_bound(py)
    }

    /// :class:`LandmarkID` referencing the landmark log.
    #[getter]
    fn landmark_id<'py>(&self, py: Python<'py>) -> Bound<'py, PyLandmarkID> {
        self.landmark_id.clone_ref(py).into_bound(py)
    }

    /// Dotted-decimal OID of the signature algorithm.
    #[getter]
    fn signature_algorithm_oid(&self) -> &str {
        &self.signature_algorithm_oid
    }

    /// Raw signature bytes.
    #[getter]
    fn signature<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.signature)
    }

    fn __repr__(&self) -> String {
        format!(
            "LandmarkCertificate(algorithm='{}')",
            self.signature_algorithm_oid
        )
    }
}

// ── Module registration ───────────────────────────────────────────────────────

/// Register all MTC classes into the ``synta.mtc`` submodule.
/// Populate the `synta.mtc` module with all classes.
///
/// `m` is the pre-created `synta.mtc` submodule passed in from `lib.rs`.
pub fn register_mtc_module(m: &Bound<'_, pyo3::types::PyModule>) -> PyResult<()> {
    m.add_class::<PyProofNode>()?;
    m.add_class::<PySubtree>()?;
    m.add_class::<PySubtreeProof>()?;
    m.add_class::<PyInclusionProof>()?;
    m.add_class::<PyLogID>()?;
    m.add_class::<PyCosignerID>()?;
    m.add_class::<PyCheckpoint>()?;
    m.add_class::<PySubtreeSignature>()?;
    m.add_class::<PyTbsCertificateLogEntry>()?;
    m.add_class::<PyMerkleTreeCertEntry>()?;
    m.add_class::<PyLandmarkID>()?;
    m.add_class::<PyStandaloneCertificate>()?;
    m.add_class::<PyLandmarkCertificate>()?;
    Ok(())
}