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 */
1819use std::str::FromStr;
2021#[cfg(feature = "async")]
22use darkfi_serial::async_trait;
23use darkfi_serial::{SerialDecodable, SerialEncodable};
24use pasta_curves::pallas;
2526use super::{pasta_prelude::*, poseidon_hash, ContractId};
27use crate::{fp_from_bs58, fp_to_bs58, ty_from_fp, ContractError};
2829pub type FunctionCode = u8;
3031#[derive(Copy, Clone, Debug, Eq, PartialEq, SerialEncodable, SerialDecodable)]
32pub struct FuncRef {
33pub contract_id: ContractId,
34pub func_code: FunctionCode,
35}
3637impl FuncRef {
38pub fn to_func_id(&self) -> FuncId {
39let func_id =
40 poseidon_hash([self.contract_id.inner(), pallas::Base::from(self.func_code as u64)]);
41 FuncId(func_id)
42 }
43}
4445#[derive(Copy, Clone, Debug, Eq, PartialEq, SerialEncodable, SerialDecodable)]
46pub struct FuncId(pallas::Base);
4748impl FuncId {
49pub fn none() -> Self {
50Self(pallas::Base::ZERO)
51 }
5253pub fn inner(&self) -> pallas::Base {
54self.0
55}
5657/// Create a `FuncId` object from given bytes, erroring if the
58 /// input bytes are noncanonical.
59pub fn from_bytes(x: [u8; 32]) -> Result<Self, ContractError> {
60match pallas::Base::from_repr(x).into() {
61Some(v) => Ok(Self(v)),
62None => {
63Err(ContractError::IoError("Failed to instantiate FuncId from bytes".to_string()))
64 }
65 }
66 }
6768/// Convert the `FuncId` type into 32 raw bytes
69pub fn to_bytes(&self) -> [u8; 32] {
70self.0.to_repr()
71 }
72}
7374fp_from_bs58!(FuncId);
75fp_to_bs58!(FuncId);
76ty_from_fp!(FuncId);