Skip to content

Commit e884e49

Browse files
committed
Docs: fix make test-docs and add documentation for network conf
1 parent 0e565a3 commit e884e49

File tree

11 files changed

+755
-32
lines changed

11 files changed

+755
-32
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

core/src/chain_id.rs

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,18 @@ use std::{
1212
use binprot::{BinProtRead, BinProtWrite};
1313
use serde::{Deserialize, Deserializer, Serialize, Serializer};
1414

15+
/// Unique identifier for a Mina blockchain network.
16+
///
17+
/// The ChainId is a 32-byte hash that uniquely identifies a specific Mina network
18+
/// configuration. It is computed from various network parameters including:
19+
/// - Genesis state hash
20+
/// - Constraint system digests (circuit verification hashes)
21+
/// - Protocol constants (timing parameters, fees, etc.)
22+
/// - Protocol version numbers
23+
/// - Transaction pool configuration
24+
///
25+
/// Different networks (mainnet, devnet) will have different ChainIds, and any
26+
/// change to core protocol parameters will result in a new ChainId.
1527
#[derive(Clone, PartialEq, Eq)]
1628
pub struct ChainId([u8; 32]);
1729

@@ -45,6 +57,22 @@ fn hash_genesis_constants(
4557
}
4658

4759
impl ChainId {
60+
/// Compute a ChainId from network configuration parameters.
61+
///
62+
/// This function deterministically generates a unique ChainId by hashing
63+
/// together all the parameters that define a Mina network's behavior.
64+
/// Any change to these parameters will result in a different ChainId.
65+
///
66+
/// # Arguments
67+
/// * `constraint_system_digests` - MD5 hashes of the zkSNARK circuits
68+
/// * `genesis_state_hash` - Hash of the network's genesis block
69+
/// * `genesis_constants` - Protocol timing and behavior constants
70+
/// * `protocol_transaction_version` - Transaction format version
71+
/// * `protocol_network_version` - Network protocol version
72+
/// * `tx_max_pool_size` - Maximum transaction pool size
73+
///
74+
/// # Returns
75+
/// A new ChainId uniquely identifying this network configuration
4876
pub fn compute(
4977
constraint_system_digests: &[Md5],
5078
genesis_state_hash: &StateHash,
@@ -68,7 +96,15 @@ impl ChainId {
6896
ChainId(hasher.finalize().try_into().unwrap())
6997
}
7098

71-
/// Computes shared key for libp2p Pnet protocol.
99+
/// Computes the preshared key for libp2p private network protocol.
100+
///
101+
/// This creates a network-specific encryption key that ensures nodes
102+
/// can only communicate with other nodes on the same Mina network.
103+
/// The key is derived from the ChainId to automatically separate
104+
/// different networks at the transport layer.
105+
///
106+
/// # Returns
107+
/// A 32-byte preshared key for libp2p Pnet
72108
pub fn preshared_key(&self) -> [u8; 32] {
73109
let mut hasher = Blake2b256::default();
74110
hasher.update(b"/coda/0.0.1/");
@@ -79,10 +115,22 @@ impl ChainId {
79115
psk_fixed
80116
}
81117

118+
/// Convert the ChainId to a hexadecimal string representation.
119+
///
120+
/// # Returns
121+
/// A 64-character hex string (32 bytes * 2 hex chars per byte)
82122
pub fn to_hex(&self) -> String {
83123
hex::encode(self.0)
84124
}
85125

126+
/// Parse a ChainId from a hexadecimal string.
127+
///
128+
/// # Arguments
129+
/// * `s` - A 64-character hex string representing the ChainId
130+
///
131+
/// # Returns
132+
/// * `Ok(ChainId)` if the string is valid
133+
/// * `Err(hex::FromHexError)` if the string is malformed
86134
pub fn from_hex(s: &str) -> Result<ChainId, hex::FromHexError> {
87135
let h = hex::decode(s)?;
88136
let bs = h[..32]
@@ -91,6 +139,16 @@ impl ChainId {
91139
Ok(ChainId(bs))
92140
}
93141

142+
/// Create a ChainId from raw bytes.
143+
///
144+
/// # Arguments
145+
/// * `bytes` - A byte slice containing at least 32 bytes
146+
///
147+
/// # Returns
148+
/// A ChainId using the first 32 bytes of the input
149+
///
150+
/// # Panics
151+
/// Panics if the input contains fewer than 32 bytes
94152
pub fn from_bytes(bytes: &[u8]) -> ChainId {
95153
let mut arr = [0u8; 32];
96154
arr.copy_from_slice(&bytes[..32]);
@@ -147,11 +205,25 @@ impl Debug for ChainId {
147205
}
148206
}
149207

208+
/// The ChainId for the Mina devnet.
209+
///
210+
/// This ChainId identifies the development/testing network and is computed
211+
/// from devnet's specific configuration parameters. Nodes must use this
212+
/// ChainId to participate in the devnet.
213+
///
214+
/// Hex representation: `29936104443aaf264a7f0192ac64b1c7173198c1ed404c1bcff5e562e05eb7f6`
150215
pub const DEVNET_CHAIN_ID: ChainId = ChainId([
151216
0x29, 0x93, 0x61, 0x04, 0x44, 0x3a, 0xaf, 0x26, 0x4a, 0x7f, 0x01, 0x92, 0xac, 0x64, 0xb1, 0xc7,
152217
0x17, 0x31, 0x98, 0xc1, 0xed, 0x40, 0x4c, 0x1b, 0xcf, 0xf5, 0xe5, 0x62, 0xe0, 0x5e, 0xb7, 0xf6,
153218
]);
154219

220+
/// The ChainId for the Mina mainnet.
221+
///
222+
/// This ChainId identifies the production Mina blockchain and is computed
223+
/// from mainnet's specific configuration parameters. Nodes must use this
224+
/// ChainId to participate in the mainnet.
225+
///
226+
/// Hex representation: `a7351abc7ddf2ea92d1b38cc8e636c271c1dfd2c081c637f62ebc2af34eb7cc1`
155227
pub const MAINNET_CHAIN_ID: ChainId = ChainId([
156228
0xa7, 0x35, 0x1a, 0xbc, 0x7d, 0xdf, 0x2e, 0xa9, 0x2d, 0x1b, 0x38, 0xcc, 0x8e, 0x63, 0x6c, 0x27,
157229
0x1c, 0x1d, 0xfd, 0x2c, 0x08, 0x1c, 0x63, 0x7f, 0x62, 0xeb, 0xc2, 0xaf, 0x34, 0xeb, 0x7c, 0xc1,

core/src/constants.rs

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,196 @@ pub fn constraint_constants() -> &'static ConstraintConstants {
1414
NetworkConfig::global().constraint_constants
1515
}
1616

17+
/// Constants that define fork-specific blockchain state.
18+
///
19+
/// Fork constants specify the blockchain state at which a protocol upgrade or fork occurred.
20+
/// These are used to handle protocol changes and ensure compatibility across network upgrades.
1721
#[derive(Clone, Debug)]
1822
pub struct ForkConstants {
23+
/// Hash of the blockchain state at the fork point
1924
pub state_hash: Fp,
25+
26+
/// Blockchain length (number of blocks) at the fork point
2027
pub blockchain_length: u32,
28+
29+
/// Global slot number since genesis at the fork point
2130
pub global_slot_since_genesis: u32,
2231
}
2332

33+
/// Protocol constraint constants that define core blockchain behavior.
34+
///
35+
/// These constants configure fundamental aspects of the Mina protocol including consensus,
36+
/// transaction processing, economic parameters, and ledger structure. They are compile-time
37+
/// parameters that must be consistent across all nodes in a network.
38+
///
39+
/// ## Consensus and Timing Parameters
40+
///
41+
/// The consensus mechanism relies on slot-based timing where blocks are produced in discrete
42+
/// time slots. The timing hierarchy is:
43+
/// - **Slots**: Basic time units for block production
44+
/// - **Sub-windows**: Groups of slots within an epoch
45+
/// - **Windows**: Collections of sub-windows that define epoch structure
46+
/// - **Epochs**: Complete consensus periods
47+
///
48+
/// ## Economic Parameters
49+
///
50+
/// The protocol defines economic incentives through fees and rewards:
51+
/// - **Coinbase rewards**: Paid to block producers for successful blocks
52+
/// - **Account creation fees**: Required to create new accounts on the ledger
53+
/// - **Supercharged rewards**: Multiplier for enhanced block producer rewards
54+
///
55+
/// ## Ledger and Transaction Structure
56+
///
57+
/// The ledger uses a Merkle tree structure for efficient verification:
58+
/// - **Ledger depth**: Determines the maximum number of accounts (2^depth)
59+
/// - **Transaction capacity**: Limits transactions per block for performance
60+
/// - **Pending coinbase**: Manages delayed coinbase payouts
61+
///
62+
/// ## Usage Example
63+
///
64+
/// ```rust
65+
/// use openmina_core::constants::constraint_constants;
66+
///
67+
/// // Access global constraint constants
68+
/// let constants = constraint_constants();
69+
///
70+
/// // Calculate slots per window
71+
/// let slots_per_window = constants.sub_windows_per_window;
72+
/// println!("Sub-windows per window: {}", slots_per_window);
73+
///
74+
/// // Get block timing
75+
/// let block_time_ms = constants.block_window_duration_ms;
76+
/// println!("Block time: {}ms", block_time_ms);
77+
///
78+
/// // Check economic parameters
79+
/// let coinbase_reward = constants.coinbase_amount;
80+
/// let creation_fee = constants.account_creation_fee;
81+
/// println!("Coinbase: {} nanomina, Account fee: {} nanomina",
82+
/// coinbase_reward, creation_fee);
83+
/// ```
84+
///
85+
/// ## Network Differences
86+
///
87+
/// While most constraint constants are identical across networks, some parameters
88+
/// may differ between mainnet and testnets for development purposes.
89+
///
90+
/// Related OCaml implementation: <https://github.com/MinaProtocol/mina/tree/compatible/src/config>
91+
/// Protocol specification: <https://github.com/MinaProtocol/mina/blob/compatible/docs/specs/types_and_structures/serialized_key.md>
2492
#[derive(Clone, Debug)]
2593
pub struct ConstraintConstants {
94+
/// Number of sub-windows that make up a complete window.
95+
///
96+
/// Used in the consensus mechanism to structure epoch timing. Combined with
97+
/// `slots_per_sub_window` from protocol constants, this determines the total
98+
/// slots per window: `slots_per_window = slots_per_sub_window × sub_windows_per_window`.
99+
///
100+
/// **Value**: 11 (both mainnet and devnet)
26101
pub sub_windows_per_window: u64,
102+
103+
/// Depth of the account ledger Merkle tree.
104+
///
105+
/// This determines the maximum number of accounts that can be stored in the ledger:
106+
/// `max_accounts = 2^ledger_depth`. The depth affects proof sizes and verification time.
107+
/// A larger depth allows more accounts but increases computational overhead.
108+
///
109+
/// **Value**: 35 (supports ~34 billion accounts)
110+
/// **Usage**: Account addressing, sparse ledger proofs, zkSNARK constraints
27111
pub ledger_depth: u64,
112+
113+
/// Number of blocks to delay before SNARK work becomes available.
114+
///
115+
/// This creates a buffer period between when a block is produced and when
116+
/// the associated SNARK work can be included in subsequent blocks. This delay
117+
/// helps ensure fair distribution of SNARK work opportunities.
118+
///
119+
/// **Value**: 2 blocks
120+
/// **Usage**: SNARK work scheduling, proof marketplace timing
28121
pub work_delay: u64,
122+
123+
/// Duration of each block production slot in milliseconds.
124+
///
125+
/// This is the fundamental time unit for the consensus protocol. Block producers
126+
/// attempt to create blocks during their assigned slots. The duration affects
127+
/// network synchronization requirements and transaction confirmation times.
128+
///
129+
/// **Value**: 180,000ms (3 minutes)
130+
/// **Usage**: Consensus timing, slot calculations, network synchronization
29131
pub block_window_duration_ms: u64,
132+
133+
/// Log₂ of the maximum number of transactions per block.
134+
///
135+
/// The actual transaction capacity is `2^transaction_capacity_log_2`. This logarithmic
136+
/// representation is used because the value directly affects zkSNARK circuit constraints.
137+
/// Higher capacity allows more transactions but increases block processing time.
138+
///
139+
/// Corresponds to `transaction_capacity` in the protocol specification, which defines
140+
/// the maximum transactions per block (represented as `two_to_the`).
141+
///
142+
/// **Value**: 7 (supports 2^7 = 128 transactions per block)
143+
/// **Usage**: Transaction pool management, block construction, circuit constraints
30144
pub transaction_capacity_log_2: u64,
145+
146+
/// Number of confirmations before coinbase reward is spendable.
147+
///
148+
/// Coinbase rewards are not immediately spendable and require a certain number
149+
/// of block confirmations before they can be used. This parameter defines the
150+
/// depth of the pending coinbase Merkle tree structure used to track these
151+
/// delayed rewards until they mature.
152+
///
153+
/// **Value**: 5 (coinbase rewards require 5 block confirmations)
154+
/// **Usage**: Coinbase reward management, staged ledger operations, reward maturity
31155
pub pending_coinbase_depth: usize,
156+
157+
/// Block reward amount in nanomina (10⁻⁹ MINA).
158+
///
159+
/// This is the base reward paid to block producers for successfully creating a block.
160+
/// The amount is specified in nanomina, where 1 MINA = 10⁹ nanomina. Block producers
161+
/// may receive additional rewards through the supercharged coinbase mechanism.
162+
///
163+
/// **Value**: 720,000,000,000 nanomina (720 MINA)
164+
/// **Usage**: Block producer rewards, economic incentives, reward calculations
32165
pub coinbase_amount: u64,
166+
167+
/// Multiplier for supercharged coinbase rewards.
168+
///
169+
/// Supercharged rewards were designed to provide double block rewards (factor of 2)
170+
/// to block producers staking with unlocked tokens during the early mainnet period
171+
/// following the 2021 launch. This mechanism incentivized participation and orderly
172+
/// markets after mainnet launch.
173+
///
174+
/// **Historical values**:
175+
/// - Original mainnet: 2 (double rewards for unlocked tokens)
176+
/// - Berkeley hardfork (June 2024): 1 (supercharged rewards removed via MIP1)
177+
///
178+
/// The removal was decided by community vote on January 1, 2023, as proposed by
179+
/// community member Gareth Davies. This change ensures uniform rewards for all
180+
/// tokens and reduces inflation, promoting a sustainable economic model.
181+
///
182+
/// **References**:
183+
/// - Berkeley Upgrade: <https://minaprotocol.com/blog/minas-berkeley-upgrade-what-to-expect>
184+
/// - Supercharged Rewards Removal: <https://minaprotocol.com/blog/update-on-minas-supercharged-rewards-schedule>
185+
/// - Original Proposal: <https://github.com/MinaProtocol/mina/issues/5753>
186+
///
187+
/// **Usage**: Enhanced reward calculations, incentive mechanisms
33188
pub supercharged_coinbase_factor: u64,
189+
190+
/// Fee required to create a new account in nanomina.
191+
///
192+
/// When a transaction creates a new account that doesn't exist on the ledger,
193+
/// this fee is charged in addition to the transaction fee. This prevents
194+
/// spam account creation and manages ledger growth.
195+
///
196+
/// **Value**: 1,000,000,000 nanomina (1 MINA)
197+
/// **Usage**: Account creation, transaction validation, fee calculations
34198
pub account_creation_fee: u64,
199+
200+
/// Optional fork constants defining a protocol upgrade point.
201+
///
202+
/// When present, these constants specify the blockchain state at which a protocol
203+
/// fork or upgrade occurred. This allows the protocol to handle transitions between
204+
/// different versions while maintaining consensus.
205+
///
206+
/// **Usage**: Protocol upgrades, compatibility handling, genesis configuration
35207
pub fork: Option<ForkConstants>,
36208
}
37209
#[derive(Clone, Debug, BinProtWrite)]

0 commit comments

Comments
 (0)