Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Perf] Skip costly validation for stored data #2574

Draft
wants to merge 3 commits into
base: staging
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions console/account/src/compute_key/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ impl<N: Network> FromBytes for ComputeKey<N> {
}
}

impl<N: Network> FromBytesUnchecked for ComputeKey<N> {
/// Reads an account compute key from a buffer.
#[inline]
fn read_le_unchecked<R: Read>(mut reader: R) -> IoResult<Self> {
let pk_sig = Group::from_x_coordinate_unchecked(Field::new(N::Field::read_le(&mut reader)?))
.map_err(|e| error(format!("{e}")))?;
let pr_sig = Group::from_x_coordinate_unchecked(Field::new(N::Field::read_le(&mut reader)?))
.map_err(|e| error(format!("{e}")))?;
Self::try_from((pk_sig, pr_sig)).map_err(|e| error(format!("{e}")))
}
}

impl<N: Network> ToBytes for ComputeKey<N> {
/// Writes an account compute key to a buffer.
fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
Expand Down Expand Up @@ -56,7 +68,9 @@ mod tests {
// Check the byte representation.
let expected_bytes = expected.to_bytes_le()?;
assert_eq!(expected, ComputeKey::read_le(&expected_bytes[..])?);
assert_eq!(expected, ComputeKey::read_le_unchecked(&expected_bytes[..])?);
assert!(ComputeKey::<CurrentNetwork>::read_le(&expected_bytes[1..]).is_err());
assert!(ComputeKey::<CurrentNetwork>::read_le_unchecked(&expected_bytes[1..]).is_err());
}
Ok(())
}
Expand Down
13 changes: 13 additions & 0 deletions console/account/src/signature/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@ impl<N: Network> FromBytes for Signature<N> {
}
}

impl<N: Network> FromBytesUnchecked for Signature<N> {
/// Reads an account signature from a buffer.
#[inline]
fn read_le_unchecked<R: Read>(mut reader: R) -> IoResult<Self> {
let challenge = Scalar::new(FromBytes::read_le(&mut reader)?);
let response = Scalar::new(FromBytes::read_le(&mut reader)?);
let compute_key = ComputeKey::read_le_unchecked(&mut reader)?;
Ok(Self { challenge, response, compute_key })
}
}

impl<N: Network> ToBytes for Signature<N> {
/// Writes an account signature to a buffer.
#[inline]
Expand Down Expand Up @@ -56,7 +67,9 @@ mod tests {
// Check the byte representation.
let signature_bytes = signature.to_bytes_le()?;
assert_eq!(signature, Signature::read_le(&signature_bytes[..])?);
assert_eq!(signature, Signature::read_le_unchecked(&signature_bytes[..])?);
assert!(Signature::<CurrentNetwork>::read_le(&signature_bytes[1..]).is_err());
assert!(Signature::<CurrentNetwork>::read_le_unchecked(&signature_bytes[1..]).is_err());
}
Ok(())
}
Expand Down
2 changes: 2 additions & 0 deletions console/network/environment/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ pub mod prelude {
FromBits as _,
FromBytes,
FromBytesDeserializer,
FromBytesUnchecked,
FromBytesUncheckedDeserializer,
LimitedWriter,
TestRng,
ToBits as _,
Expand Down
10 changes: 10 additions & 0 deletions console/types/address/src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ impl<E: Environment> FromBytes for Address<E> {
}
}

impl<E: Environment> FromBytesUnchecked for Address<E> {
/// Reads in an account address from a buffer.
#[inline]
fn read_le_unchecked<R: Read>(mut reader: R) -> IoResult<Self> {
Ok(Address::new(FromBytesUnchecked::read_le_unchecked(&mut reader)?))
}
}

impl<E: Environment> ToBytes for Address<E> {
/// Writes an account address to a buffer.
fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
Expand Down Expand Up @@ -50,7 +58,9 @@ mod tests {
// Check the byte representation.
let expected_bytes = expected.to_bytes_le()?;
assert_eq!(expected, Address::read_le(&expected_bytes[..])?);
assert_eq!(expected, Address::read_le_unchecked(&expected_bytes[..])?);
assert!(Address::<CurrentEnvironment>::read_le(&expected_bytes[1..]).is_err());
assert!(Address::<CurrentEnvironment>::read_le_unchecked(&expected_bytes[1..]).is_err());
}
Ok(())
}
Expand Down
10 changes: 10 additions & 0 deletions console/types/group/src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ impl<E: Environment> FromBytes for Group<E> {
}
}

impl<E: Environment> FromBytesUnchecked for Group<E> {
/// Reads the group from a buffer.
#[inline]
fn read_le_unchecked<R: Read>(mut reader: R) -> IoResult<Self> {
Self::from_x_coordinate_unchecked(FromBytes::read_le(&mut reader)?).map_err(|e| error(e.to_string()))
}
}

impl<E: Environment> ToBytes for Group<E> {
/// Writes the group to a buffer.
#[inline]
Expand Down Expand Up @@ -51,7 +59,9 @@ mod tests {
// Check the byte representation.
let expected_bytes = expected.to_bytes_le()?;
assert_eq!(expected, Group::read_le(&expected_bytes[..])?);
assert_eq!(expected, Group::read_le_unchecked(&expected_bytes[..])?);
assert!(Group::<CurrentEnvironment>::read_le(&expected_bytes[1..]).is_err());
assert!(Group::<CurrentEnvironment>::read_le_unchecked(&expected_bytes[1..]).is_err());
}
Ok(())
}
Expand Down
8 changes: 8 additions & 0 deletions console/types/group/src/from_x_coordinate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,12 @@ impl<E: Environment> Group<E> {
}
bail!("Failed to recover an affine group from an x-coordinate of {x_coordinate}")
}

/// Attempts to recover an affine group element from a given x-coordinate field element.
pub fn from_x_coordinate_unchecked(x_coordinate: Field<E>) -> Result<Self> {
if let Some((p1, _p2)) = E::Affine::pair_from_x_coordinate(*x_coordinate) {
return Ok(Self::new(p1));
}
bail!("Failed to recover an affine group from an x-coordinate of {x_coordinate}")
}
}
6 changes: 6 additions & 0 deletions ledger/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ name = "bonded_mapping"
path = "benches/bonded_mapping.rs"
harness = false

[[bench]]
name = "dag"
path = "benches/dag.rs"
harness = false
required-features = ["test-helpers"]

[[bench]]
name = "transaction"
path = "benches/transaction.rs"
Expand Down
15 changes: 15 additions & 0 deletions ledger/authority/src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,20 @@ impl<N: Network> FromBytes for Authority<N> {
}
}

impl<N: Network> FromBytesUnchecked for Authority<N> {
/// Reads the authority from the buffer.
fn read_le_unchecked<R: Read>(mut reader: R) -> IoResult<Self> {
// Read the variant.
let variant = u8::read_le(&mut reader)?;
// Match the variant.
match variant {
0 => Ok(Self::Beacon(FromBytes::read_le(&mut reader)?)),
1 => Ok(Self::Quorum(FromBytesUnchecked::read_le_unchecked(&mut reader)?)),
2.. => Err(error("Invalid authority variant")),
}
}
}

impl<N: Network> ToBytes for Authority<N> {
/// Writes the authority to the buffer.
fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
Expand Down Expand Up @@ -63,6 +77,7 @@ mod tests {
// Check the byte representation.
let expected_bytes = expected.to_bytes_le().unwrap();
assert_eq!(expected, Authority::read_le(&expected_bytes[..]).unwrap());
assert_eq!(expected, Authority::read_le_unchecked(&expected_bytes[..]).unwrap());
}
}
}
1 change: 1 addition & 0 deletions ledger/authority/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use console::{
Formatter,
FromBytes,
FromBytesDeserializer,
FromBytesUnchecked,
FromStr,
IoResult,
Read,
Expand Down
98 changes: 98 additions & 0 deletions ledger/benches/dag.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Copyright 2024 Aleo Network Foundation
// This file is part of the snarkVM library.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[macro_use]
extern crate criterion;

use console::{network::MainnetV0, prelude::*};
use snarkvm_ledger::narwhal::subdag::test_helpers::sample_subdag;

use criterion::Criterion;

/// Helper method to benchmark serialization.
fn bench_serialization<T: Serialize + DeserializeOwned + ToBytes + FromBytes + FromBytesUnchecked + Clone>(
c: &mut Criterion,
name: &str,
object: T,
) {
///////////////
// Serialize //
///////////////

// snarkvm_utilities::ToBytes
{
let object = object.clone();
c.bench_function(&format!("{name}::to_bytes_le"), move |b| b.iter(|| object.to_bytes_le().unwrap()));
}
// bincode::serialize
{
let object = object.clone();
c.bench_function(&format!("{name}::serialize (bincode)"), move |b| {
b.iter(|| bincode::serialize(&object).unwrap())
});
}
// serde_json::to_string
{
let object = object.clone();
c.bench_function(&format!("{name}::to_string (serde_json)"), move |b| {
b.iter(|| serde_json::to_string(&object).unwrap())
});
}

/////////////////
// Deserialize //
/////////////////

// snarkvm_utilities::FromBytes
{
let buffer = object.to_bytes_le().unwrap();
c.bench_function(&format!("{name}::from_bytes_le"), move |b| b.iter(|| T::from_bytes_le(&buffer).unwrap()));
}
// snarkvm_utilities::FromBytesUnchecked
{
let buffer = object.to_bytes_le().unwrap();
c.bench_function(&format!("{name}::from_bytes_le_unchecked"), move |b| {
b.iter(|| T::from_bytes_le_unchecked(&buffer).unwrap())
});
}
// bincode::deserialize
{
let buffer = bincode::serialize(&object).unwrap();
c.bench_function(&format!("{name}::deserialize (bincode)"), move |b| {
b.iter(|| bincode::deserialize::<T>(&buffer).unwrap())
});
}
// serde_json::from_str
{
let object = serde_json::to_string(&object).unwrap();
c.bench_function(&format!("{name}::from_str (serde_json)"), move |b| {
b.iter(|| serde_json::from_str::<T>(&object).unwrap())
});
}
}

fn subdag_serialization(c: &mut Criterion) {
let rng = &mut TestRng::default();
let subdag = sample_subdag(rng);
bench_serialization(c, "Subdag", subdag);
}

criterion_group! {
name = subdag;
config = Criterion::default().sample_size(10);
targets = subdag_serialization
}

criterion_main!(subdag);
72 changes: 72 additions & 0 deletions ledger/block/src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,76 @@ impl<N: Network> FromBytes for Block<N> {
}
}

impl<N: Network> FromBytesUnchecked for Block<N> {
/// Reads the block from the buffer without performing expensive input validation.
#[inline]
fn read_le_unchecked<R: Read>(mut reader: R) -> IoResult<Self> {
// Read the version.
let version = u8::read_le(&mut reader)?;
// Ensure the version is valid.
if version != 1 {
return Err(error("Invalid block version"));
}

// Read the block hash.
let block_hash: N::BlockHash = FromBytes::read_le(&mut reader)?;
// Read the previous block hash.
let previous_hash = FromBytes::read_le(&mut reader)?;
// Read the header.
let header = FromBytes::read_le(&mut reader)?;

// Write the authority.
let authority = FromBytesUnchecked::read_le_unchecked(&mut reader)?;

// Read the number of ratifications.
let ratifications = Ratifications::read_le(&mut reader)?;

// Read the solutions.
let solutions: Solutions<N> = FromBytes::read_le(&mut reader)?;

// Read the number of aborted solution IDs.
let num_aborted_solutions = u32::read_le(&mut reader)?;
// Ensure the number of aborted solutions IDs is within bounds (this is an early safety check).
if num_aborted_solutions as usize > Solutions::<N>::MAX_ABORTED_SOLUTIONS {
return Err(error("Invalid number of aborted solutions IDs in the block"));
}
// Read the aborted solution IDs.
let mut aborted_solution_ids = Vec::with_capacity(num_aborted_solutions as usize);
for _ in 0..num_aborted_solutions {
aborted_solution_ids.push(FromBytes::read_le(&mut reader)?);
}

// Read the transactions.
let transactions = FromBytes::read_le(&mut reader)?;

// Read the number of aborted transaction IDs.
let num_aborted_transactions = u32::read_le(&mut reader)?;
// Ensure the number of aborted transaction IDs is within bounds (this is an early safety check).
if num_aborted_transactions as usize > Transactions::<N>::MAX_ABORTED_TRANSACTIONS {
return Err(error("Invalid number of aborted transaction IDs in the block"));
}
// Read the aborted transaction IDs.
let mut aborted_transaction_ids = Vec::with_capacity(num_aborted_transactions as usize);
for _ in 0..num_aborted_transactions {
aborted_transaction_ids.push(FromBytes::read_le(&mut reader)?);
}

// Construct the block.
Self::from_unchecked(
block_hash,
previous_hash,
header,
authority,
ratifications,
solutions,
aborted_solution_ids,
transactions,
aborted_transaction_ids,
)
.map_err(error)
}
}

impl<N: Network> ToBytes for Block<N> {
/// Writes the block to the buffer.
#[inline]
Expand Down Expand Up @@ -141,6 +211,7 @@ mod tests {
// Check the byte representation.
let expected_bytes = expected.to_bytes_le()?;
assert_eq!(expected, Block::read_le(&expected_bytes[..])?);
assert_eq!(expected, Block::read_le_unchecked(&expected_bytes[..])?);
}
Ok(())
}
Expand All @@ -153,6 +224,7 @@ mod tests {
// Check the byte representation.
let expected_bytes = genesis_block.to_bytes_le()?;
assert_eq!(genesis_block, Block::read_le(&expected_bytes[..])?);
assert_eq!(genesis_block, Block::read_le_unchecked(&expected_bytes[..])?);

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion ledger/block/src/serialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ impl<'de, N: Network> Deserialize<'de> for Block<N> {
false => Err(de::Error::custom(error("Mismatching block hash, possible data corruption"))),
}
}
false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "block"),
false => FromBytesUncheckedDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "block"),
}
}
}
Expand Down
Loading