darkfi_money_contract/model/token_id.rs
1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2026 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 darkfi_sdk::{
20 crypto::{
21 constants::DRK_TOKEN_ID_PERSONALIZATION, pasta_prelude::PrimeField, util::hash_to_base,
22 },
23 error::ContractError,
24 pasta::pallas,
25};
26use darkfi_serial::{SerialDecodable, SerialEncodable};
27use lazy_static::lazy_static;
28
29#[cfg(feature = "client")]
30use darkfi_serial::async_trait;
31
32use super::poseidon_hash;
33
34lazy_static! {
35 /// Native DARK token ID.
36 /// It does not correspond to any real commitment since we only rely on this value as
37 /// a constant.
38 pub static ref DARK_TOKEN_ID: TokenId = TokenId(hash_to_base(&[0x69], &[DRK_TOKEN_ID_PERSONALIZATION]));
39}
40
41/// TokenId represents an on-chain identifier for a certain token.
42#[derive(Copy, Clone, Debug, Eq, PartialEq, SerialEncodable, SerialDecodable)]
43pub struct TokenId(pallas::Base);
44
45impl TokenId {
46 /// Derives a `TokenId` from provided function id,
47 /// user data and blind.
48 pub fn derive_from(
49 func_id: pallas::Base,
50 user_data: pallas::Base,
51 blind: pallas::Base,
52 ) -> Self {
53 let token_id = poseidon_hash([func_id, user_data, blind]);
54 Self(token_id)
55 }
56
57 /// Get the inner `pallas::Base` element.
58 pub fn inner(&self) -> pallas::Base {
59 self.0
60 }
61
62 /// Create a `TokenId` object from given bytes, erroring if the input
63 /// bytes are noncanonical.
64 pub fn from_bytes(x: [u8; 32]) -> Result<Self, ContractError> {
65 match pallas::Base::from_repr(x).into() {
66 Some(v) => Ok(Self(v)),
67 None => {
68 Err(ContractError::IoError("Failed to instantiate TokenId from bytes".to_string()))
69 }
70 }
71 }
72
73 /// Convert the `TokenId` type into 32 raw bytes
74 pub fn to_bytes(&self) -> [u8; 32] {
75 self.0.to_repr()
76 }
77}
78
79use core::str::FromStr;
80darkfi_sdk::fp_from_bs58!(TokenId);
81darkfi_sdk::fp_to_bs58!(TokenId);
82darkfi_sdk::ty_from_fp!(TokenId);