uts-core 0.1.0-alpha.1

Core types and traits for Univeral Timestamps in Rust
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
//! # OpenTimestamps OpCodes
//!
//! It contains opcode information and utilities to work with opcodes.

use crate::{
    alloc::{Allocator, Global, vec::Vec},
    codec::{Decode, DecodeIn, Decoder, Encode, Encoder},
    error::{DecodeError, EncodeError},
};
use alloy_primitives::hex;
use core::{fmt, hint::unreachable_unchecked};
use digest::Digest;
use ripemd::Ripemd160;
use sha1::Sha1;
use sha2::Sha256;
use sha3::Keccak256;

/// An OpenTimestamps opcode.
///
/// This is always a valid opcode.
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(serde_with::SerializeDisplay, serde_with::DeserializeFromStr)
)]
#[repr(transparent)]
pub struct OpCode(u8);

impl fmt::Debug for OpCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

impl fmt::Display for OpCode {
    /// Formats the opcode as a string.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

impl Encode for OpCode {
    #[inline]
    fn encode(&self, encoder: &mut impl Encoder) -> Result<(), EncodeError> {
        encoder.encode_byte(self.tag())
    }
}

impl Decode for OpCode {
    #[inline]
    fn decode(decoder: &mut impl Decoder) -> Result<Self, DecodeError> {
        let byte = decoder.decode_byte()?;
        OpCode::new(byte).ok_or(DecodeError::BadOpCode(byte))
    }
}

impl OpCode {
    /// Returns the 8-bit tag identifying the opcode.
    #[inline]
    pub const fn tag(self) -> u8 {
        self.0
    }

    /// Returns `true` when the opcode requires an immediate operand.
    #[inline]
    pub const fn has_immediate(&self) -> bool {
        matches!(*self, Self::APPEND | Self::PREPEND)
    }

    /// Returns `true` for control opcodes.
    #[inline]
    pub const fn is_control(&self) -> bool {
        matches!(*self, Self::ATTESTATION | Self::FORK)
    }

    /// Returns `true` for digest opcodes.
    #[inline]
    pub const fn is_digest(&self) -> bool {
        self.as_digest().is_some()
    }

    /// Returns the digest opcode wrapper, if applicable.
    #[inline]
    pub const fn as_digest(&self) -> Option<DigestOp> {
        match *self {
            Self::SHA1 | Self::SHA256 | Self::RIPEMD160 | Self::KECCAK256 => Some(DigestOp(*self)),
            _ => None,
        }
    }

    /// Executes the opcode on the given input data, with an optional immediate value.
    ///
    /// # Panics
    ///
    /// Panics if the opcode is a control opcode.
    #[inline]
    pub fn execute(&self, input: impl AsRef<[u8]>, immediate: impl AsRef<[u8]>) -> Vec<u8> {
        self.execute_in(input, immediate, Global)
    }

    /// Executes the opcode on the given input data, with an optional immediate value.
    ///
    /// # Panics
    ///
    /// Panics if the opcode is a control opcode.
    #[inline]
    pub fn execute_in<A: Allocator>(
        &self,
        input: impl AsRef<[u8]>,
        immediate: impl AsRef<[u8]>,
        alloc: A,
    ) -> Vec<u8, A> {
        if let Some(digest_op) = self.as_digest() {
            return digest_op.execute_in(input, alloc);
        }

        let input = input.as_ref();
        match *self {
            Self::APPEND => {
                let immediate = immediate.as_ref();
                let mut out = Vec::with_capacity_in(input.len() + immediate.len(), alloc);
                out.extend_from_slice(input);
                out.extend_from_slice(immediate);
                out
            }
            Self::PREPEND => {
                let immediate = immediate.as_ref();
                let mut out = Vec::with_capacity_in(input.len() + immediate.len(), alloc);
                out.extend_from_slice(immediate);
                out.extend_from_slice(input);
                out
            }
            Self::REVERSE => {
                let len = input.len();
                let mut out = Vec::<u8, A>::with_capacity_in(len, alloc);

                unsafe {
                    // SAFETY: The vector capacity is set to len, so setting the length to len is valid.
                    out.set_len(len);

                    // LLVM will take care of vectorization here.
                    let input_ptr = input.as_ptr();
                    let out_ptr = out.as_mut_ptr();
                    for i in 0..len {
                        // SAFETY: both pointers are valid for `len` bytes.
                        *out_ptr.add(i) = *input_ptr.add(len - 1 - i);
                    }
                }
                out
            }
            Self::HEXLIFY => {
                let hex_len = input.len() * 2;
                let mut out = Vec::<u8, A>::with_capacity_in(hex_len, alloc);
                // SAFETY: that the vector is actually the specified size.
                unsafe {
                    out.set_len(hex_len);
                }
                // SAFETY: the output buffer is large enough.
                unsafe {
                    hex::encode_to_slice(input, &mut out).unwrap_unchecked();
                }
                out
            }
            _ => panic!("Cannot execute control opcode"),
        }
    }
}

impl PartialEq<u8> for OpCode {
    fn eq(&self, other: &u8) -> bool {
        self.tag().eq(other)
    }
}

/// An OpenTimestamps digest opcode.
///
/// This is always a valid opcode.
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct DigestOp(OpCode);

impl fmt::Debug for DigestOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.0.name())
    }
}

impl fmt::Display for DigestOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl PartialEq<OpCode> for DigestOp {
    fn eq(&self, other: &OpCode) -> bool {
        self.0.eq(other)
    }
}

impl PartialEq<u8> for DigestOp {
    fn eq(&self, other: &u8) -> bool {
        self.0.eq(other)
    }
}

impl Encode for DigestOp {
    #[inline]
    fn encode(&self, encoder: &mut impl Encoder) -> Result<(), EncodeError> {
        self.0.encode(encoder)
    }
}

impl<A: Allocator> DecodeIn<A> for DigestOp {
    #[inline]
    fn decode_in(decoder: &mut impl Decoder, _alloc: A) -> Result<Self, DecodeError> {
        let opcode = OpCode::decode(decoder)?;
        opcode
            .as_digest()
            .ok_or(DecodeError::ExpectedDigestOp(opcode))
    }
}

impl DigestOp {
    /// Returns the wrapped opcode.
    #[inline]
    pub const fn to_opcode(self) -> OpCode {
        self.0
    }

    /// Returns the 8-bit tag identifying the digest opcode.
    #[inline]
    pub const fn tag(&self) -> u8 {
        self.0.tag()
    }
}

/// Extension trait for `Digest` implementors to get the corresponding `DigestOp`.
pub trait DigestOpExt: Digest {
    const OPCODE: DigestOp;

    fn opcode() -> DigestOp;
}

macro_rules! define_opcodes {
    ($($val:literal => $variant:ident),* $(,)?) => {
         $(
            #[doc = concat!("The `", stringify!($val), "` (\"", stringify!($variant),"\") opcode.")]
            pub const $variant: u8 = $val;
        )*

        $(
            impl OpCode {
                #[doc = concat!("The `", stringify!($val), "` (\"", stringify!($variant),"\") opcode.")]
                pub const $variant: Self = Self($val);
            }
        )*

        impl OpCode {
            #[inline]
            pub const fn new(v: u8) -> Option<Self> {
                match v {
                    $( $val => Some(Self::$variant), )*
                    _ => None,
                }
            }

            #[inline]
            pub const fn name(&self) -> &'static str {
                match *self {
                    $( Self::$variant => stringify!($variant), )*
                    // SAFETY: unreachable as all variants are covered.
                    _ => unsafe { unreachable_unchecked() }
                }
            }
        }

        /// Error returned when parsing an invalid opcode from a string.
        #[derive(Debug)]
        pub struct OpCodeFromStrError;

        impl core::fmt::Display for OpCodeFromStrError {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                write!(f, "invalid opcode string")
            }
        }

        impl std::error::Error for OpCodeFromStrError {}

        impl core::str::FromStr for OpCode {
            type Err = OpCodeFromStrError;

            #[inline]
            fn from_str(s: &str) -> Result<Self, Self::Err> {
                match s {
                    $( stringify!($variant) => Ok(Self::$variant), )*
                    _ => Err(OpCodeFromStrError),
                }
            }
         }
    };
}

macro_rules! define_digest_opcodes {
    ($($val:literal => $variant:ident),* $(,)?) => {
        $(
            impl DigestOp {
                #[doc = concat!("The `", stringify!($val), "` (\"", stringify!($variant),"\") digest opcode.")]
                pub const $variant: Self = Self(OpCode::$variant);
            }
        )*

        impl DigestOp {
            /// Returns the output length of the digest in bytes.
            #[inline]
            pub const fn output_size(&self) -> usize {
                use digest::typenum::Unsigned;
                paste::paste! {
                    match *self {
                        $( Self::$variant => <[<$variant:camel>] as ::digest::OutputSizeUser>::OutputSize::USIZE, )*
                        // SAFETY: unreachable as all variants are covered.
                        _ => unsafe { unreachable_unchecked() }
                    }
                }
            }

            /// Executes the digest operation on the input data.
            pub fn execute(&self, input: impl AsRef<[u8]>) -> $crate::alloc::vec::Vec<u8> {
                self.execute_in(input, $crate::alloc::Global)
            }

            /// Executes the digest operation on the input data.
            pub fn execute_in<A: $crate::alloc::Allocator>(&self, input: impl AsRef<[u8]>, alloc: A) -> $crate::alloc::vec::Vec<u8, A> {
                match *self {
                    $( Self::$variant => {
                        paste::paste! {
                            let mut hasher = [<$variant:camel>]::new();
                            hasher.update(input);
                            $crate::alloc::SliceExt::to_vec_in(hasher.finalize().as_slice(), alloc)
                        }
                    }, )*
                    // SAFETY: unreachable as all variants are covered.
                    _ => unsafe { unreachable_unchecked() }
                }
            }
        }
        paste::paste! {
            $(
                impl DigestOpExt for [<$variant:camel>] {
                    const OPCODE: DigestOp = DigestOp::$variant;

                    #[inline]
                    fn opcode() -> DigestOp {
                        DigestOp::$variant
                    }
                }
            )*
        }
    };
}

macro_rules! impl_simple_step {
    ($variant:ident) => {paste::paste! {
        impl<A: $crate::alloc::Allocator + Clone> $crate::codec::v1::timestamp::builder::TimestampBuilder<A> {
            #[doc = concat!("Push the `", stringify!($variant), "` opcode.")]
            pub fn [< $variant:lower >](&mut self) -> &mut Self {
                self.push_step(OpCode::[<$variant>])
            }
        }
    }};
    ($($variant:ident),* $(,)?) => {
        $(
            impl_simple_step! { $variant }
        )*
    };
}

macro_rules! impl_step_with_data {
    ($variant:ident) => {paste::paste! {
        impl<A: $crate::alloc::Allocator + Clone> $crate::codec::v1::timestamp::builder::TimestampBuilder<A> {
            #[doc = concat!("Push the `", stringify!($variant), "` opcode.")]
            pub fn [< $variant:lower >](&mut self, data: $crate::alloc::vec::Vec<u8, A>) -> &mut Self {
                self.push_immediate_step(OpCode::[<$variant>], data)
            }
        }
    }};
    ($($variant:ident),* $(,)?) => {
        $(
            impl_step_with_data! { $variant }
        )*
    };
}

define_opcodes! {
    0x02 => SHA1,
    0x03 => RIPEMD160,
    0x08 => SHA256,
    0x67 => KECCAK256,
    0xf0 => APPEND,
    0xf1 => PREPEND,
    0xf2 => REVERSE,
    0xf3 => HEXLIFY,
    0x00 => ATTESTATION,
    0xff => FORK,
}

define_digest_opcodes! {
    0x02 => SHA1,
    0x03 => RIPEMD160,
    0x08 => SHA256,
    0x67 => KECCAK256,
}

impl_simple_step! {
    SHA1,
    RIPEMD160,
    SHA256,
    KECCAK256,
    REVERSE,
    HEXLIFY,
}

impl_step_with_data! {
    APPEND,
    PREPEND,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn digest_len() {
        assert_eq!(DigestOp::SHA1.output_size(), 20);
        assert_eq!(DigestOp::RIPEMD160.output_size(), 20);
        assert_eq!(DigestOp::SHA256.output_size(), 32);
        assert_eq!(DigestOp::KECCAK256.output_size(), 32);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_opcode() {
        let opcode = OpCode::SHA256;
        let serialized = serde_json::to_string(&opcode).unwrap();
        assert_eq!(serialized, "\"SHA256\"");
        let deserialized: OpCode = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized, opcode);

        let digest_op = DigestOp::SHA256;
        let serialized = serde_json::to_string(&digest_op).unwrap();
        assert_eq!(serialized, "\"SHA256\"");
        let deserialized: DigestOp = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized, digest_op);
    }
}