prime/
seals.rs

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
// Prime consensus: proof of publication layer for client-side validation
//
// SPDX-License-Identifier: Apache-2.0
//
// Designed in 2019-2025 by Dr Maxim Orlovsky <orlovsky@uviolet.net>
// Written in 2024-2025 by Dr Maxim Orlovsky <orlovsky@uviolet.net>
//
// Copyright (C) 2024-2025 Ultraviolet Alliance. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under
// the License.

use core::convert::Infallible;
use core::fmt::{self, Display, Formatter};
use core::str::FromStr;

use amplify::confinement::TinyVec;
use amplify::{ByteArray, Bytes32};
use baid64::{Baid64ParseError, DisplayBaid64, FromBaid64Str};
use commit_verify::{CommitmentId, DigestExt, MerkleHash, Sha256};
use single_use_seals::{ClientSideWitness, PublishedWitness, SealWitness, SingleUseSeal};

use crate::{impl_serde_baid64, PrimeHeader, PrimeId, SealsHash, LIB_NAME_PRIME};

/// Single-use seal used in Prime.
#[derive(Wrapper, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, From)]
#[wrapper(Deref, BorrowSlice, Hex, Index, RangeOps)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_PRIME)]
#[derive(CommitEncode)]
#[commit_encode(strategy = strict, id = MerkleHash)]
pub struct PrimeSeal(
    #[from]
    #[from([u8; 32])]
    Bytes32,
);

impl DisplayBaid64 for PrimeSeal {
    const HRI: &'static str = "seal";
    const CHUNKING: bool = true;
    const PREFIX: bool = true;
    const EMBED_CHECKSUM: bool = false;
    const MNEMONIC: bool = false;
    fn to_baid64_payload(&self) -> [u8; 32] { self.to_byte_array() }
}
impl FromBaid64Str for PrimeSeal {}
impl FromStr for PrimeSeal {
    type Err = Baid64ParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> { Self::from_baid64_str(s) }
}
impl Display for PrimeSeal {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.fmt_baid64(f) }
}
impl_serde_baid64!(PrimeSeal);

impl From<Sha256> for PrimeSeal {
    fn from(hasher: Sha256) -> Self { hasher.finish().into() }
}
impl CommitmentId for PrimeSeal {
    const TAG: &'static str = "urn:ultraviolet:prime:seal#2024-11-15";
}

impl SingleUseSeal for PrimeSeal {
    type Message = SealsHash;
    type PubWitness = PrimeHeader;
    type CliWitness = InclProof;

    fn is_included(&self, _: &SealWitness<Self>) -> bool { true }
}

impl PublishedWitness<PrimeSeal> for PrimeHeader {
    type PubId = PrimeId;
    type Error = InvalidProof;

    fn pub_id(&self) -> Self::PubId { self.prime_id() }

    fn verify_commitment(&self, msg: SealsHash) -> Result<(), Self::Error> {
        if msg == self.seals_root {
            Ok(())
        } else {
            Err(InvalidProof)
        }
    }
}

/// Merkle path element of the proof of inclusion [`ProofOfIncl`].
#[derive(Clone, Eq, PartialEq, Hash, Debug, From)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_PRIME)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))]
pub struct MerklePathItem {
    pub inverse: bool,
    pub pair: MerkleHash,
}

/// Proof of inclusion.
#[derive(Clone, Eq, PartialEq, Hash, Debug, From, Default)]
#[derive(StrictType, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_PRIME)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))]
pub struct InclProof {
    #[from]
    pub merkle_path: TinyVec<MerklePathItem>,
}

impl ClientSideWitness for InclProof {
    type Message = Bytes32;
    type Seal = PrimeSeal;
    type Error = Infallible;

    fn convolve_commit(&self, _msg: Bytes32) -> Result<SealsHash, Self::Error> {
        todo!();
        // TODO: Implement merkle proof verification inside commit_verify
        /*let mut hash = MerkleHash::from_byte_array(msg.to_byte_array());
        for node in &self.merkle_path {
            hash = MerkleHash::branches(, node);
        }
        SealsHash::from_byte_array(hash.to_byte_array())
         */
    }
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Display, Error, From)]
#[display("the provided proof is not valid for the given prime header")]
pub struct InvalidProof;