darkfi_sdk/crypto/
contract_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
19#[cfg(feature = "async")]
20use darkfi_serial::async_trait;
21use darkfi_serial::{serialize, SerialDecodable, SerialEncodable};
22use lazy_static::lazy_static;
23use pasta_curves::{group::ff::PrimeField, pallas};
24
25use super::{poseidon_hash, PublicKey, SecretKey};
26use crate::error::ContractError;
27
28lazy_static! {
29    // The idea here is that 0 is not a valid x coordinate for any pallas point,
30    // therefore a signature cannot be produced for such IDs. This allows us to
31    // avoid hardcoding contract IDs for arbitrary contract deployments, because
32    // the contracts with 0 as their x coordinate can never have a valid signature.
33
34    /// Derivation prefix for `ContractId`
35    pub static ref CONTRACT_ID_PREFIX: pallas::Base = pallas::Base::from(42);
36
37    /// Contract ID for the native money contract
38    ///
39    /// `BZHKGQ26bzmBithTQYTJtjo2QdCqpkR9tjSBopT4yf4o`
40    pub static ref MONEY_CONTRACT_ID: ContractId =
41        ContractId::from(poseidon_hash([*CONTRACT_ID_PREFIX, pallas::Base::zero(), pallas::Base::from(0)]));
42
43    /// Contract ID for the native DAO contract
44    ///
45    /// `Fd8kfCuqU8BoFFp6GcXv5pC8XXRkBK7gUPQX5XDz7iXj`
46    pub static ref DAO_CONTRACT_ID: ContractId =
47        ContractId::from(poseidon_hash([*CONTRACT_ID_PREFIX, pallas::Base::zero(), pallas::Base::from(1)]));
48
49    /// Contract ID for the native Deployooor contract
50    ///
51    /// `EJs7oEjKkvCeEVCmpRsd6fEoTGCFJ7WKUBfmAjwaegN`
52    pub static ref DEPLOYOOOR_CONTRACT_ID: ContractId =
53        ContractId::from(poseidon_hash([*CONTRACT_ID_PREFIX, pallas::Base::zero(), pallas::Base::from(2)]));
54}
55
56/// ContractId represents an on-chain identifier for a certain smart contract.
57#[derive(Copy, Clone, Debug, Eq, PartialEq, SerialEncodable, SerialDecodable)]
58pub struct ContractId(pallas::Base);
59
60impl ContractId {
61    /// Derives a `ContractId` from a `SecretKey` (deploy key)
62    pub fn derive(deploy_key: SecretKey) -> Self {
63        let public_key = PublicKey::from_secret(deploy_key);
64        let (x, y) = public_key.xy();
65        let hash = poseidon_hash([*CONTRACT_ID_PREFIX, x, y]);
66        Self(hash)
67    }
68
69    /// Derive a contract ID from a `PublicKey`
70    pub fn derive_public(public_key: PublicKey) -> Self {
71        let (x, y) = public_key.xy();
72        let hash = poseidon_hash([*CONTRACT_ID_PREFIX, x, y]);
73        Self(hash)
74    }
75
76    /// Get the inner `pallas::Base` element.
77    pub fn inner(&self) -> pallas::Base {
78        self.0
79    }
80
81    /// Create a `ContractId` object from given bytes.
82    pub fn from_bytes(x: [u8; 32]) -> Result<Self, ContractError> {
83        match pallas::Base::from_repr(x).into() {
84            Some(v) => Ok(Self(v)),
85            None => Err(ContractError::IoError(
86                "Failed to instantiate ContractId from bytes".to_string(),
87            )),
88        }
89    }
90
91    /// Convert a `ContractId` object to its byte representation
92    pub fn to_bytes(&self) -> [u8; 32] {
93        self.0.to_repr()
94    }
95
96    /// `blake3(self || tree_name)` is used in databases to have a
97    /// fixed-size name for a contract's state db.
98    pub fn hash_state_id(&self, tree_name: &str) -> [u8; 32] {
99        let mut hasher = blake3::Hasher::new();
100        hasher.update(&serialize(self));
101        hasher.update(tree_name.as_bytes());
102        let id = hasher.finalize();
103        *id.as_bytes()
104    }
105}
106
107use core::str::FromStr;
108crate::fp_from_bs58!(ContractId);
109crate::fp_to_bs58!(ContractId);
110crate::ty_from_fp!(ContractId);