snarkos_node/prover/
mod.rs

1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkOS library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16mod router;
17
18use crate::traits::NodeInterface;
19use snarkos_account::Account;
20use snarkos_node_bft::ledger_service::ProverLedgerService;
21use snarkos_node_router::{
22    Heartbeat,
23    Inbound,
24    Outbound,
25    Router,
26    Routing,
27    messages::{Message, NodeType, UnconfirmedSolution},
28};
29use snarkos_node_sync::{BlockSync, BlockSyncMode};
30use snarkos_node_tcp::{
31    P2P,
32    protocols::{Disconnect, Handshake, OnConnect, Reading, Writing},
33};
34use snarkvm::{
35    ledger::narwhal::Data,
36    prelude::{
37        Network,
38        block::{Block, Header},
39        puzzle::{Puzzle, Solution},
40        store::ConsensusStorage,
41    },
42    synthesizer::VM,
43};
44
45use aleo_std::StorageMode;
46use anyhow::Result;
47use colored::Colorize;
48use core::{marker::PhantomData, time::Duration};
49use parking_lot::{Mutex, RwLock};
50use rand::{CryptoRng, Rng, rngs::OsRng};
51use snarkos_node_bft::helpers::fmt_id;
52use std::{
53    net::SocketAddr,
54    sync::{
55        Arc,
56        atomic::{AtomicBool, AtomicU8, Ordering},
57    },
58};
59use tokio::task::JoinHandle;
60
61/// A prover is a light node, capable of producing proofs for consensus.
62#[derive(Clone)]
63pub struct Prover<N: Network, C: ConsensusStorage<N>> {
64    /// The router of the node.
65    router: Router<N>,
66    /// The sync module.
67    sync: Arc<BlockSync<N>>,
68    /// The genesis block.
69    genesis: Block<N>,
70    /// The puzzle.
71    puzzle: Puzzle<N>,
72    /// The latest epoch hash.
73    latest_epoch_hash: Arc<RwLock<Option<N::BlockHash>>>,
74    /// The latest block header.
75    latest_block_header: Arc<RwLock<Option<Header<N>>>>,
76    /// The number of puzzle instances.
77    puzzle_instances: Arc<AtomicU8>,
78    /// The maximum number of puzzle instances.
79    max_puzzle_instances: u8,
80    /// The spawned handles.
81    handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
82    /// The shutdown signal.
83    shutdown: Arc<AtomicBool>,
84    /// PhantomData.
85    _phantom: PhantomData<C>,
86}
87
88impl<N: Network, C: ConsensusStorage<N>> Prover<N, C> {
89    /// Initializes a new prover node.
90    pub async fn new(
91        node_ip: SocketAddr,
92        account: Account<N>,
93        trusted_peers: &[SocketAddr],
94        genesis: Block<N>,
95        storage_mode: StorageMode,
96        shutdown: Arc<AtomicBool>,
97    ) -> Result<Self> {
98        // Initialize the signal handler.
99        let signal_node = Self::handle_signals(shutdown.clone());
100
101        // Initialize the ledger service.
102        let ledger_service = Arc::new(ProverLedgerService::new());
103        // Determine if the prover should allow external peers.
104        let allow_external_peers = true;
105        // Determine if the prover should rotate external peers.
106        let rotate_external_peers = false;
107
108        // Initialize the node router.
109        let router = Router::new(
110            node_ip,
111            NodeType::Prover,
112            account,
113            trusted_peers,
114            Self::MAXIMUM_NUMBER_OF_PEERS as u16,
115            rotate_external_peers,
116            allow_external_peers,
117            matches!(storage_mode, StorageMode::Development(_)),
118        )
119        .await?;
120
121        // Initialize the sync module.
122        let sync = BlockSync::new(BlockSyncMode::Router, ledger_service.clone(), router.tcp().clone());
123
124        // Compute the maximum number of puzzle instances.
125        let max_puzzle_instances = num_cpus::get().saturating_sub(2).clamp(1, 6);
126        // Initialize the node.
127        let node = Self {
128            router,
129            sync: Arc::new(sync),
130            genesis,
131            puzzle: VM::<N, C>::new_puzzle()?,
132            latest_epoch_hash: Default::default(),
133            latest_block_header: Default::default(),
134            puzzle_instances: Default::default(),
135            max_puzzle_instances: u8::try_from(max_puzzle_instances)?,
136            handles: Default::default(),
137            shutdown,
138            _phantom: Default::default(),
139        };
140        // Initialize the routing.
141        node.initialize_routing().await;
142        // Initialize the puzzle.
143        node.initialize_puzzle().await;
144        // Initialize the notification message loop.
145        node.handles.lock().push(crate::start_notification_message_loop());
146        // Pass the node to the signal handler.
147        let _ = signal_node.set(node.clone());
148        // Return the node.
149        Ok(node)
150    }
151}
152
153#[async_trait]
154impl<N: Network, C: ConsensusStorage<N>> NodeInterface<N> for Prover<N, C> {
155    /// Shuts down the node.
156    async fn shut_down(&self) {
157        info!("Shutting down...");
158
159        // Shut down the puzzle.
160        debug!("Shutting down the puzzle...");
161        self.shutdown.store(true, Ordering::Release);
162
163        // Abort the tasks.
164        debug!("Shutting down the prover...");
165        self.handles.lock().iter().for_each(|handle| handle.abort());
166
167        // Shut down the router.
168        self.router.shut_down().await;
169
170        info!("Node has shut down.");
171    }
172}
173
174impl<N: Network, C: ConsensusStorage<N>> Prover<N, C> {
175    /// Initialize a new instance of the puzzle.
176    async fn initialize_puzzle(&self) {
177        for _ in 0..self.max_puzzle_instances {
178            let prover = self.clone();
179            self.handles.lock().push(tokio::spawn(async move {
180                prover.puzzle_loop().await;
181            }));
182        }
183    }
184
185    /// Executes an instance of the puzzle.
186    async fn puzzle_loop(&self) {
187        loop {
188            // If the node is not connected to any peers, then skip this iteration.
189            if self.router.number_of_connected_peers() == 0 {
190                debug!("Skipping an iteration of the puzzle (no connected peers)");
191                tokio::time::sleep(Duration::from_secs(N::ANCHOR_TIME as u64)).await;
192                continue;
193            }
194
195            // If the number of instances of the puzzle exceeds the maximum, then skip this iteration.
196            if self.num_puzzle_instances() > self.max_puzzle_instances {
197                // Sleep for a brief period of time.
198                tokio::time::sleep(Duration::from_millis(500)).await;
199                continue;
200            }
201
202            // Read the latest epoch hash.
203            let latest_epoch_hash = *self.latest_epoch_hash.read();
204            // Read the latest state.
205            let latest_state = self
206                .latest_block_header
207                .read()
208                .as_ref()
209                .map(|header| (header.coinbase_target(), header.proof_target()));
210
211            // If the latest epoch hash and latest state exists, then proceed to generate a solution.
212            if let (Some(epoch_hash), Some((coinbase_target, proof_target))) = (latest_epoch_hash, latest_state) {
213                // Execute the puzzle.
214                let prover = self.clone();
215                let result = tokio::task::spawn_blocking(move || {
216                    prover.puzzle_iteration(epoch_hash, coinbase_target, proof_target, &mut OsRng)
217                })
218                .await;
219
220                // If the prover found a solution, then broadcast it.
221                if let Ok(Some((solution_target, solution))) = result {
222                    info!("Found a Solution '{}' (Proof Target {solution_target})", solution.id());
223                    // Broadcast the solution.
224                    self.broadcast_solution(solution);
225                }
226            } else {
227                // Otherwise, sleep for a brief period of time, to await for puzzle state.
228                tokio::time::sleep(Duration::from_secs(1)).await;
229            }
230
231            // If the Ctrl-C handler registered the signal, stop the prover.
232            if self.shutdown.load(Ordering::Acquire) {
233                debug!("Shutting down the puzzle...");
234                break;
235            }
236        }
237    }
238
239    /// Performs one iteration of the puzzle.
240    fn puzzle_iteration<R: Rng + CryptoRng>(
241        &self,
242        epoch_hash: N::BlockHash,
243        coinbase_target: u64,
244        proof_target: u64,
245        rng: &mut R,
246    ) -> Option<(u64, Solution<N>)> {
247        // Increment the puzzle instances.
248        self.increment_puzzle_instances();
249
250        debug!(
251            "Proving 'Puzzle' for Epoch '{}' {}",
252            fmt_id(epoch_hash),
253            format!("(Coinbase Target {coinbase_target}, Proof Target {proof_target})").dimmed()
254        );
255
256        // Compute the solution.
257        let result =
258            self.puzzle.prove(epoch_hash, self.address(), rng.gen(), Some(proof_target)).ok().and_then(|solution| {
259                self.puzzle.get_proof_target(&solution).ok().map(|solution_target| (solution_target, solution))
260            });
261
262        // Decrement the puzzle instances.
263        self.decrement_puzzle_instances();
264        // Return the result.
265        result
266    }
267
268    /// Broadcasts the solution to the network.
269    fn broadcast_solution(&self, solution: Solution<N>) {
270        // Prepare the unconfirmed solution message.
271        let message = Message::UnconfirmedSolution(UnconfirmedSolution {
272            solution_id: solution.id(),
273            solution: Data::Object(solution),
274        });
275        // Propagate the "UnconfirmedSolution".
276        self.propagate(message, &[]);
277    }
278
279    /// Returns the current number of puzzle instances.
280    fn num_puzzle_instances(&self) -> u8 {
281        self.puzzle_instances.load(Ordering::Relaxed)
282    }
283
284    /// Increments the number of puzzle instances.
285    fn increment_puzzle_instances(&self) {
286        self.puzzle_instances.fetch_add(1, Ordering::Relaxed);
287        #[cfg(debug_assertions)]
288        trace!("Number of Instances - {}", self.num_puzzle_instances());
289    }
290
291    /// Decrements the number of puzzle instances.
292    fn decrement_puzzle_instances(&self) {
293        self.puzzle_instances.fetch_sub(1, Ordering::Relaxed);
294        #[cfg(debug_assertions)]
295        trace!("Number of Instances - {}", self.num_puzzle_instances());
296    }
297}