Skip to content

Commit b100a56

Browse files
authored
Merge pull request #2944 from ProvableHQ/feat/loggable-error
[Feature] LoggableError trait
2 parents 7009257 + 724a091 commit b100a56

12 files changed

Lines changed: 193 additions & 139 deletions

File tree

Cargo.lock

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

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@ version = "0.14"
468468
version = "1.4"
469469

470470
[workspace.dependencies.locktick]
471-
version = "0.3"
471+
version = "0.4"
472472

473473
[workspace.dependencies.lru]
474474
version = "0.16"

ledger/Cargo.toml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,9 @@ optional = true
123123
[dependencies.snarkvm-synthesizer]
124124
workspace = true
125125

126+
[dependencies.snarkvm-utilities]
127+
workspace = true
128+
126129
[dependencies.aleo-std]
127130
workspace = true
128131
features = [ "storage" ]
@@ -191,9 +194,6 @@ features = [ "preserve_order" ]
191194
[dev-dependencies.snarkvm-circuit]
192195
workspace = true
193196

194-
[dev-dependencies.snarkvm-utilities]
195-
workspace = true
196-
197197
[dev-dependencies.snarkvm-synthesizer]
198198
workspace = true
199199
features = [ "test" ]

ledger/src/check_next_block.rs

Lines changed: 30 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ use super::*;
1717

1818
use crate::narwhal::BatchHeader;
1919

20+
use anyhow::{Context, bail};
21+
2022
impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
2123
/// Checks the given block is valid next block.
2224
pub fn check_next_block<R: CryptoRng + Rng>(&self, block: &Block<N>, rng: &mut R) -> Result<()> {
@@ -40,29 +42,6 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
4042
}
4143
}
4244

43-
// TODO (howardwu): Remove this after moving the total supply into credits.aleo.
44-
{
45-
// // Retrieve the latest total supply.
46-
// let latest_total_supply = self.latest_total_supply_in_microcredits();
47-
// // Retrieve the block reward from the first block ratification.
48-
// let block_reward = match block.ratifications()[0] {
49-
// Ratify::BlockReward(block_reward) => block_reward,
50-
// _ => bail!("Block {height} is invalid - the first ratification must be a block reward"),
51-
// };
52-
// // Retrieve the puzzle reward from the second block ratification.
53-
// let puzzle_reward = match block.ratifications()[1] {
54-
// Ratify::PuzzleReward(puzzle_reward) => puzzle_reward,
55-
// _ => bail!("Block {height} is invalid - the second ratification must be a puzzle reward"),
56-
// };
57-
// // Compute the next total supply in microcredits.
58-
// let next_total_supply_in_microcredits =
59-
// update_total_supply(latest_total_supply, block_reward, puzzle_reward, block.transactions())?;
60-
// // Ensure the total supply in microcredits is correct.
61-
// if next_total_supply_in_microcredits != block.total_supply_in_microcredits() {
62-
// bail!("Invalid total supply in microcredits")
63-
// }
64-
}
65-
6645
// Construct the finalize state.
6746
let state = FinalizeGlobalState::new::<N>(
6847
block.round(),
@@ -74,14 +53,17 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
7453

7554
// Ensure speculation over the unconfirmed transactions is correct and ensure each transaction is well-formed and unique.
7655
let time_since_last_block = block.timestamp().saturating_sub(self.latest_timestamp());
77-
let ratified_finalize_operations = self.vm.check_speculate(
78-
state,
79-
time_since_last_block,
80-
block.ratifications(),
81-
block.solutions(),
82-
block.transactions(),
83-
rng,
84-
)?;
56+
let ratified_finalize_operations = self
57+
.vm
58+
.check_speculate(
59+
state,
60+
time_since_last_block,
61+
block.ratifications(),
62+
block.solutions(),
63+
block.transactions(),
64+
rng,
65+
)
66+
.with_context(|| "Failed to speculate over unconfirmed transactions")?;
8567

8668
// Retrieve the committee lookback.
8769
let committee_lookback = self
@@ -98,16 +80,18 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
9880
};
9981

10082
// Ensure the block is correct.
101-
let (expected_existing_solution_ids, expected_existing_transaction_ids) = block.verify(
102-
&latest_block,
103-
self.latest_state_root(),
104-
&previous_committee_lookback,
105-
&committee_lookback,
106-
self.puzzle(),
107-
self.latest_epoch_hash()?,
108-
OffsetDateTime::now_utc().unix_timestamp(),
109-
ratified_finalize_operations,
110-
)?;
83+
let (expected_existing_solution_ids, expected_existing_transaction_ids) = block
84+
.verify(
85+
&latest_block,
86+
self.latest_state_root(),
87+
&previous_committee_lookback,
88+
&committee_lookback,
89+
self.puzzle(),
90+
self.latest_epoch_hash()?,
91+
OffsetDateTime::now_utc().unix_timestamp(),
92+
ratified_finalize_operations,
93+
)
94+
.with_context(|| "Failed to verify block")?;
11195

11296
// Ensure that the provers are within their stake bounds.
11397
if let Some(solutions) = block.solutions().deref() {
@@ -130,7 +114,7 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
130114
// Determine if the block subdag is correctly constructed and is not a combination of multiple subdags.
131115
self.check_block_subdag_atomicity(block)?;
132116

133-
// Ensure that all leafs of the subdag point to valid batches in other subdags/blocks.
117+
// Ensure that all leaves of the subdag point to valid batches in other subdags/blocks.
134118
self.check_block_subdag_leaves(block)?;
135119

136120
// Ensure that each existing solution ID from the block exists in the ledger.
@@ -204,8 +188,9 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
204188
cfg_iter!(subdag).try_for_each(|(round, certificates)| {
205189
// Retrieve the committee lookback for the round.
206190
let committee_lookback = self
207-
.get_committee_lookback_for_round(*round)?
208-
.ok_or_else(|| anyhow!("No committee lookback found for round {round}"))?;
191+
.get_committee_lookback_for_round(*round)
192+
.with_context(|| format!("Failed to get committee lookback for round {round}"))?
193+
.ok_or_else(|| anyhow!("No committee lookback for round {round}"))?;
209194

210195
// Check that each certificate for this round has met quorum requirements.
211196
// Note that we do not need to check the quorum requirement for the previous certificates
@@ -273,7 +258,7 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
273258
// Compute the leader for the commit round.
274259
let computed_leader = previous_committee_lookback
275260
.get_leader(round)
276-
.map_err(|e| anyhow!("Failed to compute leader for round {round}: {e}"))?;
261+
.with_context(|| format!("Failed to compute leader for round {round}"))?;
277262

278263
// Retrieve the previous leader certificates.
279264
let previous_certificate = match subdag.get(&round).and_then(|certificates| {

ledger/src/find.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515

1616
use super::*;
1717

18+
use snarkvm_utilities::LoggableError;
19+
1820
impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
1921
/// Returns the block height that contains the given `state root`.
2022
pub fn find_block_height_from_state_root(&self, state_root: N::StateRoot) -> Result<Option<u32>> {
@@ -128,8 +130,8 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
128130
match commitment {
129131
Ok(Some(commitment)) => Some((commitment, record)),
130132
Ok(None) => None,
131-
Err(e) => {
132-
warn!("Failed to process 'find_record_ciphertexts({:?})': {e}", filter);
133+
Err(err) => {
134+
err.log_warning(format!("Failed to process 'find_record_ciphertexts({filter:?})'"));
133135
None
134136
}
135137
}
@@ -146,8 +148,8 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
146148
self.find_record_ciphertexts(view_key, filter).map(|iter| {
147149
iter.flat_map(|(commitment, record)| match record.decrypt(view_key) {
148150
Ok(record) => Some((commitment, record)),
149-
Err(e) => {
150-
warn!("Failed to decrypt the record: {e}");
151+
Err(err) => {
152+
err.log_warning("Failed to decrypt record");
151153
None
152154
}
153155
})

ledger/store/Cargo.toml

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ edition = "2024"
1919
[features]
2020
default = [ "indexmap/rayon" ]
2121
locktick = [ "dep:locktick", "snarkvm-ledger-puzzle/locktick" ]
22-
rocks = [ "rocksdb", "smallvec", "tracing" ]
22+
rocks = [ "rocksdb", "smallvec" ]
2323
serial = [
2424
"snarkvm-console/serial",
2525
"snarkvm-ledger-block/serial",
@@ -109,10 +109,6 @@ workspace = true
109109
features = [ "write" ]
110110
optional = true
111111

112-
[dependencies.tracing]
113-
workspace = true
114-
optional = true
115-
116112
[dev-dependencies.aleo-std]
117113
workspace = true
118114

@@ -131,3 +127,6 @@ workspace = true
131127

132128
[dev-dependencies.tracing-test]
133129
version = "0.2.5"
130+
131+
[dev-dependencies.tracing]
132+
workspace = true

ledger/store/src/helpers/memory/internal/map.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,10 @@ impl<
137137
// Set the atomic batch flag to `true`.
138138
self.batch_in_progress.store(true, Ordering::SeqCst);
139139
// Ensure that the atomic batch is empty.
140-
assert!(self.atomic_batch.lock().is_empty());
140+
assert!(
141+
self.atomic_batch.lock().is_empty(),
142+
"Cannot start an atomic batch operation while another one is already in progress"
143+
);
141144
}
142145

143146
///

ledger/store/src/helpers/memory/internal/nested_map.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,17 @@
1717

1818
use crate::helpers::{NestedMap, NestedMapRead};
1919
use console::network::prelude::*;
20-
2120
use snarkvm_utilities::bytes::unchecked_deserialize;
2221

23-
use core::hash::Hash;
22+
use anyhow::Context;
2423
#[cfg(feature = "locktick")]
2524
use locktick::parking_lot::{Mutex, RwLock};
2625
#[cfg(not(feature = "locktick"))]
2726
use parking_lot::{Mutex, RwLock};
2827
use std::{
2928
borrow::Cow,
3029
collections::{BTreeMap, BTreeSet, btree_map},
30+
hash::Hash,
3131
sync::{
3232
Arc,
3333
atomic::{AtomicBool, Ordering},
@@ -152,7 +152,10 @@ impl<
152152
// Set the atomic batch flag to `true`.
153153
self.batch_in_progress.store(true, Ordering::SeqCst);
154154
// Ensure that the atomic batch is empty.
155-
assert!(self.atomic_batch.lock().is_empty());
155+
assert!(
156+
self.atomic_batch.lock().is_empty(),
157+
"Cannot start an atomic operation while another one is already in progress"
158+
);
156159
}
157160

158161
///
@@ -284,9 +287,9 @@ impl<
284287
///
285288
fn contains_key_confirmed(&self, map: &M, key: &K) -> Result<bool> {
286289
// Serialize 'm'.
287-
let m = bincode::serialize(map)?;
290+
let m = bincode::serialize(map).with_context(|| "Failed to serialize map")?;
288291
// Concatenate 'm' and 'k' with a 0-byte separator.
289-
let mk = to_map_key(&m, &bincode::serialize(key)?);
292+
let mk = to_map_key(&m, &bincode::serialize(key).with_context(|| "Failed to serialize map key")?);
290293
// Return whether the concatenated key exists in the map.
291294
Ok(self.map_inner.read().contains_key(&mk))
292295
}

0 commit comments

Comments
 (0)