1use std::{
2 fs::File,
3 io::{BufRead, BufReader, Read},
4 net::IpAddr,
5 path::Path,
6 sync::Arc,
7 time::Duration,
8};
9
10use anyhow::Context;
11use ledger::proofs::provers::BlockProver;
12use mina_p2p_messages::v2::{self, NonZeroCurvePoint};
13use node::{
14 account::AccountSecretKey,
15 daemon_json::Daemon,
16 p2p::{
17 channels::ChannelId, connection::outgoing::P2pConnectionOutgoingInitOpts,
18 identity::SecretKey as P2pSecretKey, P2pLimits, P2pMeshsubConfig, P2pTimeouts,
19 },
20 service::Recorder,
21 snark::{get_srs, BlockVerifier, TransactionVerifier, VerifierSRS},
22 transition_frontier::{archive::archive_config::ArchiveConfig, genesis::GenesisConfig},
23 BlockProducerConfig, GlobalConfig, LedgerConfig, P2pConfig, SnarkConfig, SnarkerConfig,
24 SnarkerStrategy, TransitionFrontierConfig,
25};
26use openmina_core::{consensus::ConsensusConstants, constants::constraint_constants};
27use openmina_node_common::{archive::config::ArchiveStorageOptions, p2p::TaskSpawner};
28use rand::Rng;
29
30use crate::NodeServiceBuilder;
31
32use super::Node;
33
34pub struct NodeBuilder {
35 rng_seed: [u8; 32],
36 custom_initial_time: Option<redux::Timestamp>,
37 genesis_config: Arc<GenesisConfig>,
38 p2p: P2pConfig,
39 p2p_sec_key: Option<P2pSecretKey>,
40 p2p_is_seed: bool,
41 p2p_is_started: bool,
42 block_producer: Option<BlockProducerConfig>,
43 archive: Option<ArchiveConfig>,
44 snarker: Option<SnarkerConfig>,
45 service: NodeServiceBuilder,
46 verifier_srs: Option<Arc<VerifierSRS>>,
47 block_verifier_index: Option<BlockVerifier>,
48 work_verifier_index: Option<TransactionVerifier>,
49 http_port: Option<u16>,
50 daemon_conf: Daemon,
51}
52
53impl NodeBuilder {
54 pub fn new(
55 custom_rng_seed: Option<[u8; 32]>,
56 daemon_conf: Daemon,
57 genesis_config: Arc<GenesisConfig>,
58 ) -> Self {
59 let rng_seed = custom_rng_seed.unwrap_or_else(|| {
60 let mut seed = [0; 32];
61 getrandom::getrandom(&mut seed).unwrap_or_else(|_| {
62 seed = rand::thread_rng().gen();
63 });
64 seed
65 });
66 Self {
67 rng_seed,
68 custom_initial_time: None,
69 genesis_config,
70 p2p: P2pConfig {
71 libp2p_port: None,
72 listen_port: None,
73 identity_pub_key: P2pSecretKey::deterministic(0).public_key(),
75 initial_peers: Vec::new(),
76 external_addrs: Vec::new(),
77 enabled_channels: ChannelId::iter_all().collect(),
78 peer_discovery: true,
79 meshsub: P2pMeshsubConfig {
80 initial_time: Duration::ZERO,
81 ..Default::default()
82 },
83 timeouts: P2pTimeouts::default(),
84 limits: P2pLimits::default().with_max_peers(Some(100)),
85 },
86 p2p_sec_key: None,
87 p2p_is_seed: false,
88 p2p_is_started: false,
89 block_producer: None,
90 archive: None,
91 snarker: None,
92 service: NodeServiceBuilder::new(rng_seed),
93 verifier_srs: None,
94 block_verifier_index: None,
95 work_verifier_index: None,
96 http_port: None,
97 daemon_conf,
98 }
99 }
100
101 pub fn custom_initial_time(&mut self, time: redux::Timestamp) -> &mut Self {
103 self.custom_initial_time = Some(time);
104 self
105 }
106
107 pub fn p2p_sec_key(&mut self, key: P2pSecretKey) -> &mut Self {
109 self.p2p.identity_pub_key = key.public_key();
110 self.p2p_sec_key = Some(key);
111 self
112 }
113
114 pub fn p2p_libp2p_port(&mut self, port: u16) -> &mut Self {
115 self.p2p.libp2p_port = Some(port);
116 self
117 }
118
119 pub fn p2p_seed_node(&mut self) -> &mut Self {
121 self.p2p_is_seed = true;
122 self
123 }
124
125 pub fn p2p_no_discovery(&mut self) -> &mut Self {
126 self.p2p.peer_discovery = false;
127 self
128 }
129
130 pub fn initial_peers(
132 &mut self,
133 peers: impl IntoIterator<Item = P2pConnectionOutgoingInitOpts>,
134 ) -> &mut Self {
135 self.p2p.initial_peers.extend(peers);
136 self
137 }
138
139 pub fn external_addrs(&mut self, v: impl Iterator<Item = IpAddr>) -> &mut Self {
140 self.p2p.external_addrs.extend(v);
141 self
142 }
143
144 pub fn initial_peers_from_file(&mut self, path: impl AsRef<Path>) -> anyhow::Result<&mut Self> {
146 peers_from_reader(
147 &mut self.p2p.initial_peers,
148 File::open(&path).context(anyhow::anyhow!(
149 "opening peer list file {:?}",
150 path.as_ref()
151 ))?,
152 )
153 .context(anyhow::anyhow!(
154 "reading peer list file {:?}",
155 path.as_ref()
156 ))?;
157
158 Ok(self)
159 }
160
161 pub fn initial_peers_from_url(
163 &mut self,
164 url: impl reqwest::IntoUrl,
165 ) -> anyhow::Result<&mut Self> {
166 let url = url.into_url().context("failed to parse peers url")?;
167 peers_from_reader(
168 &mut self.p2p.initial_peers,
169 reqwest::blocking::get(url.clone())
170 .context(anyhow::anyhow!("reading peer list url {url}"))?,
171 )
172 .context(anyhow::anyhow!("reading peer list url {url}"))?;
173 Ok(self)
174 }
175
176 pub fn p2p_max_peers(&mut self, limit: usize) -> &mut Self {
177 self.p2p.limits = self.p2p.limits.with_max_peers(Some(limit));
178 self
179 }
180
181 pub fn p2p_custom_task_spawner(
183 &mut self,
184 spawner: impl TaskSpawner,
185 ) -> anyhow::Result<&mut Self> {
186 let sec_key: P2pSecretKey = self.p2p_sec_key.clone().ok_or_else(|| anyhow::anyhow!("before calling `with_p2p_custom_task_spawner` method, p2p secret key needs to be set with `with_p2p_sec_key`."))?;
187 self.service
188 .p2p_init_with_custom_task_spawner(sec_key, spawner);
189 self.p2p_is_started = true;
190 Ok(self)
191 }
192
193 pub fn block_producer(
195 &mut self,
196 key: AccountSecretKey,
197 provers: Option<BlockProver>,
198 ) -> &mut Self {
199 let config = BlockProducerConfig {
200 pub_key: key.public_key().into(),
201 custom_coinbase_receiver: None,
202 proposed_protocol_version: None,
203 };
204 self.block_producer = Some(config);
205 self.service.block_producer_init(key, provers);
206 self
207 }
208
209 pub fn block_producer_from_file(
211 &mut self,
212 path: impl AsRef<Path>,
213 password: &str,
214 provers: Option<BlockProver>,
215 ) -> anyhow::Result<&mut Self> {
216 let key = AccountSecretKey::from_encrypted_file(path, password)
217 .context("Failed to decrypt secret key file")?;
218 Ok(self.block_producer(key, provers))
219 }
220
221 pub fn archive(&mut self, options: ArchiveStorageOptions, work_dir: String) -> &mut Self {
222 self.archive = Some(ArchiveConfig::new(work_dir.clone()));
223 self.service.archive_init(options, work_dir.clone());
224 self
225 }
226
227 pub fn custom_coinbase_receiver(
229 &mut self,
230 addr: NonZeroCurvePoint,
231 ) -> anyhow::Result<&mut Self> {
232 let bp = self.block_producer.as_mut().ok_or_else(|| {
233 anyhow::anyhow!(
234 "can't set custom_coinbase_receiver when block producer is not initialized."
235 )
236 })?;
237 bp.custom_coinbase_receiver = Some(addr);
238 Ok(self)
239 }
240
241 pub fn custom_block_producer_config(
242 &mut self,
243 config: BlockProducerConfig,
244 ) -> anyhow::Result<&mut Self> {
245 *self.block_producer.as_mut().ok_or_else(|| {
246 anyhow::anyhow!("block producer not initialized! Call `block_producer` function first.")
247 })? = config;
248 Ok(self)
249 }
250
251 pub fn snarker(
252 &mut self,
253 sec_key: AccountSecretKey,
254 fee: u64,
255 strategy: SnarkerStrategy,
256 ) -> &mut Self {
257 let config = SnarkerConfig {
258 public_key: sec_key.public_key(),
259 fee: v2::CurrencyFeeStableV1(v2::UnsignedExtendedUInt64Int64ForVersionTagsStableV1(
260 fee.into(),
261 )),
262 strategy,
263 auto_commit: true,
264 };
265 self.snarker = Some(config);
266 self
267 }
268
269 pub fn verifier_srs(&mut self, srs: Arc<VerifierSRS>) -> &mut Self {
271 self.verifier_srs = Some(srs);
272 self
273 }
274
275 pub fn block_verifier_index(&mut self, index: BlockVerifier) -> &mut Self {
276 self.block_verifier_index = Some(index);
277 self
278 }
279
280 pub fn work_verifier_index(&mut self, index: TransactionVerifier) -> &mut Self {
281 self.work_verifier_index = Some(index);
282 self
283 }
284
285 pub fn gather_stats(&mut self) -> &mut Self {
286 self.service.gather_stats();
287 self
288 }
289
290 pub fn record(&mut self, recorder: Recorder) -> &mut Self {
291 self.service.record(recorder);
292 self
293 }
294
295 pub fn http_server(&mut self, port: u16) -> &mut Self {
296 self.http_port = Some(port);
297 self.service.http_server_init(port);
298 self
299 }
300
301 pub fn build(mut self) -> anyhow::Result<Node> {
302 let p2p_sec_key = self.p2p_sec_key.clone().unwrap_or_else(P2pSecretKey::rand);
303 self.p2p_sec_key(p2p_sec_key.clone());
304 if self.p2p.initial_peers.is_empty() && !self.p2p_is_seed {
305 self.p2p.initial_peers = default_peers();
306 }
307
308 self.p2p.initial_peers = self
309 .p2p
310 .initial_peers
311 .into_iter()
312 .filter(|opts| *opts.peer_id() != p2p_sec_key.public_key().peer_id())
313 .filter_map(|opts| match opts {
314 P2pConnectionOutgoingInitOpts::LibP2P(mut opts) => {
315 opts.host = opts.host.resolve()?;
316 Some(P2pConnectionOutgoingInitOpts::LibP2P(opts))
317 }
318 x => Some(x),
319 })
320 .collect();
321
322 let srs = self.verifier_srs.unwrap_or_else(get_srs);
323 let block_verifier_index = self
324 .block_verifier_index
325 .unwrap_or_else(BlockVerifier::make);
326 let work_verifier_index = self
327 .work_verifier_index
328 .unwrap_or_else(TransactionVerifier::make);
329
330 let initial_time = self
331 .custom_initial_time
332 .unwrap_or_else(redux::Timestamp::global_now);
333 self.p2p.meshsub.initial_time = initial_time
334 .checked_sub(redux::Timestamp::ZERO)
335 .unwrap_or_default();
336
337 let protocol_constants = self.genesis_config.protocol_constants()?;
338 let consensus_consts =
339 ConsensusConstants::create(constraint_constants(), &protocol_constants);
340
341 let node_config = node::Config {
343 global: GlobalConfig {
344 build: node::BuildEnv::get().into(),
345 snarker: self.snarker,
346 consensus_constants: consensus_consts.clone(),
347 testing_run: false,
348 client_port: self.http_port,
349 },
350 p2p: self.p2p,
351 ledger: LedgerConfig {},
352 snark: SnarkConfig {
353 block_verifier_index,
354 block_verifier_srs: srs.clone(),
355 work_verifier_index,
356 work_verifier_srs: srs,
357 },
358 transition_frontier: TransitionFrontierConfig::new(self.genesis_config),
359 block_producer: self.block_producer,
360 archive: self.archive,
361 tx_pool: ledger::transaction_pool::Config {
362 trust_system: (),
363 pool_max_size: self.daemon_conf.tx_pool_max_size(),
364 slot_tx_end: self.daemon_conf.slot_tx_end(),
365 },
366 };
367
368 let mut service = self.service;
370 service.ledger_init();
371
372 if !self.p2p_is_started {
373 service.p2p_init(p2p_sec_key);
374 }
375
376 let service = service.build()?;
377 let state = node::State::new(node_config, &consensus_consts, initial_time);
378
379 Ok(Node::new(self.rng_seed, state, service, None))
380 }
381}
382
383fn default_peers() -> Vec<P2pConnectionOutgoingInitOpts> {
384 openmina_core::NetworkConfig::global()
385 .default_peers
386 .iter()
387 .map(|s| s.parse().unwrap())
388 .collect()
389}
390
391fn peers_from_reader(
392 peers: &mut Vec<P2pConnectionOutgoingInitOpts>,
393 read: impl Read,
394) -> anyhow::Result<()> {
395 let reader = BufReader::new(read);
396 for line in reader.lines() {
397 let line = line.context("reading line")?;
398 let trimmed = line.trim();
399 if trimmed.is_empty() {
400 continue;
401 }
402 match trimmed.parse::<P2pConnectionOutgoingInitOpts>() {
403 Ok(opts) => {
404 if let Some(opts) = opts.with_host_resolved() {
405 peers.push(opts);
406 } else {
407 openmina_core::warn!(
408 "Peer address name resolution failed, skipping: {:?}",
409 trimmed
410 );
411 }
412 }
413 Err(e) => openmina_core::warn!("Peer address parse error: {:?}", e),
414 }
415 }
416 Ok(())
417}