prime/
published.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
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
// 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::cmp::Ordering;
use core::fmt::{self, Display, Formatter};
use core::str::FromStr;
use core::{iter, slice};

use amplify::confinement::{ConfinedVec, TinyBlob, TinyVec};
use amplify::{Bytes32, Wrapper};
use baid64::{Baid64ParseError, DisplayBaid64, FromBaid64Str};
use commit_verify::{CommitId, CommitmentId, DigestExt, MerkleHash, MerkleLeaves, ReservedBytes, Sha256};

use crate::{impl_serde_baid64, PrimeSeal, LIB_NAME_PRIME};

/// Prime header.
///
/// The length of the prime header is fixed, 8*32 = 256 bytes.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_PRIME)]
#[derive(CommitEncode)]
#[commit_encode(strategy = strict, id = PrimeId)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))]
pub struct PrimeHeader {
    pub version: ReservedBytes<9>,
    pub diff_target: u8,
    pub filters: u8,
    pub tree_depth: u8,
    pub nonce: u32,
    pub height: u64,
    pub timestamp: i64,
    pub prev_header: PrimeId,
    pub filters_root: FiltersHash,
    pub seals_root: SealsHash,
    /// Public key which provides verified delay function.
    pub public_key: Bytes32,
    /// Computed secret key from the past (part of verified delay function).
    pub prev_secret_key: Bytes32,
    /// "Coinbase" seal.
    pub coinbase: PrimeSeal,
    /// Proofs of publication block.
    pub publications: ProofsHash,
}

impl PartialOrd for PrimeHeader {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}
impl Ord for PrimeHeader {
    fn cmp(&self, other: &Self) -> Ordering { self.prime_id().cmp(&other.prime_id()) }
}

impl PrimeHeader {
    #[inline]
    pub fn prime_id(&self) -> PrimeId { self.commit_id() }
}

// TODO: Debug with detailed STON (with type annotations)
// TODO: Display with STON or Armor

/// Tagged hash of the prime header.
#[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)]
pub struct PrimeId(
    #[from]
    #[from([u8; 32])]
    Bytes32,
);

impl DisplayBaid64 for PrimeId {
    const HRI: &'static str = "uv";
    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 PrimeId {}
impl FromStr for PrimeId {
    type Err = Baid64ParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> { Self::from_baid64_str(s) }
}
impl Display for PrimeId {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.fmt_baid64(f) }
}
impl_serde_baid64!(PrimeId);

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

/// Prime first-level block made of bloom filters.
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_PRIME)]
#[derive(CommitEncode)]
#[commit_encode(strategy = merklize, id = FiltersHash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))]
pub struct FiltersBlock {
    pub prime_id: PrimeId,
    // 16 KiB, each filter for ~200 seals, giving up to 100k TPS. Annual growth 500 GB
    pub filters: ConfinedVec<BloomFilter, 0, 0x200>,
}

impl MerkleLeaves for FiltersBlock {
    type Leaf = BloomFilter;
    type LeafIter<'tmp>
        = iter::Copied<slice::Iter<'tmp, BloomFilter>>
    where Self: 'tmp;

    fn merkle_leaves(&self) -> Self::LeafIter<'_> { self.filters.iter().copied() }
}

/// Tagged hash of the filters block [`FiltersBlock`].
#[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)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
pub struct FiltersHash(
    #[from]
    #[from([u8; 32])]
    Bytes32,
);

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

#[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)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
pub struct BloomFilter(
    #[from]
    #[from([u8; 32])]
    Bytes32,
);

/// Prime second-level block containing all closed single-use seals.
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_PRIME)]
#[derive(CommitEncode)]
#[commit_encode(strategy = merklize, id = SealsHash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))]
pub struct SealsBlock {
    pub prime_id: PrimeId,
    // 3 MiB
    pub seals: ConfinedVec<PrimeSeal, 0, 0x19000>,
}

impl MerkleLeaves for SealsBlock {
    type Leaf = PrimeSeal;
    type LeafIter<'tmp>
        = iter::Copied<slice::Iter<'tmp, PrimeSeal>>
    where Self: 'tmp;

    fn merkle_leaves(&self) -> Self::LeafIter<'_> { self.seals.iter().copied() }
}

/// Tagged hash of the seals block [`SealsBlock`].
#[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)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
pub struct SealsHash(
    #[from]
    #[from([u8; 32])]
    Bytes32,
);

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

/// Prime extension block containing proofs of publication.
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_PRIME)]
#[derive(CommitEncode)]
#[commit_encode(strategy = merklize, id = ProofsHash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))]
pub struct ProofsBlock {
    pub prime_id: PrimeId,
    // 3 MiB
    pub proofs: TinyVec<ProofOfPubl>,
}

impl MerkleLeaves for ProofsBlock {
    type Leaf = ProofOfPubl;
    type LeafIter<'tmp>
        = iter::Cloned<slice::Iter<'tmp, ProofOfPubl>>
    where Self: 'tmp;

    fn merkle_leaves(&self) -> Self::LeafIter<'_> { self.proofs.iter().cloned() }
}

/// Tagged hash of the proofs of publication block [`ProofsBlock`].
#[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)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
pub struct ProofsHash(
    #[from]
    #[from([u8; 32])]
    Bytes32,
);

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

/// Proof of publication.
#[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Debug)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_PRIME, tags = custom, dumb = Self::Custom(strict_dumb!()))]
#[derive(CommitEncode)]
#[commit_encode(strategy = strict, id = MerkleHash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(tag = "type", content = "data"))]
pub enum ProofOfPubl {
    /// Miner-defined information.
    #[strict_type(tag = 0x00)]
    Miner(TinyBlob),

    #[strict_type(tag = 0xFF)]
    Custom(TinyBlob),
}