Skip to content

Commit 1a7db35

Browse files
authored
Merge pull request #1554 from o1-labs/dw/protocol-doc
Core: add documentation for constants.rs
2 parents aedace1 + f32cf7f commit 1a7db35

File tree

2 files changed

+186
-11
lines changed

2 files changed

+186
-11
lines changed

core/src/chain_id.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
//! ```rust
5757
//! use mina_core::ChainId;
5858
//!
59+
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
5960
//! // Use predefined network
6061
//! let mainnet_id = mina_core::MAINNET_CHAIN_ID;
6162
//! println!("Mainnet ID: {}", mainnet_id);
@@ -65,6 +66,8 @@
6566
//!
6667
//! // Generate preshared key for private networking
6768
//! let psk = chain_id.preshared_key();
69+
//! # Ok(())
70+
//! # }
6871
//! ```
6972
7073
use mina_p2p_messages::v2::{
@@ -135,6 +138,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer};
135138
/// ```rust
136139
/// use mina_core::{ChainId, MAINNET_CHAIN_ID};
137140
///
141+
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
138142
/// // Use predefined mainnet ID
139143
/// let mainnet = MAINNET_CHAIN_ID;
140144
/// println!("Mainnet: {}", mainnet.to_hex());
@@ -144,6 +148,8 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer};
144148
///
145149
/// // Generate private network key
146150
/// let psk = mainnet.preshared_key();
151+
/// # Ok(())
152+
/// # }
147153
/// ```
148154
#[derive(Clone, PartialEq, Eq)]
149155
pub struct ChainId([u8; 32]);
@@ -221,6 +227,11 @@ impl ChainId {
221227
/// use mina_core::ChainId;
222228
/// use mina_p2p_messages::v2::UnsignedExtendedUInt32StableV1;
223229
///
230+
/// # // Use actual devnet values for the example
231+
/// # let constraint_digests = mina_core::network::devnet::CONSTRAINT_SYSTEM_DIGESTS;
232+
/// # let genesis_hash: mina_p2p_messages::v2::StateHash =
233+
/// # "3NL93SipJfAMNDBRfQ8Uo8LPovC74mnJZfZYB5SK7mTtkL72dsPx".parse().unwrap();
234+
/// # let protocol_constants = mina_core::constants::PROTOCOL_CONSTANTS.clone();
224235
/// let chain_id = ChainId::compute(
225236
/// &constraint_digests,
226237
/// &genesis_hash,
@@ -349,9 +360,12 @@ impl ChainId {
349360
/// ```rust
350361
/// use mina_core::ChainId;
351362
///
363+
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
352364
/// let chain_id = ChainId::from_hex(
353365
/// "a7351abc7ddf2ea92d1b38cc8e636c271c1dfd2c081c637f62ebc2af34eb7cc1"
354366
/// )?;
367+
/// # Ok(())
368+
/// # }
355369
/// ```
356370
pub fn from_hex(s: &str) -> Result<ChainId, hex::FromHexError> {
357371
let h = hex::decode(s)?;

core/src/constants.rs

Lines changed: 172 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,35 +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

24-
/// Protocol constraint constants
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
42+
/// produced in discrete 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 mina_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>
2592
#[derive(Clone, Debug)]
2693
pub struct ConstraintConstants {
27-
/// Number of sub-windows in a single slot window
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)
28101
pub sub_windows_per_window: u64,
29-
/// Depth of the account ledger Merkle tree
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
30111
pub ledger_depth: u64,
31-
/// Number of slots to delay SNARK work for proof generation
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
32121
pub work_delay: u64,
33-
/// Duration of each block window in milliseconds
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
34131
pub block_window_duration_ms: u64,
35-
/// Log2 of maximum transactions per block
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
36144
pub transaction_capacity_log_2: u64,
37-
/// Depth of the pending coinbase Merkle tree
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
38155
pub pending_coinbase_depth: usize,
39-
/// Base amount awarded for producing a block
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
40165
pub coinbase_amount: u64,
41-
/// Multiplier for coinbase when account is "supercharged"
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
42188
pub supercharged_coinbase_factor: u64,
43-
/// Fee charged for creating a new account
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
44198
pub account_creation_fee: u64,
45-
/// Optional fork configuration for protocol upgrades
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
46207
pub fork: Option<ForkConstants>,
47208
}
48209
#[derive(Clone, Debug, BinProtWrite)]

0 commit comments

Comments
 (0)