darkfi_money_contract/model/token_id.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 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 // Is this even needed? Not used elsewhere except here.
36 /// Derivation prefix for `TokenId`
37 pub static ref TOKEN_ID_PREFIX: pallas::Base = pallas::Base::from(69);
38
39 /// Native DARK token ID.
40 /// It does not correspond to any real commitment since we only rely on this value as
41 /// a constant.
42 pub static ref DARK_TOKEN_ID: TokenId = TokenId(hash_to_base(&[0x69], &[DRK_TOKEN_ID_PERSONALIZATION]));
43}
44
45/// TokenId represents an on-chain identifier for a certain token.
46#[derive(Copy, Clone, Debug, Eq, PartialEq, SerialEncodable, SerialDecodable)]
47pub struct TokenId(pallas::Base);
48
49impl TokenId {
50 /// Derives a `TokenId` from provided function id,
51 /// user data and blind.
52 pub fn derive_from(
53 func_id: pallas::Base,
54 user_data: pallas::Base,
55 blind: pallas::Base,
56 ) -> Self {
57 let token_id = poseidon_hash([func_id, user_data, blind]);
58 Self(token_id)
59 }
60
61 /// Get the inner `pallas::Base` element.
62 pub fn inner(&self) -> pallas::Base {
63 self.0
64 }
65
66 /// Create a `TokenId` object from given bytes, erroring if the input
67 /// bytes are noncanonical.
68 pub fn from_bytes(x: [u8; 32]) -> Result<Self, ContractError> {
69 match pallas::Base::from_repr(x).into() {
70 Some(v) => Ok(Self(v)),
71 None => {
72 Err(ContractError::IoError("Failed to instantiate TokenId from bytes".to_string()))
73 }
74 }
75 }
76
77 /// Convert the `TokenId` type into 32 raw bytes
78 pub fn to_bytes(&self) -> [u8; 32] {
79 self.0.to_repr()
80 }
81}
82
83use core::str::FromStr;
84darkfi_sdk::fp_from_bs58!(TokenId);
85darkfi_sdk::fp_to_bs58!(TokenId);
86darkfi_sdk::ty_from_fp!(TokenId);