Skip to main content

midnight_coin_structure/
fab.rs

1// This file is part of midnight-ledger.
2// Copyright (C) Midnight Foundation
3// SPDX-License-Identifier: Apache-2.0
4// Licensed under the Apache License, Version 2.0 (the "License");
5// You may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7// http://www.apache.org/licenses/LICENSE-2.0
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14use crate::coin::UserAddress;
15use crate::coin::{
16    Commitment, Info, Nonce, Nullifier, PublicKey, QualifiedInfo, ShieldedTokenType,
17    UnshieldedTokenType,
18};
19use crate::contract::ContractAddress;
20use crate::transfer::{Recipient, SenderEvidence};
21use base_crypto::fab::{Aligned, Alignment, InvalidBuiltinDecode, Value, ValueAtom, ValueSlice};
22use base_crypto::hash::{HashOutput, PERSISTENT_HASH_BYTES as PHB};
23
24macro_rules! via_hash_output {
25    ($($ty:ident),*) => {
26        $(
27            impl Aligned for $ty {
28                fn alignment() -> Alignment {
29                    HashOutput::alignment()
30                }
31            }
32
33            impl From<$ty> for ValueAtom {
34                fn from(hash: $ty) -> ValueAtom {
35                    ValueAtom(hash.0.0.to_vec()).normalize()
36                }
37            }
38
39            impl TryFrom<&ValueAtom> for $ty {
40                type Error = InvalidBuiltinDecode;
41
42                fn try_from(value: &ValueAtom) -> Result<$ty, InvalidBuiltinDecode> {
43                    let mut buf = [0u8; PHB];
44                    if value.0.len() <= PHB {
45                        buf[..value.0.len()].copy_from_slice(&value.0[..]);
46                        Ok($ty(HashOutput(buf)))
47                    } else {
48                        Err(InvalidBuiltinDecode(stringify!($ty)))
49                    }
50                }
51            }
52
53            impl From<$ty> for Value {
54                fn from(val: $ty) -> Value {
55                    Value(vec![val.into()])
56                }
57            }
58
59            impl TryFrom<&ValueSlice> for $ty {
60                type Error = InvalidBuiltinDecode;
61
62                fn try_from(value: &ValueSlice) -> Result<$ty, InvalidBuiltinDecode> {
63                    if value.0.len() == 1 {
64                        Ok(<$ty>::try_from(&value.0[0])?)
65                    } else {
66                        Err(InvalidBuiltinDecode(stringify!($ty)))
67                    }
68                }
69            }
70        )*
71    }
72}
73
74via_hash_output!(
75    ContractAddress,
76    UserAddress,
77    Nonce,
78    Nullifier,
79    Commitment,
80    PublicKey,
81    UnshieldedTokenType,
82    ShieldedTokenType
83);
84
85impl Aligned for Info {
86    fn alignment() -> Alignment {
87        Alignment::concat([
88            &Nonce::alignment(),
89            &ShieldedTokenType::alignment(),
90            &u128::alignment(),
91        ])
92    }
93}
94
95impl Aligned for QualifiedInfo {
96    fn alignment() -> Alignment {
97        Alignment::concat([
98            &Nonce::alignment(),
99            &ShieldedTokenType::alignment(),
100            &u128::alignment(),
101            &u64::alignment(),
102        ])
103    }
104}
105
106impl Aligned for Recipient {
107    fn alignment() -> Alignment {
108        Alignment::concat([
109            &bool::alignment(),
110            &<[u8; 32]>::alignment(),
111            &<[u8; 32]>::alignment(),
112        ])
113    }
114}
115
116impl From<Info> for Value {
117    fn from(info: Info) -> Value {
118        Value(vec![
119            info.nonce.into(),
120            info.type_.into(),
121            info.value.into(),
122        ])
123    }
124}
125
126impl TryFrom<&ValueSlice> for Info {
127    type Error = InvalidBuiltinDecode;
128
129    fn try_from(value: &ValueSlice) -> Result<Info, InvalidBuiltinDecode> {
130        if value.0.len() == 3 {
131            Ok(Info {
132                nonce: (&value.0[0]).try_into()?,
133                type_: (&value.0[1]).try_into()?,
134                value: (&value.0[2]).try_into()?,
135            })
136        } else {
137            Err(InvalidBuiltinDecode("CoinInfo"))
138        }
139    }
140}
141
142impl From<QualifiedInfo> for Value {
143    fn from(info: QualifiedInfo) -> Value {
144        Value(vec![
145            info.nonce.into(),
146            info.type_.into(),
147            info.value.into(),
148            info.mt_index.into(),
149        ])
150    }
151}
152
153impl TryFrom<&ValueSlice> for QualifiedInfo {
154    type Error = InvalidBuiltinDecode;
155
156    fn try_from(value: &ValueSlice) -> Result<QualifiedInfo, InvalidBuiltinDecode> {
157        if value.0.len() == 4 {
158            Ok(QualifiedInfo {
159                nonce: (&value.0[0]).try_into()?,
160                type_: (&value.0[1]).try_into()?,
161                value: (&value.0[2]).try_into()?,
162                mt_index: (&value.0[3]).try_into()?,
163            })
164        } else {
165            Err(InvalidBuiltinDecode("QualifiedCoinInfo"))
166        }
167    }
168}
169
170impl From<Recipient> for Value {
171    fn from(recipient: Recipient) -> Value {
172        Value(match recipient {
173            Recipient::User(pk) => vec![true.into(), pk.into(), ().into()],
174            Recipient::Contract(contract) => vec![false.into(), ().into(), contract.into()],
175        })
176    }
177}
178
179impl TryFrom<&ValueSlice> for Recipient {
180    type Error = InvalidBuiltinDecode;
181
182    fn try_from(value: &ValueSlice) -> Result<Recipient, InvalidBuiltinDecode> {
183        if value.0.len() == 3 {
184            let is_left: bool = (&value.0[0]).try_into()?;
185            if is_left {
186                <()>::try_from(&value.0[2])?;
187                Ok(Recipient::User((&value.0[1]).try_into()?))
188            } else {
189                <()>::try_from(&value.0[1])?;
190                Ok(Recipient::Contract((&value.0[2]).try_into()?))
191            }
192        } else {
193            Err(InvalidBuiltinDecode("Recipient"))
194        }
195    }
196}
197
198impl TryFrom<&ValueSlice> for SenderEvidence<'static> {
199    type Error = InvalidBuiltinDecode;
200
201    fn try_from(value: &ValueSlice) -> Result<SenderEvidence<'static>, InvalidBuiltinDecode> {
202        if value.0.len() == 3 {
203            let is_left: bool = (&value.0[0]).try_into()?;
204            if is_left {
205                <()>::try_from(&value.0[2])?;
206                Ok(SenderEvidence::User(std::borrow::Cow::Owned(
207                    (&value.0[1]).try_into()?,
208                )))
209            } else {
210                <()>::try_from(&value.0[1])?;
211                Ok(SenderEvidence::Contract((&value.0[2]).try_into()?))
212            }
213        } else {
214            Err(InvalidBuiltinDecode("SenderEvidence"))
215        }
216    }
217}