sonicapi/state/
raw.rs

1// SONIC: Standard library for formally-verifiable distributed contracts
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Designed in 2019-2025 by Dr Maxim Orlovsky <orlovsky@ubideco.org>
6// Written in 2024-2025 by Dr Maxim Orlovsky <orlovsky@ubideco.org>
7//
8// Copyright (C) 2019-2024 LNP/BP Standards Association, Switzerland.
9// Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO),
10//                         Institute for Distributed and Cognitive Systems (InDCS), Switzerland.
11// Copyright (C) 2019-2025 Dr Maxim Orlovsky.
12// All rights under the above copyrights are reserved.
13//
14// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
15// in compliance with the License. You may obtain a copy of the License at
16//
17//        http://www.apache.org/licenses/LICENSE-2.0
18//
19// Unless required by applicable law or agreed to in writing, software distributed under the License
20// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
21// or implied. See the License for the specific language governing permissions and limitations under
22// the License.
23
24use aluvm::LibSite;
25use amplify::confinement::{SmallBlob, U24 as U24MAX};
26use strict_encoding::StreamReader;
27use strict_types::{SemId, StrictVal, TypeSystem};
28use ultrasonic::RawData;
29
30use crate::{StateBuildError, StateConvertError, LIB_NAME_SONIC};
31
32pub const TOTAL_RAW_BYTES: usize = U24MAX;
33
34#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
35#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
36#[strict_type(lib = LIB_NAME_SONIC, tags = custom, dumb = Self::StrictDecode(strict_dumb!()))]
37#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))]
38pub enum RawConvertor {
39    /// Convert raw bytes using strict encoding.
40    #[strict_type(tag = 0x00)]
41    StrictDecode(SemId),
42    // In the future we can add more adaptors:
43    // - using just a specific range of raw bytes, not a full value - such that multiple APIs may read different parts
44    //   of the same data;
45    /// Execute a custom function.
46    // AluVM is reserved for the future. We need it here to avoid breaking changes.
47    #[strict_type(tag = 0xFF)]
48    AluVM(
49        /// The entry point to the script (virtual machine uses libraries from
50        /// [`crate::Semantics`]).
51        LibSite,
52    ),
53}
54
55impl RawConvertor {
56    pub fn convert(&self, raw: &RawData, sys: &TypeSystem) -> Result<StrictVal, StateConvertError> {
57        match self {
58            Self::StrictDecode(sem_id) => strict_convert(*sem_id, raw, sys),
59            Self::AluVM(_) => Err(StateConvertError::Unsupported),
60        }
61    }
62}
63
64#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
65#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
66#[strict_type(lib = LIB_NAME_SONIC, tags = custom, dumb = Self::StrictEncode(strict_dumb!()))]
67#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))]
68pub enum RawBuilder {
69    /// Convert strict value into raw bytes using strict encoding.
70    #[strict_type(tag = 0x00)]
71    StrictEncode(SemId),
72
73    /// Execute a custom function.
74    // AluVM is reserved for the future. We need it here to avoid breaking changes.
75    #[strict_type(tag = 0xFF)]
76    AluVM(
77        /// The entry point to the script (virtual machine uses libraries from
78        /// [`crate::Semantics`]).
79        LibSite,
80    ),
81}
82
83impl RawBuilder {
84    #[allow(clippy::result_large_err)]
85    pub fn build(&self, val: StrictVal, sys: &TypeSystem) -> Result<RawData, StateBuildError> {
86        match self {
87            Self::StrictEncode(sem_id) => strict_build(*sem_id, val, sys),
88            Self::AluVM(_) => Err(StateBuildError::Unsupported),
89        }
90    }
91}
92
93fn strict_convert(sem_id: SemId, raw: &RawData, sys: &TypeSystem) -> Result<StrictVal, StateConvertError> {
94    let mut reader = StreamReader::cursor::<TOTAL_RAW_BYTES>(&raw[..]);
95    let mut val = sys.strict_read_type(sem_id, &mut reader)?.unbox();
96
97    if reader.into_cursor().position() != raw[..].len() as u64 {
98        return Err(StateConvertError::NotEntirelyConsumed);
99    }
100
101    loop {
102        if let StrictVal::Tuple(ref mut vec) = val {
103            if vec.len() == 1 {
104                val = vec.remove(0);
105                continue;
106            }
107        }
108        break;
109    }
110
111    Ok(val)
112}
113
114#[allow(clippy::result_large_err)]
115fn strict_build(sem_id: SemId, val: StrictVal, sys: &TypeSystem) -> Result<RawData, StateBuildError> {
116    let mut data = SmallBlob::new();
117
118    let typed_val = sys.typify(val, sem_id)?;
119    sys.strict_write_value(&typed_val, &mut data)?;
120
121    Ok(RawData::from(data))
122}