From 3af0e6a833ba52761588ccec622c48f8aaa247d9 Mon Sep 17 00:00:00 2001 From: Nazar Mokrynskyi Date: Mon, 9 Oct 2023 21:28:54 +0300 Subject: [PATCH] Replace most of blake2 usage with blake3 --- Cargo.lock | 1 - crates/pallet-feeds/src/feed_processor.rs | 4 +- crates/pallet-feeds/src/lib.rs | 6 +- crates/pallet-feeds/src/tests.rs | 4 +- crates/pallet-object-store/src/lib.rs | 12 ++-- crates/pallet-object-store/src/tests.rs | 2 +- crates/pallet-subspace/src/benchmarking.rs | 4 +- crates/pallet-subspace/src/mock.rs | 4 +- .../src/bundle_producer_election.rs | 6 +- crates/sp-domains/src/lib.rs | 8 +-- crates/sp-domains/src/merkle_tree.rs | 6 +- crates/subspace-archiving/src/archiver.rs | 12 ++-- .../src/piece_reconstructor.rs | 4 +- .../tests/integration/archiver.rs | 23 +++--- crates/subspace-core-primitives/Cargo.toml | 2 - crates/subspace-core-primitives/src/crypto.rs | 71 +++++-------------- crates/subspace-core-primitives/src/lib.rs | 55 +++++++------- .../subspace-core-primitives/src/objects.rs | 10 +-- .../benches/auditing.rs | 4 +- .../benches/proving.rs | 4 +- .../src/auditing.rs | 4 +- .../src/single_disk_farm/plotting.rs | 6 +- crates/subspace-networking/src/constructor.rs | 2 +- crates/subspace-proof-of-space/src/shim.rs | 8 +-- crates/subspace-rpc-primitives/src/lib.rs | 4 +- .../tests/integration/object_mapping.rs | 22 +++--- crates/subspace-verification/src/lib.rs | 18 ++--- domains/runtime/evm/src/lib.rs | 4 +- domains/test/runtime/evm/src/lib.rs | 4 +- 29 files changed, 134 insertions(+), 180 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 08328649246..e1e78a1edd8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11491,7 +11491,6 @@ dependencies = [ name = "subspace-core-primitives" version = "0.1.0" dependencies = [ - "blake2", "blake3", "blst_rust", "criterion", diff --git a/crates/pallet-feeds/src/feed_processor.rs b/crates/pallet-feeds/src/feed_processor.rs index 397129d70fb..08bad2b1401 100644 --- a/crates/pallet-feeds/src/feed_processor.rs +++ b/crates/pallet-feeds/src/feed_processor.rs @@ -20,7 +20,7 @@ use codec::{Compact, CompactLen, Decode, Encode}; use sp_runtime::{DispatchError, DispatchResult}; use sp_std::vec; use sp_std::vec::Vec; -use subspace_core_primitives::Blake2b256Hash; +use subspace_core_primitives::Blake3Hash; /// Holds the offset to some portion of data within/or the object #[derive(Debug)] @@ -35,7 +35,7 @@ pub enum FeedObjectMapping { } impl FeedObjectMapping { - pub(crate) fn try_into_call_object Blake2b256Hash>( + pub(crate) fn try_into_call_object Blake3Hash>( self, feed_id: FeedID, object: &[u8], diff --git a/crates/pallet-feeds/src/lib.rs b/crates/pallet-feeds/src/lib.rs index b89a3ea8c3d..ff4cd5cc3e6 100644 --- a/crates/pallet-feeds/src/lib.rs +++ b/crates/pallet-feeds/src/lib.rs @@ -23,7 +23,7 @@ use core::mem; pub use pallet::*; use sp_std::vec; use sp_std::vec::Vec; -use subspace_core_primitives::{crypto, Blake2b256Hash}; +use subspace_core_primitives::{crypto, Blake3Hash}; pub mod feed_processor; #[cfg(all(feature = "std", test))] @@ -366,7 +366,7 @@ mod pallet { #[derive(Debug)] pub struct CallObject { /// Key to the object located at the offset. - pub key: Blake2b256Hash, + pub key: Blake3Hash, /// Offset of object in the encoded call. pub offset: u32, } @@ -398,7 +398,7 @@ impl Call { let mut co = object_mapping.try_into_call_object( feed_id, object.as_slice(), - |data| crypto::blake2b_256_hash(data), + |data| crypto::blake3_hash(data), )?; co.offset += base_offset; Some(co) diff --git a/crates/pallet-feeds/src/tests.rs b/crates/pallet-feeds/src/tests.rs index fd3d8344901..be4f6e44a5c 100644 --- a/crates/pallet-feeds/src/tests.rs +++ b/crates/pallet-feeds/src/tests.rs @@ -260,7 +260,7 @@ fn create_content_feed(object: Object, kind: MockFeedProcessorKind, contents: Ve content ); - assert_eq!(mappings[i].key, crypto::blake2b_256_hash(&content)); + assert_eq!(mappings[i].key, crypto::blake3_hash(&content)); }) }); } @@ -290,7 +290,7 @@ fn create_custom_content_feed( // key should match the feed name spaced key assert_eq!( mappings[i].key, - crypto::blake2b_256_hash_list(&[&FEED_ID.encode(), key.as_slice()]) + crypto::blake3_hash_list(&[&FEED_ID.encode(), key.as_slice()]) ); }); diff --git a/crates/pallet-object-store/src/lib.rs b/crates/pallet-object-store/src/lib.rs index b0acb292549..2b29b47f712 100644 --- a/crates/pallet-object-store/src/lib.rs +++ b/crates/pallet-object-store/src/lib.rs @@ -25,7 +25,7 @@ mod mock; mod tests; pub use pallet::*; -use subspace_core_primitives::{crypto, Blake2b256Hash}; +use subspace_core_primitives::{crypto, Blake3Hash}; #[frame_support::pallet] mod pallet { @@ -33,7 +33,7 @@ mod pallet { use frame_system::pallet_prelude::*; use log::debug; use sp_std::prelude::*; - use subspace_core_primitives::{crypto, Blake2b256Hash}; + use subspace_core_primitives::{crypto, Blake3Hash}; #[pallet::config] pub trait Config: frame_system::Config { @@ -52,7 +52,7 @@ mod pallet { /// New object was added. ObjectSubmitted { who: T::AccountId, - object_id: Blake2b256Hash, + object_id: Blake3Hash, object_size: u32, }, } @@ -69,7 +69,7 @@ mod pallet { let object_size = object.len() as u32; - let object_id = crypto::blake2b_256_hash(&object); + let object_id = crypto::blake3_hash(&object); debug!( target: "runtime:object-store", @@ -93,7 +93,7 @@ mod pallet { #[derive(Debug)] pub struct CallObject { /// Object hash - pub hash: Blake2b256Hash, + pub hash: Blake3Hash, /// Offset of object in the encoded call. pub offset: u32, } @@ -105,7 +105,7 @@ impl Call { Self::put { object } => { // `1` corresponds to `Call::put {}` enum variant encoding. Some(CallObject { - hash: crypto::blake2b_256_hash(object), + hash: crypto::blake3_hash(object), offset: 1, }) } diff --git a/crates/pallet-object-store/src/tests.rs b/crates/pallet-object-store/src/tests.rs index 982226578dc..9a1a7c7e652 100644 --- a/crates/pallet-object-store/src/tests.rs +++ b/crates/pallet-object-store/src/tests.rs @@ -8,7 +8,7 @@ const ACCOUNT_ID: u64 = 100; fn can_do_put() { new_test_ext().execute_with(|| { let object = vec![1, 2, 3, 4, 5]; - let object_id = crypto::blake2b_256_hash(&object); + let object_id = crypto::blake3_hash(&object); let object_size = object.len() as u32; assert_ok!(ObjectStore::put(RuntimeOrigin::signed(ACCOUNT_ID), object)); diff --git a/crates/pallet-subspace/src/benchmarking.rs b/crates/pallet-subspace/src/benchmarking.rs index ea2b3c77fc7..72c105b0e1d 100644 --- a/crates/pallet-subspace/src/benchmarking.rs +++ b/crates/pallet-subspace/src/benchmarking.rs @@ -22,7 +22,7 @@ mod benchmarks { use sp_std::vec; use sp_std::vec::Vec; use subspace_core_primitives::{ - ArchivedBlockProgress, Blake2b256Hash, LastArchivedBlock, PotOutput, SegmentHeader, + ArchivedBlockProgress, Blake3Hash, LastArchivedBlock, PotOutput, SegmentHeader, SegmentIndex, Solution, SolutionRange, }; @@ -154,7 +154,7 @@ mod benchmarks { SegmentHeader::V0 { segment_index, segment_commitment: subspace_core_primitives::SegmentCommitment::default(), - prev_segment_header_hash: Blake2b256Hash::default(), + prev_segment_header_hash: Blake3Hash::default(), last_archived_block: LastArchivedBlock { number: 0, archived_progress: ArchivedBlockProgress::Complete, diff --git a/crates/pallet-subspace/src/mock.rs b/crates/pallet-subspace/src/mock.rs index 2ff54e4a18d..d1268c33199 100644 --- a/crates/pallet-subspace/src/mock.rs +++ b/crates/pallet-subspace/src/mock.rs @@ -47,7 +47,7 @@ use subspace_archiving::archiver::{Archiver, NewArchivedSegment}; use subspace_core_primitives::crypto::kzg::{embedded_kzg_settings, Kzg}; use subspace_core_primitives::crypto::Scalar; use subspace_core_primitives::{ - ArchivedBlockProgress, ArchivedHistorySegment, Blake2b256Hash, BlockNumber, HistorySize, + ArchivedBlockProgress, ArchivedHistorySegment, Blake3Hash, BlockNumber, HistorySize, LastArchivedBlock, Piece, PieceOffset, PosSeed, PotOutput, PublicKey, Record, RecordedHistorySegment, SegmentCommitment, SegmentHeader, SegmentIndex, SlotNumber, Solution, SolutionRange, REWARD_SIGNING_CONTEXT, @@ -392,7 +392,7 @@ pub fn create_segment_header(segment_index: SegmentIndex) -> SegmentHeader { SegmentHeader::V0 { segment_index, segment_commitment: SegmentCommitment::default(), - prev_segment_header_hash: Blake2b256Hash::default(), + prev_segment_header_hash: Blake3Hash::default(), last_archived_block: LastArchivedBlock { number: 0, archived_progress: ArchivedBlockProgress::Complete, diff --git a/crates/sp-domains/src/bundle_producer_election.rs b/crates/sp-domains/src/bundle_producer_election.rs index e732c2100aa..fc179a7978e 100644 --- a/crates/sp-domains/src/bundle_producer_election.rs +++ b/crates/sp-domains/src/bundle_producer_election.rs @@ -4,12 +4,12 @@ use scale_info::TypeInfo; use sp_core::crypto::{VrfPublic, Wraps}; use sp_core::sr25519::vrf::{VrfOutput, VrfSignature, VrfTranscript}; use sp_std::vec::Vec; -use subspace_core_primitives::Blake2b256Hash; +use subspace_core_primitives::Blake3Hash; const VRF_TRANSCRIPT_LABEL: &[u8] = b"bundle_producer_election"; /// Generates a domain-specific vrf transcript from given global_challenge. -pub fn make_transcript(domain_id: DomainId, global_challenge: &Blake2b256Hash) -> VrfTranscript { +pub fn make_transcript(domain_id: DomainId, global_challenge: &Blake3Hash) -> VrfTranscript { VrfTranscript::new( VRF_TRANSCRIPT_LABEL, &[ @@ -70,7 +70,7 @@ pub(crate) fn verify_vrf_signature( domain_id: DomainId, public_key: &OperatorPublicKey, vrf_signature: &VrfSignature, - global_challenge: &Blake2b256Hash, + global_challenge: &Blake3Hash, ) -> Result<(), VrfProofError> { if !public_key.as_inner_ref().vrf_verify( &make_transcript(domain_id, global_challenge).into(), diff --git a/crates/sp-domains/src/lib.rs b/crates/sp-domains/src/lib.rs index c2162923cab..4a3c66783d0 100644 --- a/crates/sp-domains/src/lib.rs +++ b/crates/sp-domains/src/lib.rs @@ -50,8 +50,8 @@ use sp_runtime::traits::{ use sp_runtime::{DigestItem, OpaqueExtrinsic, Percent}; use sp_std::vec::Vec; use sp_weights::Weight; -use subspace_core_primitives::crypto::blake2b_256_hash; -use subspace_core_primitives::{bidirectional_distance, Blake2b256Hash, Randomness, U256}; +use subspace_core_primitives::crypto::blake3_hash; +use subspace_core_primitives::{bidirectional_distance, Blake3Hash, Randomness, U256}; use subspace_runtime_primitives::{Balance, Moment}; /// Key type for Operator. @@ -505,10 +505,10 @@ impl ProofOfElection { } /// Computes the VRF hash. - pub fn vrf_hash(&self) -> Blake2b256Hash { + pub fn vrf_hash(&self) -> Blake3Hash { let mut bytes = self.vrf_signature.output.encode(); bytes.append(&mut self.vrf_signature.proof.encode()); - blake2b_256_hash(&bytes) + blake3_hash(&bytes) } } diff --git a/crates/sp-domains/src/merkle_tree.rs b/crates/sp-domains/src/merkle_tree.rs index 9f80c670b1f..50ddd126ee0 100644 --- a/crates/sp-domains/src/merkle_tree.rs +++ b/crates/sp-domains/src/merkle_tree.rs @@ -7,7 +7,7 @@ use rs_merkle::Hasher; use scale_info::TypeInfo; use sp_runtime::traits::{BlakeTwo256, Hash}; use sp_std::vec::Vec; -use subspace_core_primitives::Blake2b256Hash; +use subspace_core_primitives::Blake3Hash; /// Merkle tree using [`Blake2b256Algorithm`]. pub type MerkleTree = rs_merkle::MerkleTree; @@ -37,9 +37,9 @@ impl Default for Blake2b256Algorithm { } impl Hasher for Blake2b256Algorithm { - type Hash = Blake2b256Hash; + type Hash = Blake3Hash; - fn hash(data: &[u8]) -> Blake2b256Hash { + fn hash(data: &[u8]) -> Blake3Hash { let mut hasher = Blake2b::new(); hasher.update(data); hasher.finalize_fixed().into() diff --git a/crates/subspace-archiving/src/archiver.rs b/crates/subspace-archiving/src/archiver.rs index a8fb83b447a..9a2012393c2 100644 --- a/crates/subspace-archiving/src/archiver.rs +++ b/crates/subspace-archiving/src/archiver.rs @@ -30,12 +30,12 @@ use parity_scale_codec::{Compact, CompactLen, Decode, Encode, Input, Output}; #[cfg(feature = "parallel")] use rayon::prelude::*; use subspace_core_primitives::crypto::kzg::{Commitment, Kzg, Witness}; -use subspace_core_primitives::crypto::{blake2b_256_254_hash_to_scalar, Scalar}; +use subspace_core_primitives::crypto::{blake3_254_hash_to_scalar, Scalar}; use subspace_core_primitives::objects::{ BlockObject, BlockObjectMapping, PieceObject, PieceObjectMapping, }; use subspace_core_primitives::{ - ArchivedBlockProgress, ArchivedHistorySegment, Blake2b256Hash, BlockNumber, LastArchivedBlock, + ArchivedBlockProgress, ArchivedHistorySegment, Blake3Hash, BlockNumber, LastArchivedBlock, PieceArray, RawRecord, RecordWitness, RecordedHistorySegment, SegmentCommitment, SegmentHeader, SegmentIndex, }; @@ -238,7 +238,7 @@ pub struct Archiver { /// An index of the current segment segment_index: SegmentIndex, /// Hash of the segment header of the previous segment - prev_segment_header_hash: Blake2b256Hash, + prev_segment_header_hash: Blake3Hash, /// Last archived block last_archived_block: LastArchivedBlock, } @@ -267,7 +267,7 @@ impl Archiver { erasure_coding, kzg, segment_index: SegmentIndex::ZERO, - prev_segment_header_hash: Blake2b256Hash::default(), + prev_segment_header_hash: Blake3Hash::default(), last_archived_block: INITIAL_LAST_ARCHIVED_BLOCK, }) } @@ -780,7 +780,7 @@ impl Archiver { .poly( &record_commitments .iter() - .map(|commitment| blake2b_256_254_hash_to_scalar(&commitment.to_bytes())) + .map(|commitment| blake3_254_hash_to_scalar(&commitment.to_bytes())) .collect::>(), ) .expect("Internally produced values must never fail; qed"); @@ -890,7 +890,7 @@ pub fn is_piece_valid( return false; }; - let commitment_hash = blake2b_256_254_hash_to_scalar(commitment.as_ref()); + let commitment_hash = blake3_254_hash_to_scalar(commitment.as_ref()); kzg.verify( &segment_commitment, diff --git a/crates/subspace-archiving/src/piece_reconstructor.rs b/crates/subspace-archiving/src/piece_reconstructor.rs index 015d6e57e1c..2ddfaa5b0e1 100644 --- a/crates/subspace-archiving/src/piece_reconstructor.rs +++ b/crates/subspace-archiving/src/piece_reconstructor.rs @@ -6,7 +6,7 @@ use core::num::NonZeroUsize; #[cfg(feature = "parallel")] use rayon::prelude::*; use subspace_core_primitives::crypto::kzg::{Commitment, Kzg, Polynomial}; -use subspace_core_primitives::crypto::{blake2b_256_254_hash_to_scalar, Scalar}; +use subspace_core_primitives::crypto::{blake3_254_hash_to_scalar, Scalar}; use subspace_core_primitives::{ArchivedHistorySegment, Piece, RawRecord}; use subspace_erasure_coding::ErasureCoding; @@ -177,7 +177,7 @@ impl PiecesReconstructor { reconstructed_piece .commitment_mut() .copy_from_slice(&commitment_bytes); - blake2b_256_254_hash_to_scalar(&commitment_bytes) + blake3_254_hash_to_scalar(&commitment_bytes) }) .collect::>(); diff --git a/crates/subspace-archiving/tests/integration/archiver.rs b/crates/subspace-archiving/tests/integration/archiver.rs index 4ccf04a3097..46c1fd5a325 100644 --- a/crates/subspace-archiving/tests/integration/archiver.rs +++ b/crates/subspace-archiving/tests/integration/archiver.rs @@ -11,9 +11,8 @@ use subspace_core_primitives::crypto::kzg::{embedded_kzg_settings, Kzg}; use subspace_core_primitives::crypto::Scalar; use subspace_core_primitives::objects::{BlockObject, BlockObjectMapping, PieceObject}; use subspace_core_primitives::{ - ArchivedBlockProgress, ArchivedHistorySegment, Blake2b256Hash, LastArchivedBlock, PieceArray, + ArchivedBlockProgress, ArchivedHistorySegment, Blake3Hash, LastArchivedBlock, PieceArray, Record, RecordedHistorySegment, SegmentCommitment, SegmentHeader, SegmentIndex, - BLAKE2B_256_HASH_SIZE, }; fn extract_data>(data: &[u8], offset: O) -> &[u8] { @@ -82,11 +81,11 @@ fn archiver() { let object_mapping = BlockObjectMapping { objects: vec![ BlockObject::V0 { - hash: Blake2b256Hash::default(), + hash: Blake3Hash::default(), offset: 0u32, }, BlockObject::V0 { - hash: Blake2b256Hash::default(), + hash: Blake3Hash::default(), offset: RecordedHistorySegment::SIZE as u32 / 3, }, ], @@ -118,15 +117,15 @@ fn archiver() { let object_mapping = BlockObjectMapping { objects: vec![ BlockObject::V0 { - hash: Blake2b256Hash::default(), + hash: Blake3Hash::default(), offset: RecordedHistorySegment::SIZE as u32 / 6, }, BlockObject::V0 { - hash: Blake2b256Hash::default(), + hash: Blake3Hash::default(), offset: RecordedHistorySegment::SIZE as u32 / 5, }, BlockObject::V0 { - hash: Blake2b256Hash::default(), + hash: Blake3Hash::default(), offset: RecordedHistorySegment::SIZE as u32 / 3 * 2 - 200, }, ], @@ -151,7 +150,7 @@ fn archiver() { first_archived_segment .segment_header .prev_segment_header_hash(), - [0u8; BLAKE2B_256_HASH_SIZE] + Blake3Hash::default(), ); { let last_archived_block = first_archived_segment.segment_header.last_archived_block(); @@ -398,7 +397,7 @@ fn invalid_usage() { SegmentHeader::V0 { segment_index: SegmentIndex::ZERO, segment_commitment: SegmentCommitment::default(), - prev_segment_header_hash: Blake2b256Hash::default(), + prev_segment_header_hash: Blake3Hash::default(), last_archived_block: LastArchivedBlock { number: 0, archived_progress: ArchivedBlockProgress::Partial(10), @@ -424,7 +423,7 @@ fn invalid_usage() { SegmentHeader::V0 { segment_index: SegmentIndex::ZERO, segment_commitment: SegmentCommitment::default(), - prev_segment_header_hash: Blake2b256Hash::default(), + prev_segment_header_hash: Blake3Hash::default(), last_archived_block: LastArchivedBlock { number: 0, archived_progress: ArchivedBlockProgress::Partial(10), @@ -521,7 +520,7 @@ fn spill_over_edge_case() { vec![0u8; RecordedHistorySegment::SIZE], BlockObjectMapping { objects: vec![BlockObject::V0 { - hash: Blake2b256Hash::default(), + hash: Blake3Hash::default(), offset: 0, }], }, @@ -566,7 +565,7 @@ fn object_on_the_edge_of_segment() { let mut second_block = vec![0u8; RecordedHistorySegment::SIZE * 2]; let object_mapping = BlockObject::V0 { - hash: Blake2b256Hash::default(), + hash: Blake3Hash::default(), // Offset is designed to fall exactly on the edge of the segment offset: RecordedHistorySegment::SIZE as u32 // Segment enum variant diff --git a/crates/subspace-core-primitives/Cargo.toml b/crates/subspace-core-primitives/Cargo.toml index d71dbe1c26e..5cc0b19de22 100644 --- a/crates/subspace-core-primitives/Cargo.toml +++ b/crates/subspace-core-primitives/Cargo.toml @@ -16,7 +16,6 @@ include = [ bench = false [dependencies] -blake2 = { version = "0.10.6", default-features = false } blake3 = { version = "1.4.1", default-features = false } # TODO: Switch to upstream `main` once https://github.com/sifraitech/rust-kzg/pull/204 is merged and blst has upstream no_std support blst_rust = { git = "https://github.com/subspace/rust-kzg", rev = "1058cc8c8af8461b490dc212c41d7d506a746577", default-features = false } @@ -65,7 +64,6 @@ serde = [ "hex/serde", ] std = [ - "blake2/std", "blake3/std", "blst_rust/std", "hex/std", diff --git a/crates/subspace-core-primitives/src/crypto.rs b/crates/subspace-core-primitives/src/crypto.rs index a1581a27f8a..985cce8218b 100644 --- a/crates/subspace-core-primitives/src/crypto.rs +++ b/crates/subspace-core-primitives/src/crypto.rs @@ -19,13 +19,10 @@ extern crate alloc; pub mod kzg; -use crate::{Blake2b256Hash, Blake3Hash}; +use crate::Blake3Hash; use alloc::format; use alloc::string::String; use alloc::vec::Vec; -use blake2::digest::typenum::U32; -use blake2::digest::{FixedOutput, Update}; -use blake2::{Blake2b, Blake2bMac, Digest}; use blst_rust::types::fr::FsFr; use core::cmp::Ordering; use core::hash::{Hash, Hasher}; @@ -34,56 +31,6 @@ use derive_more::{AsMut, AsRef, Deref, DerefMut, From, Into}; use parity_scale_codec::{Decode, Encode, EncodeLike, Input, MaxEncodedLen}; use scale_info::{Type, TypeInfo}; -/// BLAKE2b-256 hashing of a single value. -pub fn blake2b_256_hash(data: &[u8]) -> Blake2b256Hash { - let mut state = Blake2b::::new(); - Update::update(&mut state, data); - state.finalize_fixed().into() -} - -/// BLAKE2b-256 hashing of a single value truncated to 254 bits. -/// -/// TODO: We probably wouldn't need this eventually -pub fn blake2b_256_254_hash(data: &[u8]) -> Blake2b256Hash { - let mut hash = blake2b_256_hash(data); - // Erase last 2 bits to effectively truncate the hash (number is interpreted as little-endian) - hash[31] &= 0b00111111; - hash -} - -/// BLAKE2b-256 hashing of a single value truncated to 254 bits. -/// -/// TODO: We probably wouldn't need this eventually -pub fn blake2b_256_254_hash_to_scalar(data: &[u8]) -> Scalar { - let mut hash = blake2b_256_hash(data); - // Erase last 2 bits to effectively truncate the hash (number is interpreted as little-endian) - hash[31] &= 0b00111111; - Scalar::try_from(hash) - .expect("Last bit erased, thus hash is guaranteed to fit into scalar; qed") -} - -/// BLAKE2b-256 keyed hashing of a single value. -/// -/// PANIC: Panics if key is longer than 64 bytes. -pub fn blake2b_256_hash_with_key(key: &[u8], data: &[u8]) -> Blake2b256Hash { - let mut state = Blake2bMac::::new_with_salt_and_personal(key, &[], &[]) - .expect("Only panics when key is over 64 bytes as specified in function description"); - Update::update(&mut state, data); - state.finalize_fixed().into() -} - -/// BLAKE2b-256 hashing of a list of values. -pub fn blake2b_256_hash_list(data: &[&[u8]]) -> Blake2b256Hash { - let mut state = Blake2b::::new(); - for d in data { - Update::update(&mut state, d); - } - state - .finalize() - .try_into() - .expect("Initialized with correct length; qed") -} - /// BLAKE3 hashing of a single value. pub fn blake3_hash(data: &[u8]) -> Blake3Hash { *blake3::hash(data).as_bytes() @@ -97,6 +44,11 @@ pub fn blake3_hash_parallel(data: &[u8]) -> Blake3Hash { *state.finalize().as_bytes() } +/// BLAKE3 keyed hashing of a single value. +pub fn blake3_hash_with_key(key: &[u8; 32], data: &[u8]) -> Blake3Hash { + *blake3::keyed_hash(key, data).as_bytes() +} + /// BLAKE3 hashing of a list of values. pub fn blake3_hash_list(data: &[&[u8]]) -> Blake3Hash { let mut state = blake3::Hasher::new(); @@ -106,6 +58,17 @@ pub fn blake3_hash_list(data: &[&[u8]]) -> Blake3Hash { *state.finalize().as_bytes() } +/// BLAKE3 hashing of a single value truncated to 254 bits. +/// +/// TODO: We probably wouldn't need this eventually +pub fn blake3_254_hash_to_scalar(data: &[u8]) -> Scalar { + let mut hash = blake3_hash(data); + // Erase last 2 bits to effectively truncate the hash (number is interpreted as little-endian) + hash[31] &= 0b00111111; + Scalar::try_from(hash) + .expect("Last bit erased, thus hash is guaranteed to fit into scalar; qed") +} + /// Representation of a single BLS12-381 scalar value. #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, From, Into, AsRef, AsMut, Deref, DerefMut)] #[repr(transparent)] diff --git a/crates/subspace-core-primitives/src/lib.rs b/crates/subspace-core-primitives/src/lib.rs index 477c24f7b2c..0a3cf46fb79 100644 --- a/crates/subspace-core-primitives/src/lib.rs +++ b/crates/subspace-core-primitives/src/lib.rs @@ -41,10 +41,7 @@ mod tests; extern crate alloc; -use crate::crypto::{ - blake2b_256_hash, blake2b_256_hash_list, blake2b_256_hash_with_key, blake3_hash, - blake3_hash_list, Scalar, -}; +use crate::crypto::{blake3_hash, blake3_hash_list, blake3_hash_with_key, Scalar}; #[cfg(feature = "serde")] use ::serde::{Deserialize, Serialize}; use alloc::boxed::Box; @@ -77,12 +74,6 @@ pub const REWARD_SIGNING_CONTEXT: &[u8] = b"subspace_reward"; /// Byte length of a randomness type. pub const RANDOMNESS_LENGTH: usize = 32; -/// Size of BLAKE2b-256 hash output (in bytes). -pub const BLAKE2B_256_HASH_SIZE: usize = 32; - -/// BLAKE2b-256 hash output -pub type Blake2b256Hash = [u8; BLAKE2B_256_HASH_SIZE]; - /// Size of BLAKE3 hash output (in bytes). pub const BLAKE3_HASH_SIZE: usize = 32; @@ -127,8 +118,8 @@ impl AsMut<[u8]> for Randomness { impl Randomness { /// Derive global slot challenge from global randomness. // TODO: Separate type for global challenge - pub fn derive_global_challenge(&self, slot: SlotNumber) -> Blake2b256Hash { - blake2b_256_hash_list(&[&self.0, &slot.to_le_bytes()]) + pub fn derive_global_challenge(&self, slot: SlotNumber) -> Blake3Hash { + blake3_hash_list(&[&self.0, &slot.to_le_bytes()]) } } @@ -233,8 +224,8 @@ impl PosProof { pub const SIZE: usize = 20 * 8; /// Proof hash. - pub fn hash(&self) -> Blake2b256Hash { - blake2b_256_hash(&self.0) + pub fn hash(&self) -> Blake3Hash { + blake3_hash(&self.0) } } @@ -367,7 +358,7 @@ impl PotOutput { /// Derives the global randomness from the output #[inline] pub fn derive_global_randomness(&self) -> Randomness { - Randomness::from(blake2b_256_hash(&self.0)) + Randomness::from(blake3_hash(&self.0)) } /// Derive seed from proof of time in case entropy injection is not needed @@ -453,8 +444,8 @@ impl AsRef<[u8]> for PublicKey { impl PublicKey { /// Public key hash. - pub fn hash(&self) -> Blake2b256Hash { - blake2b_256_hash(&self.0) + pub fn hash(&self) -> Blake3Hash { + blake3_hash(&self.0) } } @@ -570,7 +561,7 @@ pub enum SegmentHeader { /// Root of commitments of all records in a segment. segment_commitment: SegmentCommitment, /// Hash of the segment header of the previous segment - prev_segment_header_hash: Blake2b256Hash, + prev_segment_header_hash: Blake3Hash, /// Last archived block last_archived_block: LastArchivedBlock, }, @@ -578,8 +569,8 @@ pub enum SegmentHeader { impl SegmentHeader { /// Hash of the whole segment header - pub fn hash(&self) -> Blake2b256Hash { - blake2b_256_hash(&self.encode()) + pub fn hash(&self) -> Blake3Hash { + blake3_hash(&self.encode()) } /// Segment index @@ -599,7 +590,7 @@ impl SegmentHeader { } /// Hash of the segment header of the previous segment - pub fn prev_segment_header_hash(&self) -> Blake2b256Hash { + pub fn prev_segment_header_hash(&self) -> Blake3Hash { match self { Self::V0 { prev_segment_header_hash, @@ -947,7 +938,7 @@ impl Default for U256 { /// Challenge used for a particular sector for particular slot #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deref)] -pub struct SectorSlotChallenge(Blake2b256Hash); +pub struct SectorSlotChallenge(Blake3Hash); impl SectorSlotChallenge { /// Index of s-bucket within sector to be audited @@ -966,7 +957,7 @@ impl SectorSlotChallenge { /// Data structure representing sector ID in farmer's plot #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Encode, Decode, TypeInfo)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct SectorId(#[cfg_attr(feature = "serde", serde(with = "hex::serde"))] Blake2b256Hash); +pub struct SectorId(#[cfg_attr(feature = "serde", serde(with = "hex::serde"))] Blake3Hash); impl AsRef<[u8]> for SectorId { #[inline] @@ -977,8 +968,8 @@ impl AsRef<[u8]> for SectorId { impl SectorId { /// Create new sector ID by deriving it from public key and sector index - pub fn new(public_key_hash: Blake2b256Hash, sector_index: SectorIndex) -> Self { - Self(blake2b_256_hash_with_key( + pub fn new(public_key_hash: Blake3Hash, sector_index: SectorIndex) -> Self { + Self(blake3_hash_with_key( &public_key_hash, §or_index.to_le_bytes(), )) @@ -1000,8 +991,12 @@ impl SectorId { let min_history_size_in_pieces = recent_segments_in_pieces * recent_history_fraction.1.in_pieces().get() / recent_history_fraction.0.in_pieces().get(); - let input_hash = - U256::from_le_bytes(blake2b_256_hash_with_key(&piece_offset.to_bytes(), &self.0)); + let input_hash = { + let piece_offset_bytes = piece_offset.to_bytes(); + let mut key = [0; 32]; + key[..piece_offset_bytes.len()].copy_from_slice(&piece_offset_bytes); + U256::from_le_bytes(blake3_hash_with_key(&key, &self.0)) + }; let history_size_in_pieces = history_size.in_pieces().get(); let num_interleaved_pieces = 1.max( u64::from(max_pieces_in_sector) * recent_history_fraction.0.in_pieces().get() @@ -1029,7 +1024,7 @@ impl SectorId { /// Derive sector slot challenge for this sector from provided global challenge pub fn derive_sector_slot_challenge( &self, - global_challenge: &Blake2b256Hash, + global_challenge: &Blake3Hash, ) -> SectorSlotChallenge { let sector_slot_challenge = Simd::from(self.0) ^ Simd::from(*global_challenge); SectorSlotChallenge(sector_slot_challenge.to_array()) @@ -1041,7 +1036,7 @@ impl SectorId { piece_offset: PieceOffset, history_size: HistorySize, ) -> PosSeed { - let evaluation_seed = blake2b_256_hash_list(&[ + let evaluation_seed = blake3_hash_list(&[ &self.0, &piece_offset.to_bytes(), &history_size.get().to_le_bytes(), @@ -1062,7 +1057,7 @@ impl SectorId { let sector_expiration_check_history_size = history_size.sector_expiration_check(min_sector_lifetime)?; - let input_hash = U256::from_le_bytes(blake2b_256_hash_list(&[ + let input_hash = U256::from_le_bytes(blake3_hash_list(&[ &self.0, sector_expiration_check_segment_commitment.as_ref(), ])); diff --git a/crates/subspace-core-primitives/src/objects.rs b/crates/subspace-core-primitives/src/objects.rs index c2ba1f2aeb5..19db4cbb388 100644 --- a/crates/subspace-core-primitives/src/objects.rs +++ b/crates/subspace-core-primitives/src/objects.rs @@ -22,7 +22,7 @@ #[cfg(not(feature = "std"))] extern crate alloc; -use crate::{Blake2b256Hash, PieceIndex}; +use crate::{Blake3Hash, PieceIndex}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use parity_scale_codec::{Decode, Encode}; @@ -40,7 +40,7 @@ pub enum BlockObject { #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] V0 { /// Object hash - hash: Blake2b256Hash, + hash: Blake3Hash, /// Offset of object in the encoded block. offset: u32, }, @@ -48,7 +48,7 @@ pub enum BlockObject { impl BlockObject { /// Object hash - pub fn hash(&self) -> Blake2b256Hash { + pub fn hash(&self) -> Blake3Hash { match self { Self::V0 { hash, .. } => *hash, } @@ -90,7 +90,7 @@ pub enum PieceObject { #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] V0 { /// Object hash - hash: Blake2b256Hash, + hash: Blake3Hash, // TODO: This is a raw record offset, not a regular one /// Offset of the object offset: u32, @@ -99,7 +99,7 @@ pub enum PieceObject { impl PieceObject { /// Object hash - pub fn hash(&self) -> Blake2b256Hash { + pub fn hash(&self) -> Blake3Hash { match self { Self::V0 { hash, .. } => *hash, } diff --git a/crates/subspace-farmer-components/benches/auditing.rs b/crates/subspace-farmer-components/benches/auditing.rs index a6567907d32..f6b754072e6 100644 --- a/crates/subspace-farmer-components/benches/auditing.rs +++ b/crates/subspace-farmer-components/benches/auditing.rs @@ -10,7 +10,7 @@ use subspace_archiving::archiver::Archiver; use subspace_core_primitives::crypto::kzg; use subspace_core_primitives::crypto::kzg::Kzg; use subspace_core_primitives::{ - Blake2b256Hash, HistorySize, PublicKey, Record, RecordedHistorySegment, SectorId, SectorIndex, + Blake3Hash, HistorySize, PublicKey, Record, RecordedHistorySegment, SectorId, SectorIndex, SolutionRange, }; use subspace_erasure_coding::ErasureCoding; @@ -75,7 +75,7 @@ pub fn criterion_benchmark(c: &mut Criterion) { ), min_sector_lifetime: HistorySize::from(NonZeroU64::new(4).unwrap()), }; - let global_challenge = Blake2b256Hash::default(); + let global_challenge = Blake3Hash::default(); let solution_range = SolutionRange::MAX; let sector_size = sector_size(pieces_in_sector); diff --git a/crates/subspace-farmer-components/benches/proving.rs b/crates/subspace-farmer-components/benches/proving.rs index 937d1bc1f92..e5455946657 100644 --- a/crates/subspace-farmer-components/benches/proving.rs +++ b/crates/subspace-farmer-components/benches/proving.rs @@ -11,7 +11,7 @@ use subspace_archiving::archiver::Archiver; use subspace_core_primitives::crypto::kzg; use subspace_core_primitives::crypto::kzg::Kzg; use subspace_core_primitives::{ - Blake2b256Hash, HistorySize, PosSeed, PublicKey, Record, RecordedHistorySegment, SectorId, + Blake3Hash, HistorySize, PosSeed, PublicKey, Record, RecordedHistorySegment, SectorId, SolutionRange, }; use subspace_erasure_coding::ErasureCoding; @@ -149,7 +149,7 @@ pub fn criterion_benchmark(c: &mut Criterion) { println!("Searching for solutions"); let global_challenge = loop { - let mut global_challenge = Blake2b256Hash::default(); + let mut global_challenge = Blake3Hash::default(); rng.fill_bytes(&mut global_challenge); let maybe_audit_result = audit_sector( diff --git a/crates/subspace-farmer-components/src/auditing.rs b/crates/subspace-farmer-components/src/auditing.rs index 3b4ec733db8..ca243969194 100644 --- a/crates/subspace-farmer-components/src/auditing.rs +++ b/crates/subspace-farmer-components/src/auditing.rs @@ -3,7 +3,7 @@ use crate::sector::{SectorContentsMap, SectorMetadataChecksummed}; use crate::ReadAt; use std::mem; use subspace_core_primitives::crypto::Scalar; -use subspace_core_primitives::{Blake2b256Hash, PublicKey, SectorId, SectorIndex, SolutionRange}; +use subspace_core_primitives::{Blake3Hash, PublicKey, SectorId, SectorIndex, SolutionRange}; use subspace_verification::is_within_solution_range; use tracing::warn; @@ -44,7 +44,7 @@ pub(crate) struct ChunkCandidate { pub fn audit_sector<'a, Sector>( public_key: &'a PublicKey, sector_index: SectorIndex, - global_challenge: &Blake2b256Hash, + global_challenge: &Blake3Hash, solution_range: SolutionRange, sector: Sector, sector_metadata: &'a SectorMetadataChecksummed, diff --git a/crates/subspace-farmer/src/single_disk_farm/plotting.rs b/crates/subspace-farmer/src/single_disk_farm/plotting.rs index 09dfed2144e..558443bd317 100644 --- a/crates/subspace-farmer/src/single_disk_farm/plotting.rs +++ b/crates/subspace-farmer/src/single_disk_farm/plotting.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use std::time::Duration; use subspace_core_primitives::crypto::kzg::Kzg; use subspace_core_primitives::{ - Blake2b256Hash, HistorySize, PieceOffset, PublicKey, SectorId, SectorIndex, SegmentHeader, + Blake3Hash, HistorySize, PieceOffset, PublicKey, SectorId, SectorIndex, SegmentHeader, SegmentIndex, }; use subspace_erasure_coding::ErasureCoding; @@ -286,7 +286,7 @@ where } pub(super) struct PlottingSchedulerOptions { - pub(super) public_key_hash: Blake2b256Hash, + pub(super) public_key_hash: Blake3Hash, pub(super) sectors_indices_left_to_plot: Range, pub(super) target_sector_count: SectorIndex, pub(super) last_archived_segment_index: SegmentIndex, @@ -482,7 +482,7 @@ where #[allow(clippy::too_many_arguments)] async fn send_plotting_notifications( - public_key_hash: Blake2b256Hash, + public_key_hash: Blake3Hash, sectors_indices_left_to_plot: Range, target_sector_count: SectorIndex, min_sector_lifetime: HistorySize, diff --git a/crates/subspace-networking/src/constructor.rs b/crates/subspace-networking/src/constructor.rs index 5a91079584e..290ca4b3fbe 100644 --- a/crates/subspace-networking/src/constructor.rs +++ b/crates/subspace-networking/src/constructor.rs @@ -289,7 +289,7 @@ where .validation_mode(ValidationMode::None) // To content-address message, we can take the hash of message and use it as an ID. .message_id_fn(|message: &GossipsubMessage| { - MessageId::from(crypto::blake2b_256_hash(&message.data)) + MessageId::from(crypto::blake3_hash(&message.data)) }) .max_transmit_size(2 * 1024 * 1024) // 2MB .build() diff --git a/crates/subspace-proof-of-space/src/shim.rs b/crates/subspace-proof-of-space/src/shim.rs index ebbedb4177a..03156fec5e2 100644 --- a/crates/subspace-proof-of-space/src/shim.rs +++ b/crates/subspace-proof-of-space/src/shim.rs @@ -2,8 +2,8 @@ use crate::{PosTableType, Quality, Table, TableGenerator}; use core::iter; -use subspace_core_primitives::crypto::blake2b_256_hash; -use subspace_core_primitives::{Blake2b256Hash, PosProof, PosQualityBytes, PosSeed, U256}; +use subspace_core_primitives::crypto::blake3_hash; +use subspace_core_primitives::{Blake3Hash, PosProof, PosQualityBytes, PosSeed, U256}; /// Abstraction that represents quality of the solution in the table. /// @@ -12,7 +12,7 @@ use subspace_core_primitives::{Blake2b256Hash, PosProof, PosQualityBytes, PosSee #[must_use] pub struct ShimQuality<'a> { seed: &'a PosSeed, - quality: Blake2b256Hash, + quality: Blake3Hash, } impl<'a> Quality for ShimQuality<'a> { @@ -89,7 +89,7 @@ impl Table for ShimTable { } fn find_quality(seed: &PosSeed, challenge_index: u32) -> Option> { - let quality = blake2b_256_hash(&challenge_index.to_le_bytes()); + let quality = blake3_hash(&challenge_index.to_le_bytes()); (U256::from_le_bytes(quality) % U256::from(3u32) > U256::zero()) .then_some(ShimQuality { seed, quality }) } diff --git a/crates/subspace-rpc-primitives/src/lib.rs b/crates/subspace-rpc-primitives/src/lib.rs index 06efcff2109..75c1bd1e23c 100644 --- a/crates/subspace-rpc-primitives/src/lib.rs +++ b/crates/subspace-rpc-primitives/src/lib.rs @@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize}; use std::time::Duration; use subspace_core_primitives::{ - Blake2b256Hash, PublicKey, RewardSignature, SlotNumber, Solution, SolutionRange, + Blake3Hash, PublicKey, RewardSignature, SlotNumber, Solution, SolutionRange, }; use subspace_farmer_components::FarmerProtocolInfo; use subspace_networking::libp2p::Multiaddr; @@ -48,7 +48,7 @@ pub struct SlotInfo { /// Slot number pub slot_number: SlotNumber, /// Global slot challenge - pub global_challenge: Blake2b256Hash, + pub global_challenge: Blake3Hash, /// Acceptable solution range for block authoring pub solution_range: SolutionRange, /// Acceptable solution range for voting diff --git a/crates/subspace-runtime/tests/integration/object_mapping.rs b/crates/subspace-runtime/tests/integration/object_mapping.rs index b457e0426b1..c33f00985be 100644 --- a/crates/subspace-runtime/tests/integration/object_mapping.rs +++ b/crates/subspace-runtime/tests/integration/object_mapping.rs @@ -4,7 +4,7 @@ use sp_objects::runtime_decl_for_objects_api::ObjectsApiV1; use sp_runtime::traits::{BlakeTwo256, Hash as HashT}; use sp_runtime::BuildStorage; use subspace_core_primitives::objects::BlockObjectMapping; -use subspace_core_primitives::{crypto, Blake2b256Hash}; +use subspace_core_primitives::{crypto, Blake3Hash}; use subspace_runtime::{ Block, FeedProcessorKind, Feeds, Header, Runtime, RuntimeCall, RuntimeOrigin, System, UncheckedExtrinsic, @@ -114,13 +114,13 @@ fn object_mapping() { assert_eq!(objects.len(), 7); // Hashes should be computed correctly. - assert_eq!(objects[0].hash(), crypto::blake2b_256_hash(&data0)); - assert_eq!(objects[1].hash(), crypto::blake2b_256_hash(&data1)); - assert_eq!(objects[2].hash(), crypto::blake2b_256_hash(&data2)); - assert_eq!(objects[3].hash(), crypto::blake2b_256_hash(&data3)); - assert_eq!(objects[4].hash(), crypto::blake2b_256_hash(&data0)); - assert_eq!(objects[5].hash(), crypto::blake2b_256_hash(&data2)); - assert_eq!(objects[6].hash(), crypto::blake2b_256_hash(&data3)); + assert_eq!(objects[0].hash(), crypto::blake3_hash(&data0)); + assert_eq!(objects[1].hash(), crypto::blake3_hash(&data1)); + assert_eq!(objects[2].hash(), crypto::blake3_hash(&data2)); + assert_eq!(objects[3].hash(), crypto::blake3_hash(&data3)); + assert_eq!(objects[4].hash(), crypto::blake3_hash(&data0)); + assert_eq!(objects[5].hash(), crypto::blake3_hash(&data2)); + assert_eq!(objects[6].hash(), crypto::blake3_hash(&data3)); // Offsets for mapped objects should be correct assert_eq!( @@ -183,8 +183,8 @@ fn get_successful_calls(block: Block) -> Vec { .collect() } -fn key(feed_id: u64, data: &[u8]) -> Blake2b256Hash { - crypto::blake2b_256_hash_list(&[&feed_id.encode(), data]) +fn key(feed_id: u64, data: &[u8]) -> Blake3Hash { + crypto::blake3_hash_list(&[&feed_id.encode(), data]) } #[test] @@ -251,7 +251,7 @@ fn new_test_ext() -> sp_io::TestExternalities { } // returns init data, encoded signed block with finality verification, and the block hash -fn get_encoded_blocks() -> (Vec, Vec, Vec) { +fn get_encoded_blocks() -> (Vec, Vec, Vec) { let init_data = vec![ 157, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, diff --git a/crates/subspace-verification/src/lib.rs b/crates/subspace-verification/src/lib.rs index 1ebdd025ef8..e26568dccef 100644 --- a/crates/subspace-verification/src/lib.rs +++ b/crates/subspace-verification/src/lib.rs @@ -29,12 +29,12 @@ use sp_arithmetic::traits::SaturatedConversion; use subspace_archiving::archiver; use subspace_core_primitives::crypto::kzg::{Commitment, Kzg, Witness}; use subspace_core_primitives::crypto::{ - blake2b_256_254_hash_to_scalar, blake2b_256_hash_with_key, blake3_hash_list, Scalar, + blake3_254_hash_to_scalar, blake3_hash_list, blake3_hash_with_key, Scalar, }; use subspace_core_primitives::{ - Blake2b256Hash, Blake3Hash, BlockNumber, BlockWeight, HistorySize, PotOutput, PublicKey, - Record, RewardSignature, SectorId, SectorSlotChallenge, SegmentCommitment, SlotNumber, - Solution, SolutionRange, + Blake3Hash, BlockNumber, BlockWeight, HistorySize, PotOutput, PublicKey, Record, + RewardSignature, SectorId, SectorSlotChallenge, SegmentCommitment, SlotNumber, Solution, + SolutionRange, }; use subspace_proof_of_space::Table; @@ -104,7 +104,7 @@ pub fn check_reward_signature( /// Calculates solution distance for given parameters, is used as a primitive to check whether /// solution distance is within solution range (see [`is_within_solution_range()`]). fn calculate_solution_distance( - global_challenge: &Blake2b256Hash, + global_challenge: &Blake3Hash, audit_chunk: SolutionRange, sector_slot_challenge: &SectorSlotChallenge, ) -> SolutionRange { @@ -115,13 +115,13 @@ fn calculate_solution_distance( .expect("Solution range is smaller in size than global challenge; qed"), ); let sector_slot_challenge_with_audit_chunk = - blake2b_256_hash_with_key(sector_slot_challenge.as_ref(), &audit_chunk.to_le_bytes()); + blake3_hash_with_key(sector_slot_challenge, &audit_chunk.to_le_bytes()); let sector_slot_challenge_with_audit_chunk_as_solution_range: SolutionRange = SolutionRange::from_le_bytes( *sector_slot_challenge_with_audit_chunk .array_chunks::<{ mem::size_of::() }>() .next() - .expect("Solution range is smaller in size than blake2b-256 hash; qed"), + .expect("Solution range is smaller in size than blake3 hash; qed"), ); subspace_core_primitives::bidirectional_distance( &global_challenge_as_solution_range, @@ -132,7 +132,7 @@ fn calculate_solution_distance( /// Returns `Some(solution_distance)` if solution distance is within the solution range for provided /// parameters. pub fn is_within_solution_range( - global_challenge: &Blake2b256Hash, + global_challenge: &Blake3Hash, audit_chunk: SolutionRange, sector_slot_challenge: &SectorSlotChallenge, solution_range: SolutionRange, @@ -308,7 +308,7 @@ where // Check that piece is part of the blockchain history if !archiver::is_record_commitment_hash_valid( kzg, - &blake2b_256_254_hash_to_scalar(solution.record_commitment.as_ref()), + &blake3_254_hash_to_scalar(solution.record_commitment.as_ref()), segment_commitment, &solution.record_witness, position, diff --git a/domains/runtime/evm/src/lib.rs b/domains/runtime/evm/src/lib.rs index 1a120e71bf3..2e6f2e9793b 100644 --- a/domains/runtime/evm/src/lib.rs +++ b/domains/runtime/evm/src/lib.rs @@ -817,12 +817,12 @@ impl_runtime_apis! { tx_range: &subspace_core_primitives::U256 ) -> bool { use subspace_core_primitives::U256; - use subspace_core_primitives::crypto::blake2b_256_hash; + use subspace_core_primitives::crypto::blake3_hash; let lookup = frame_system::ChainContext::::default(); if let Some(signer) = extract_signer_inner(extrinsic, &lookup) { // Check if the signer Id hash is within the tx range - let signer_id_hash = U256::from_be_bytes(blake2b_256_hash(&signer.encode())); + let signer_id_hash = U256::from_be_bytes(blake3_hash(&signer.encode())); sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range) } else { // Unsigned transactions are always in the range. diff --git a/domains/test/runtime/evm/src/lib.rs b/domains/test/runtime/evm/src/lib.rs index da0cde4bcf1..8311c73d9ae 100644 --- a/domains/test/runtime/evm/src/lib.rs +++ b/domains/test/runtime/evm/src/lib.rs @@ -815,11 +815,11 @@ impl_runtime_apis! { tx_range: &subspace_core_primitives::U256 ) -> bool { use subspace_core_primitives::U256; - use subspace_core_primitives::crypto::blake2b_256_hash; + use subspace_core_primitives::crypto::blake3_hash; let lookup = frame_system::ChainContext::::default(); if let Some(signer) = extract_signer_inner(extrinsic, &lookup) { - let signer_id_hash = U256::from_be_bytes(blake2b_256_hash(&signer.encode())); + let signer_id_hash = U256::from_be_bytes(blake3_hash(&signer.encode())); sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range) } else { true