darkfi_sdk/crypto/
func_ref.rs

1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2025 Dyne.org foundation
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use std::str::FromStr;
20
21#[cfg(feature = "async")]
22use darkfi_serial::async_trait;
23use darkfi_serial::{SerialDecodable, SerialEncodable};
24use pasta_curves::pallas;
25
26use super::{pasta_prelude::*, poseidon_hash, ContractId};
27use crate::{fp_from_bs58, fp_to_bs58, ty_from_fp, ContractError};
28
29pub type FunctionCode = u8;
30
31#[derive(Copy, Clone, Debug, Eq, PartialEq, SerialEncodable, SerialDecodable)]
32pub struct FuncRef {
33    pub contract_id: ContractId,
34    pub func_code: FunctionCode,
35}
36
37impl FuncRef {
38    pub fn to_func_id(&self) -> FuncId {
39        let func_id =
40            poseidon_hash([self.contract_id.inner(), pallas::Base::from(self.func_code as u64)]);
41        FuncId(func_id)
42    }
43}
44
45#[derive(Copy, Clone, Debug, Eq, PartialEq, SerialEncodable, SerialDecodable)]
46pub struct FuncId(pallas::Base);
47
48impl FuncId {
49    pub fn none() -> Self {
50        Self(pallas::Base::ZERO)
51    }
52
53    pub fn inner(&self) -> pallas::Base {
54        self.0
55    }
56
57    /// Create a `FuncId` object from given bytes, erroring if the
58    /// input bytes are noncanonical.
59    pub fn from_bytes(x: [u8; 32]) -> Result<Self, ContractError> {
60        match pallas::Base::from_repr(x).into() {
61            Some(v) => Ok(Self(v)),
62            None => {
63                Err(ContractError::IoError("Failed to instantiate FuncId from bytes".to_string()))
64            }
65        }
66    }
67
68    /// Convert the `FuncId` type into 32 raw bytes
69    pub fn to_bytes(&self) -> [u8; 32] {
70        self.0.to_repr()
71    }
72}
73
74fp_from_bs58!(FuncId);
75fp_to_bs58!(FuncId);
76ty_from_fp!(FuncId);