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