Compare commits
14 Commits
d0db73170d
...
8e44a7f5d2
| Author | SHA1 | Date | |
|---|---|---|---|
| 8e44a7f5d2 | |||
| 5380ac0b36 | |||
| 9610423617 | |||
| 6ae8fd9ed4 | |||
| ba575d0ab8 | |||
| f72387c9cb | |||
| d940ede8ac | |||
| d7ac7885b6 | |||
| b6759bac6f | |||
| 5f39a7d9b1 | |||
| f77ca05d3f | |||
| 339ea52864 | |||
| d8bfe2a2ac | |||
| 77bf4419e0 |
@ -436,10 +436,16 @@ mod benchmarks {
|
||||
dummy_values.insert(identifier, dummy_value.clone());
|
||||
}
|
||||
|
||||
let identifier_size = network_curve.scalar_bytes_len();
|
||||
|
||||
let merkle_tree =
|
||||
NetworkCurve::build_merkle_tree(
|
||||
&dummy_values,
|
||||
|value: &Vec<u8>| Ok(value.clone()),
|
||||
identifier_size + dummy_value.len(),
|
||||
&dummy_values,
|
||||
|value, buffer| {
|
||||
buffer.extend_from_slice(value.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).expect("Merkle tree for verifying shares should be valid");
|
||||
|
||||
let merkle_root = merkle_tree.last().copied().unwrap();
|
||||
@ -748,10 +754,16 @@ mod benchmarks {
|
||||
dummy_values.insert(identifier, dummy_binding_factor.clone());
|
||||
}
|
||||
|
||||
let identifier_size = network_curve.scalar_bytes_len();
|
||||
|
||||
let merkle_tree =
|
||||
NetworkCurve::build_merkle_tree(
|
||||
&dummy_values,
|
||||
|value: &Vec<u8>| Ok(value.clone()),
|
||||
identifier_size + dummy_scalar.len(),
|
||||
&dummy_values,
|
||||
|value, buffer| {
|
||||
buffer.extend_from_slice(value.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).expect("Merkle tree for binding factor should be valid");
|
||||
|
||||
let merkle_root = merkle_tree.last().copied().unwrap();
|
||||
|
||||
@ -43,6 +43,7 @@ pub enum ExodusError {
|
||||
InvalidMerkleProof,
|
||||
InvalidIdentityElement,
|
||||
NoActiveAuthorities,
|
||||
TreeGenerationFailed,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
@ -88,6 +89,7 @@ impl core::fmt::Debug for ExodusError {
|
||||
ExodusError::InvalidMerkleProof => write!(fmt, "Invalid Merkle proof provided."),
|
||||
ExodusError::InvalidIdentityElement => write!(fmt, "Invalid identity element provided."),
|
||||
ExodusError::NoActiveAuthorities => write!(fmt, "No active authorities for signing EXODUS transactions."),
|
||||
ExodusError::TreeGenerationFailed => write!(fmt, "Tree generation failed because of inconsistent indexation."),
|
||||
ExodusError::Unknown => write!(fmt, "Unknown error."),
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@ use rand_chacha::rand_core::{CryptoRng, RngCore};
|
||||
|
||||
use ghost_traits::exodus::{
|
||||
DistributedKeyGeneration, IdentifierConverter, MerkleTreeBuilder,
|
||||
CiphersuiteSizes,
|
||||
};
|
||||
|
||||
use crate::{AuthIndex, ExodusError, NetworkCurve};
|
||||
@ -241,6 +242,8 @@ impl DistributedKeyGeneration<AuthIndex, ExodusError> for NetworkCurve {
|
||||
round2_packages_bytes: &Self::RoundPackages,
|
||||
) -> Self::Part3Result {
|
||||
with_ciphersuite!(self, |f| {
|
||||
type InnerGroup = <Ciphersuite as frost_core::Ciphersuite>::Group;
|
||||
|
||||
let round2_secret_package = f::keys::dkg::round2::SecretPackage::deserialize(round2_secret_package_bytes)
|
||||
.map_err(|_| ExodusError::DeserializationError)?;
|
||||
|
||||
@ -291,13 +294,24 @@ impl DistributedKeyGeneration<AuthIndex, ExodusError> for NetworkCurve {
|
||||
let key_package_bytes = key_package.serialize()
|
||||
.map_err(|_| ExodusError::SerializationError)?;
|
||||
|
||||
let identifier_size = self.scalar_bytes_len();
|
||||
let verifying_share_size = self.element_bytes_len();
|
||||
|
||||
let verifying_shares_merkle_tree =
|
||||
Self::build_merkle_tree(
|
||||
identifier_size + verifying_share_size,
|
||||
pubkey_package.verifying_shares(),
|
||||
|verifying_share| verifying_share.serialize()
|
||||
.map_err(|_| ExodusError::SerializationError)
|
||||
|verifying_share, buffer| {
|
||||
let serialized = <InnerGroup as frost_core::Group>::serialize(
|
||||
&verifying_share.to_element()
|
||||
).map_err(|_| ExodusError::SerializationError)?;
|
||||
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
)?;
|
||||
|
||||
// TODO: make it better
|
||||
let (_, merkle_proof) =
|
||||
Self::generate_merkle_proof_from_tree(
|
||||
pubkey_package.verifying_shares(),
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
use ghost_traits::exodus::{
|
||||
IdentifierConverter, MerkleTreeBuilder,
|
||||
CiphersuiteSizes, IdentifierConverter, MerkleTreeBuilder,
|
||||
FlexibleRoundOptimizedSchnorrThresholdSignature,
|
||||
};
|
||||
use sp_std::{
|
||||
@ -15,29 +15,6 @@ impl FlexibleRoundOptimizedSchnorrThresholdSignature<AuthIndex, ExodusError> for
|
||||
type Packages<'a> = BTreeMap<AuthIndex, &'a [u8]>;
|
||||
type NoncePackages<'a> = BTreeMap<AuthIndex, (&'a [u8], &'a [u8])>;
|
||||
|
||||
fn header_bytes_len(&self) -> usize { 5 }
|
||||
|
||||
fn signature_bytes_len(&self) -> usize {
|
||||
match self {
|
||||
NetworkCurve::Secp256k1 => 64,
|
||||
NetworkCurve::Ed25519 => 64,
|
||||
}
|
||||
}
|
||||
|
||||
fn element_bytes_len(&self) -> usize {
|
||||
match self {
|
||||
NetworkCurve::Secp256k1 => 33,
|
||||
NetworkCurve::Ed25519 => 32,
|
||||
}
|
||||
}
|
||||
|
||||
fn scalar_bytes_len(&self) -> usize {
|
||||
match self {
|
||||
NetworkCurve::Secp256k1 => 32,
|
||||
NetworkCurve::Ed25519 => 32,
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_signature_share(
|
||||
&self,
|
||||
index: AuthIndex,
|
||||
@ -343,11 +320,16 @@ impl FlexibleRoundOptimizedSchnorrThresholdSignature<AuthIndex, ExodusError> for
|
||||
return Err(ExodusError::InvalidParticipantId);
|
||||
}
|
||||
|
||||
let identifier_size = self.scalar_bytes_len();
|
||||
let binding_factor_size = self.scalar_bytes_len();
|
||||
|
||||
let binding_factor_tree = Self::build_merkle_tree(
|
||||
identifier_size + binding_factor_size,
|
||||
&binding_factors_list,
|
||||
|binding_factor| {
|
||||
|binding_factor, buffer| {
|
||||
let serialized = <InnerField as frost_core::Field>::serialize(binding_factor);
|
||||
Ok(serialized.as_ref().to_vec())
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
)?;
|
||||
|
||||
|
||||
@ -13,15 +13,16 @@ impl MerkleTreeBuilder<AuthIndex, ExodusError> for NetworkCurve {
|
||||
type Hash = <SubstrateBlake2Hasher as GhostHasher>::Hash;
|
||||
|
||||
fn build_merkle_tree<C, V, F>(
|
||||
size_hint: usize,
|
||||
values: &BTreeMap<Identifier<C>, V>,
|
||||
serialize_fn: F,
|
||||
update_preimage_buffer: F,
|
||||
) -> Result<Vec<Self::Hash>, ExodusError>
|
||||
where
|
||||
C: frost_core::Ciphersuite,
|
||||
<<C as Ciphersuite>::Group as Group>::Field: frost_core::Field,
|
||||
F: Fn(&V) -> Result<Vec<u8>, ExodusError>
|
||||
F: Fn(&V, &mut Vec<u8>) -> Result<(), ExodusError>
|
||||
{
|
||||
use ghost_helpers::merkle_tree::generate_tree;
|
||||
use ghost_helpers::merkle_tree::{generate_tree, MerkleTreeError};
|
||||
|
||||
type CField<C> = <<C as Ciphersuite>::Group as Group>::Field;
|
||||
|
||||
@ -34,25 +35,28 @@ impl MerkleTreeBuilder<AuthIndex, ExodusError> for NetworkCurve {
|
||||
})
|
||||
.ok_or(ExodusError::IncorrectNumberOfIdentifiers)?;
|
||||
|
||||
generate_tree::<SubstrateBlake2Hasher, _, _, _, _>(
|
||||
let maybe_tree = generate_tree::<SubstrateBlake2Hasher, _, _, _, _>(
|
||||
max_index,
|
||||
size_hint,
|
||||
values.iter(),
|
||||
|(identifier, value)| {
|
||||
|(identifier, value), buffer| {
|
||||
let id_scalar = identifier.to_scalar();
|
||||
let id_bytes = <CField<C> as frost_core::Field>::serialize(&id_scalar);
|
||||
|
||||
let index = Self::convert_identifier_to_index(id_bytes.as_ref())?;
|
||||
let value_bytes = serialize_fn(value).map_err(|_| ExodusError::SerializationError)?;
|
||||
|
||||
// NOTE: revisit
|
||||
// Is it possible to use [u8; CONSTANT] where constant is
|
||||
// purely dependant on provided generic.
|
||||
let mut preimage = Vec::<u8>::with_capacity(id_bytes.as_ref().len() + value_bytes.len());
|
||||
preimage.extend_from_slice(id_bytes.as_ref());
|
||||
preimage.extend_from_slice(value_bytes.as_ref());
|
||||
buffer.extend_from_slice(id_bytes.as_ref());
|
||||
update_preimage_buffer(value, buffer)?;
|
||||
|
||||
Ok((index as usize, preimage))
|
||||
})
|
||||
Ok(index as usize)
|
||||
});
|
||||
|
||||
match maybe_tree {
|
||||
Ok(tree) => Ok(tree),
|
||||
Err(MerkleTreeError::Generate(exodus_err)) => Err(exodus_err),
|
||||
Err(MerkleTreeError::InvalidIndex) => Err(ExodusError::TreeGenerationFailed),
|
||||
Err(MerkleTreeError::Empty) => Err(ExodusError::IncorrectNumberOfIdentifiers),
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_merkle_proof_from_tree<C, V, F>(
|
||||
@ -66,7 +70,7 @@ impl MerkleTreeBuilder<AuthIndex, ExodusError> for NetworkCurve {
|
||||
<<C as Ciphersuite>::Group as Group>::Field: frost_core::Field,
|
||||
F: Fn(&V) -> Result<Vec<u8>, ExodusError>
|
||||
{
|
||||
use ghost_helpers::merkle_tree::generate_proof;
|
||||
use ghost_helpers::merkle_tree::{generate_proof, MerkleTreeError};
|
||||
|
||||
type CField<C> = <<C as Ciphersuite>::Group as Group>::Field;
|
||||
|
||||
@ -75,7 +79,7 @@ impl MerkleTreeBuilder<AuthIndex, ExodusError> for NetworkCurve {
|
||||
.map_err(|_| ExodusError::InvalidParticipantId)?;
|
||||
|
||||
let value = values.get(&identifier).ok_or(ExodusError::InvalidParticipantId)?;
|
||||
let value_bytes = serialize_fn(&value).map_err(|_| ExodusError::SerializationError)?;
|
||||
let value_bytes = serialize_fn(&value)?;
|
||||
|
||||
let max_index = values.keys()
|
||||
.next_back()
|
||||
@ -86,11 +90,15 @@ impl MerkleTreeBuilder<AuthIndex, ExodusError> for NetworkCurve {
|
||||
})
|
||||
.ok_or(ExodusError::IncorrectNumberOfIdentifiers)?;
|
||||
|
||||
let proof = generate_proof::<SubstrateBlake2Hasher, _>(
|
||||
let proof = generate_proof::<SubstrateBlake2Hasher, _, _>(
|
||||
merkle_tree,
|
||||
max_index,
|
||||
authority_index,
|
||||
);
|
||||
).map_err(|err| match err {
|
||||
MerkleTreeError::Generate(exodus_err) => exodus_err,
|
||||
MerkleTreeError::InvalidIndex => ExodusError::TreeGenerationFailed,
|
||||
MerkleTreeError::Empty => ExodusError::IncorrectNumberOfIdentifiers,
|
||||
})?;
|
||||
|
||||
Ok((value_bytes, proof))
|
||||
}
|
||||
|
||||
@ -72,3 +72,6 @@ mod ecdh;
|
||||
|
||||
#[macro_use]
|
||||
mod frost;
|
||||
|
||||
#[macro_use]
|
||||
mod sizes;
|
||||
|
||||
29
pallets/exodus/src/impls/sizes.rs
Normal file
29
pallets/exodus/src/impls/sizes.rs
Normal file
@ -0,0 +1,29 @@
|
||||
use ghost_helpers::networks::NetworkCurve;
|
||||
use ghost_traits::exodus::CiphersuiteSizes;
|
||||
|
||||
use crate::{AuthIndex, ExodusError};
|
||||
|
||||
impl CiphersuiteSizes<AuthIndex, ExodusError> for NetworkCurve {
|
||||
fn header_bytes_len(&self) -> usize { 5 }
|
||||
|
||||
fn signature_bytes_len(&self) -> usize {
|
||||
match self {
|
||||
NetworkCurve::Secp256k1 => 64,
|
||||
NetworkCurve::Ed25519 => 64,
|
||||
}
|
||||
}
|
||||
|
||||
fn element_bytes_len(&self) -> usize {
|
||||
match self {
|
||||
NetworkCurve::Secp256k1 => 33,
|
||||
NetworkCurve::Ed25519 => 32,
|
||||
}
|
||||
}
|
||||
|
||||
fn scalar_bytes_len(&self) -> usize {
|
||||
match self {
|
||||
NetworkCurve::Secp256k1 => 32,
|
||||
NetworkCurve::Ed25519 => 32,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -48,6 +48,7 @@ use ghost_traits::{
|
||||
exodus::{
|
||||
MerkleTreeBuilder, DistributedKeyGeneration, EllipticCurveDiffieHellman,
|
||||
FlexibleRoundOptimizedSchnorrThresholdSignature, EvmGovernanceRegistrar,
|
||||
CiphersuiteSizes,
|
||||
},
|
||||
networks::{
|
||||
NetworkDataBasicHandler, NetworkDataInspectHandler,
|
||||
|
||||
@ -1532,9 +1532,17 @@ fn test_merkle_tree_success_power_of_two_for_shares() {
|
||||
let indices = (1..=32).collect::<Vec<AuthIndex>>();
|
||||
let shares = generate_mock_secp256k1_shares(&indices);
|
||||
|
||||
let identifier_len = network_curve.scalar_bytes_len();
|
||||
let secret_share_len = network_curve.element_bytes_len();
|
||||
|
||||
let tree = NetworkCurve::build_merkle_tree::<Secp256K1Sha256TR, _, _>(
|
||||
identifier_len + secret_share_len,
|
||||
&shares,
|
||||
|share| share.serialize().map_err(|_| ExodusError::SerializationError),
|
||||
|share, buffer| {
|
||||
let serialized = share.serialize().map_err(|_| ExodusError::SerializationError)?;
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
let root = *tree.last().unwrap();
|
||||
@ -1569,11 +1577,16 @@ fn test_merkle_tree_success_power_of_two_for_scalar() {
|
||||
let indices = (1..=32).collect::<Vec<AuthIndex>>();
|
||||
let scalars = generate_mock_secp256k1_scalars(&indices);
|
||||
|
||||
let identifier_len = network_curve.scalar_bytes_len();
|
||||
let secret_scalar_len = network_curve.scalar_bytes_len();
|
||||
|
||||
let tree = NetworkCurve::build_merkle_tree::<Secp256K1Sha256TR, _, _>(
|
||||
identifier_len + secret_scalar_len,
|
||||
&scalars,
|
||||
|scalar| {
|
||||
|scalar, buffer| {
|
||||
let serialized = <Secp256K1ScalarField as Field>::serialize(scalar);
|
||||
Ok(serialized.as_ref().to_vec())
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
@ -1584,7 +1597,7 @@ fn test_merkle_tree_success_power_of_two_for_scalar() {
|
||||
&identifier.serialize(),
|
||||
).unwrap();
|
||||
|
||||
let (shares_bytes, proof) =
|
||||
let (scalar_bytes, proof) =
|
||||
NetworkCurve::generate_merkle_proof_from_tree::<Secp256K1Sha256TR, _, _>(
|
||||
&scalars,
|
||||
&tree,
|
||||
@ -1596,7 +1609,7 @@ fn test_merkle_tree_success_power_of_two_for_scalar() {
|
||||
).unwrap();
|
||||
|
||||
let result = network_curve.verify_merkle_proof(
|
||||
&shares_bytes,
|
||||
&scalar_bytes,
|
||||
&proof,
|
||||
root,
|
||||
auth_index,
|
||||
@ -1618,9 +1631,17 @@ fn test_random_sparse_combinations_stress_for_shares() {
|
||||
let indices: Vec<AuthIndex> = unique_indices.into_iter().collect();
|
||||
let shares = generate_mock_secp256k1_shares(&indices);
|
||||
|
||||
let identifier_len = network_curve.scalar_bytes_len();
|
||||
let secret_share_len = network_curve.element_bytes_len();
|
||||
|
||||
let tree = NetworkCurve::build_merkle_tree::<Secp256K1Sha256TR, _, _>(
|
||||
identifier_len + secret_share_len,
|
||||
&shares,
|
||||
|share| share.serialize().map_err(|_| ExodusError::SerializationError),
|
||||
|share, buffer| {
|
||||
let serialized = share.serialize().map_err(|_| ExodusError::SerializationError)?;
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
let root = *tree.last().unwrap();
|
||||
@ -1656,11 +1677,16 @@ fn test_random_sparse_combinations_stress_for_scalars() {
|
||||
let indices: Vec<AuthIndex> = unique_indices.into_iter().collect();
|
||||
let scalars = generate_mock_secp256k1_scalars(&indices);
|
||||
|
||||
let identifier_len = network_curve.scalar_bytes_len();
|
||||
let secret_scalar_len = network_curve.scalar_bytes_len();
|
||||
|
||||
let tree = NetworkCurve::build_merkle_tree::<Secp256K1Sha256TR, _, _>(
|
||||
identifier_len + secret_scalar_len,
|
||||
&scalars,
|
||||
|scalar| {
|
||||
|scalar, buffer| {
|
||||
let serialized = <Secp256K1ScalarField as Field>::serialize(scalar);
|
||||
Ok(serialized.as_ref().to_vec())
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
@ -1694,9 +1720,17 @@ fn test_participants_with_high_index_gap_for_shares() {
|
||||
let indices = vec![1, 1023];
|
||||
let shares = generate_mock_secp256k1_shares(&indices);
|
||||
|
||||
let identifier_len = network_curve.scalar_bytes_len();
|
||||
let secret_share_len = network_curve.element_bytes_len();
|
||||
|
||||
let tree = NetworkCurve::build_merkle_tree::<Secp256K1Sha256TR, _, _>(
|
||||
identifier_len + secret_share_len,
|
||||
&shares,
|
||||
|share| share.serialize().map_err(|_| ExodusError::SerializationError),
|
||||
|share, buffer| {
|
||||
let serialized = share.serialize().map_err(|_| ExodusError::SerializationError)?;
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
let root = *tree.last().unwrap();
|
||||
@ -1726,11 +1760,16 @@ fn test_participants_with_high_index_gap_for_scalars() {
|
||||
let indices = vec![1, 1023];
|
||||
let scalars = generate_mock_secp256k1_scalars(&indices);
|
||||
|
||||
let identifier_len = network_curve.scalar_bytes_len();
|
||||
let secret_scalar_len = network_curve.scalar_bytes_len();
|
||||
|
||||
let tree = NetworkCurve::build_merkle_tree::<Secp256K1Sha256TR, _, _>(
|
||||
identifier_len + secret_scalar_len,
|
||||
&scalars,
|
||||
|scalar| {
|
||||
|scalar, buffer| {
|
||||
let serialized = <Secp256K1ScalarField as Field>::serialize(scalar);
|
||||
Ok(serialized.as_ref().to_vec())
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
@ -1764,9 +1803,17 @@ fn test_regression_consecutive_vs_position_for_shares() {
|
||||
let custom_indices = vec![2, 3];
|
||||
let shares = generate_mock_secp256k1_shares(&custom_indices);
|
||||
|
||||
let identifier_len = network_curve.scalar_bytes_len();
|
||||
let secret_share_len = network_curve.element_bytes_len();
|
||||
|
||||
let tree = NetworkCurve::build_merkle_tree::<Secp256K1Sha256TR, _, _>(
|
||||
identifier_len + secret_share_len,
|
||||
&shares,
|
||||
|scalar| scalar.serialize().map_err(|_| ExodusError::SerializationError),
|
||||
|share, buffer| {
|
||||
let serialized = share.serialize().map_err(|_| ExodusError::SerializationError)?;
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
let root = *tree.last().unwrap();
|
||||
@ -1789,11 +1836,16 @@ fn test_regression_consecutive_vs_position_for_scalars() {
|
||||
let custom_indices = vec![2, 3];
|
||||
let scalars = generate_mock_secp256k1_scalars(&custom_indices);
|
||||
|
||||
let identifier_len = network_curve.scalar_bytes_len();
|
||||
let secret_scalar_len = network_curve.scalar_bytes_len();
|
||||
|
||||
let tree = NetworkCurve::build_merkle_tree::<Secp256K1Sha256TR, _, _>(
|
||||
identifier_len + secret_scalar_len,
|
||||
&scalars,
|
||||
|scalar| {
|
||||
|scalar, buffer| {
|
||||
let serialized = <Secp256K1ScalarField as Field>::serialize(scalar);
|
||||
Ok(serialized.as_ref().to_vec())
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
@ -1820,9 +1872,17 @@ fn test_attack_with_unknown_authority_index_for_shares() {
|
||||
let custom_indices = vec![1, 2, 3];
|
||||
let shares = generate_mock_secp256k1_shares(&custom_indices);
|
||||
|
||||
let identifier_len = network_curve.scalar_bytes_len();
|
||||
let secret_share_len = network_curve.element_bytes_len();
|
||||
|
||||
let tree = NetworkCurve::build_merkle_tree::<Secp256K1Sha256TR, _, _>(
|
||||
identifier_len + secret_share_len,
|
||||
&shares,
|
||||
|scalar| scalar.serialize().map_err(|_| ExodusError::SerializationError),
|
||||
|share, buffer| {
|
||||
let serialized = share.serialize().map_err(|_| ExodusError::SerializationError)?;
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
let root = *tree.last().unwrap();
|
||||
@ -1845,11 +1905,16 @@ fn test_attack_with_unknown_authority_index_for_scalars() {
|
||||
let custom_indices = vec![1, 2, 3];
|
||||
let scalars = generate_mock_secp256k1_scalars(&custom_indices);
|
||||
|
||||
let identifier_len = network_curve.scalar_bytes_len();
|
||||
let secret_scalar_len = network_curve.scalar_bytes_len();
|
||||
|
||||
let tree = NetworkCurve::build_merkle_tree::<Secp256K1Sha256TR, _, _>(
|
||||
identifier_len + secret_scalar_len,
|
||||
&scalars,
|
||||
|scalar| {
|
||||
|scalar, buffer| {
|
||||
let serialized = <Secp256K1ScalarField as Field>::serialize(scalar);
|
||||
Ok(serialized.as_ref().to_vec())
|
||||
buffer.extend_from_slice(serialized.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
|
||||
@ -79,14 +79,21 @@ fn claim_happy_path() {
|
||||
let users = vec![user_1.clone(), user_2.clone(), user_3.clone()];
|
||||
let max_index = 2u8;
|
||||
|
||||
let tmp_package_probe = ClaimPackage::<Test> {
|
||||
shares: user_1.allowed_shares,
|
||||
merkle_proof: Default::default(),
|
||||
token_id: user_1.token_id,
|
||||
index: 0u32,
|
||||
};
|
||||
let size_hint = tmp_package_probe.get_preimage(&user_1.evm_address, network_id).as_ref().len();
|
||||
|
||||
let raw_values_complex = vec![(0u8, &user_1), (1u8, &user_2), (2u8, &user_3)];
|
||||
let merkle_tree = generate_tree::<SubstrateKeccakHasher, u8, _, _, _>(
|
||||
let merkle_tree = generate_tree::<SubstrateKeccakHasher, u8, _, _, ()>(
|
||||
max_index,
|
||||
size_hint,
|
||||
raw_values_complex,
|
||||
|
||||
|item: (u8, &NewTestUser)| -> Result<(usize, Vec<u8>), ()> {
|
||||
let (index, u) = item;
|
||||
|
||||
|(index, u), buffer| {
|
||||
let tmp_package = ClaimPackage::<Test> {
|
||||
shares: u.allowed_shares,
|
||||
merkle_proof: Default::default(),
|
||||
@ -94,9 +101,12 @@ fn claim_happy_path() {
|
||||
index: index as u32
|
||||
};
|
||||
|
||||
Ok((index as usize, tmp_package.get_preimage(&u.evm_address, network_id).to_vec()))
|
||||
let preimage_bytes = tmp_package.get_preimage(&u.evm_address, network_id);
|
||||
buffer.extend_from_slice(preimage_bytes.as_ref());
|
||||
|
||||
Ok(index as usize)
|
||||
}
|
||||
).unwrap();
|
||||
).ok().unwrap();
|
||||
|
||||
let merkle_root = *merkle_tree.last().unwrap();
|
||||
|
||||
@ -116,7 +126,9 @@ fn claim_happy_path() {
|
||||
activated_shares: 0,
|
||||
});
|
||||
|
||||
let proof = generate_proof::<SubstrateKeccakHasher, u8>(&merkle_tree, max_index, slot_index as u8);
|
||||
let proof = generate_proof::<SubstrateKeccakHasher, u8, ()>(&merkle_tree, max_index, slot_index as u8)
|
||||
.ok()
|
||||
.unwrap();
|
||||
|
||||
let claim_package = ClaimPackage::<Test> {
|
||||
shares: current_user.allowed_shares,
|
||||
@ -205,21 +217,33 @@ fn partial_claims_happy_path() {
|
||||
let max_index = 0u8;
|
||||
let raw_values_complex = vec![(0u8, ¤t_user)];
|
||||
|
||||
let merkle_tree = generate_tree::<SubstrateKeccakHasher, u8, _, _, _>(
|
||||
let tmp_package_probe = ClaimPackage::<Test> {
|
||||
shares: current_user.allowed_shares,
|
||||
merkle_proof: Default::default(),
|
||||
token_id: current_user.token_id,
|
||||
index: 0u32,
|
||||
};
|
||||
let size_hint = tmp_package_probe.get_preimage(¤t_user.evm_address, network_id).as_ref().len();
|
||||
|
||||
let merkle_tree = generate_tree::<SubstrateKeccakHasher, u8, _, _, ()>(
|
||||
max_index,
|
||||
size_hint,
|
||||
raw_values_complex,
|
||||
|
||||
|item: (u8, &NewTestUser)| -> Result<(usize, Vec<u8>), ()> {
|
||||
let (index, u) = item;
|
||||
|(index, u), buffer| {
|
||||
let tmp_package = ClaimPackage::<Test> {
|
||||
shares: u.allowed_shares,
|
||||
merkle_proof: Default::default(),
|
||||
token_id: u.token_id,
|
||||
index: index as u32
|
||||
};
|
||||
Ok((index as usize, tmp_package.get_preimage(&u.evm_address, network_id).to_vec()))
|
||||
|
||||
let preimage_bytes = tmp_package.get_preimage(&u.evm_address, network_id);
|
||||
buffer.extend_from_slice(preimage_bytes.as_ref());
|
||||
|
||||
Ok(index as usize)
|
||||
}
|
||||
).unwrap();
|
||||
).ok().unwrap();
|
||||
|
||||
let total_shares = 1_000_000;
|
||||
let merkle_root = *merkle_tree.last().unwrap();
|
||||
@ -240,7 +264,10 @@ fn partial_claims_happy_path() {
|
||||
setup_governor(&substrate_account_b);
|
||||
setup_governor(&substrate_account_c);
|
||||
|
||||
let proof = generate_proof::<SubstrateKeccakHasher, u8>(&merkle_tree, max_index, 0u8);
|
||||
let proof = generate_proof::<SubstrateKeccakHasher, u8, ()>(&merkle_tree, max_index, 0u8)
|
||||
.ok()
|
||||
.unwrap();
|
||||
|
||||
let claim_package = ClaimPackage {
|
||||
shares: current_user.allowed_shares,
|
||||
merkle_proof: BoundedVec::try_from(proof).unwrap(),
|
||||
|
||||
@ -1,19 +1,5 @@
|
||||
use ghost_traits::hashing::GhostHasher;
|
||||
|
||||
fn combine_values<H, V>(left: V, right: V) -> H::Hash
|
||||
where
|
||||
H: GhostHasher,
|
||||
V: AsRef<[u8]>,
|
||||
{
|
||||
let hash_len = H::hash_len();
|
||||
let mut combined = sp_std::vec![0u8; hash_len * 2];
|
||||
|
||||
combined[..hash_len].copy_from_slice(left.as_ref());
|
||||
combined[hash_len..].copy_from_slice(right.as_ref());
|
||||
|
||||
H::hash(&combined)
|
||||
}
|
||||
|
||||
pub fn cumulative_hash<H, S>(raw_values: S) -> H::Hash
|
||||
where
|
||||
H: GhostHasher,
|
||||
@ -24,7 +10,7 @@ where
|
||||
.into_iter()
|
||||
.fold(H::empty(), |acc_hash, raw_value| {
|
||||
let hashed_value = H::hash(raw_value.as_ref());
|
||||
combine_values::<H, _>(acc_hash, hashed_value)
|
||||
H::combine_hashes(acc_hash, hashed_value)
|
||||
})
|
||||
}
|
||||
|
||||
@ -47,7 +33,7 @@ where
|
||||
|
||||
iter.fold(current_hash, |acc_hash, raw_value| {
|
||||
let next_hash = H::from_slice(raw_value.as_ref());
|
||||
combine_values::<H, _>(acc_hash, next_hash)
|
||||
H::combine_hashes(acc_hash, next_hash)
|
||||
})
|
||||
}
|
||||
|
||||
@ -94,45 +80,14 @@ where
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sp_core::H256;
|
||||
use sp_io::hashing::{blake2_256, sha2_256};
|
||||
use sp_std::vec::Vec;
|
||||
|
||||
pub struct TestBlake2Hasher;
|
||||
impl GhostHasher for TestBlake2Hasher {
|
||||
type Hash = H256;
|
||||
type HashBytes = [u8; 32];
|
||||
|
||||
fn hash(data: &[u8]) -> Self::Hash {
|
||||
H256::from(blake2_256(data))
|
||||
}
|
||||
fn empty() -> Self::Hash {
|
||||
H256::zero()
|
||||
}
|
||||
fn hash_len() -> usize {
|
||||
H256::len_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TestSha2Hasher;
|
||||
impl GhostHasher for TestSha2Hasher {
|
||||
type Hash = H256;
|
||||
type HashBytes = [u8; 32];
|
||||
fn hash(data: &[u8]) -> Self::Hash {
|
||||
let first_pass: [u8; 32] = sha2_256(data);
|
||||
let second_pass: [u8; 32] = sha2_256(&first_pass);
|
||||
|
||||
H256::from(second_pass)
|
||||
}
|
||||
fn hash_len() -> usize {
|
||||
H256::len_bytes()
|
||||
}
|
||||
fn empty() -> Self::Hash {
|
||||
H256::zero()
|
||||
}
|
||||
}
|
||||
use crate::{
|
||||
SubstrateBlake2Hasher, SubstrateKeccakHasher, UtxoSha2Hasher,
|
||||
};
|
||||
|
||||
fn mock_sequential_hash(header: &[u8; 80]) -> H256 {
|
||||
sequential_hash::<TestSha2Hasher, _>(core::iter::once(header))
|
||||
sequential_hash::<UtxoSha2Hasher, _>(core::iter::once(header))
|
||||
}
|
||||
|
||||
fn create_header(prev_hash: [u8; 32]) -> [u8; 80] {
|
||||
@ -141,89 +96,101 @@ mod tests {
|
||||
header
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_empty_values() {
|
||||
let empty_list: Vec<Vec<u8>> = sp_std::vec![];
|
||||
let result = cumulative_hash::<TestBlake2Hasher, _>(empty_list);
|
||||
assert_eq!(H256::zero(), result);
|
||||
macro_rules! run_hasher_tests {
|
||||
($hasher_type:ty, $mod_name:ident) => {
|
||||
mod $mod_name {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_generate_empty_values() {
|
||||
let empty_list: Vec<Vec<u8>> = sp_std::vec![];
|
||||
let result = cumulative_hash::<$hasher_type, _>(empty_list);
|
||||
assert_eq!(H256::zero(), result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cumulative_hash_determinism_and_avalanche() {
|
||||
let dataset_1 = sp_std::vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
|
||||
let dataset_2 = sp_std::vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
|
||||
let dataset_3 = sp_std::vec![vec![9, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
|
||||
|
||||
let hash_1 = cumulative_hash::<$hasher_type, _>(dataset_1);
|
||||
let hash_2 = cumulative_hash::<$hasher_type, _>(dataset_2);
|
||||
let hash_3 = cumulative_hash::<$hasher_type, _>(dataset_3);
|
||||
|
||||
assert_eq!(hash_1, hash_2);
|
||||
assert_ne!(hash_1, hash_3);
|
||||
assert_ne!(hash_2, hash_3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cumulative_hash_order_sensitive() {
|
||||
let dataset_forward = sp_std::vec![sp_std::vec![1, 1, 1], sp_std::vec![2, 2, 2]];
|
||||
let dataset_reversed = sp_std::vec![sp_std::vec![2, 2, 2], sp_std::vec![1, 1, 1]];
|
||||
|
||||
let hash_forward = cumulative_hash::<$hasher_type, _>(dataset_forward);
|
||||
let hash_reversed = cumulative_hash::<$hasher_type, _>(dataset_reversed);
|
||||
|
||||
assert_ne!(hash_forward, hash_reversed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cumulative_hash_with_slices() {
|
||||
let slice_data: &[&[u8]] = &[&[1, 2, 3], &[4, 5, 6]];
|
||||
let hash_from_slice = cumulative_hash::<$hasher_type, _>(slice_data.iter());
|
||||
assert_ne!(hash_from_slice, H256::zero());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequential_hash_empty() {
|
||||
let empty_list: Vec<Vec<u8>> = sp_std::vec![];
|
||||
let result = sequential_hash::<$hasher_type, _>(empty_list);
|
||||
assert_eq!(H256::zero(), result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequential_hash_single_element() {
|
||||
let single_item = sp_std::vec![sp_std::vec![1, 2, 3]];
|
||||
let result = sequential_hash::<$hasher_type, _>(single_item);
|
||||
let expected = <$hasher_type>::hash(&[1, 2, 3]);
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequential_hash_determinism_and_order() {
|
||||
let data_1 = sp_std::vec![sp_std::vec![1], sp_std::vec![2], sp_std::vec![3]];
|
||||
let data_2 = sp_std::vec![sp_std::vec![1], sp_std::vec![2], sp_std::vec![3]];
|
||||
let data_reversed = sp_std::vec![sp_std::vec![3], sp_std::vec![2], sp_std::vec![1]];
|
||||
|
||||
let hash_1 = sequential_hash::<$hasher_type, _>(data_1);
|
||||
let hash_2 = sequential_hash::<$hasher_type, _>(data_2);
|
||||
let hash_reversed = sequential_hash::<$hasher_type, _>(data_reversed);
|
||||
|
||||
assert_eq!(hash_1, hash_2);
|
||||
assert_ne!(hash_1, hash_reversed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequential_vs_cumulative_hash() {
|
||||
let dataset = sp_std::vec![sp_std::vec![1, 2, 3], sp_std::vec![4, 5, 6]];
|
||||
let seq_hash = sequential_hash::<$hasher_type, _>(dataset.clone());
|
||||
let cum_hash = cumulative_hash::<$hasher_type, _>(dataset);
|
||||
assert_ne!(seq_hash, cum_hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequential_hash_with_slices() {
|
||||
let slice_data: &[&[u8]] = &[&[10, 20], &[30, 40]];
|
||||
let result = sequential_hash::<$hasher_type, _>(slice_data.iter());
|
||||
assert_ne!(result, H256::zero());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cumulative_hash_determinism_and_avalanche() {
|
||||
let dataset_1 = sp_std::vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
|
||||
let dataset_2 = sp_std::vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
|
||||
let dataset_3 = sp_std::vec![vec![9, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
|
||||
|
||||
let hash_1 = cumulative_hash::<TestBlake2Hasher, _>(dataset_1);
|
||||
let hash_2 = cumulative_hash::<TestBlake2Hasher, _>(dataset_2);
|
||||
let hash_3 = cumulative_hash::<TestBlake2Hasher, _>(dataset_3);
|
||||
|
||||
assert_eq!(hash_1, hash_2);
|
||||
assert_ne!(hash_1, hash_3);
|
||||
assert_ne!(hash_2, hash_3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cumulative_hash_order_sensitive() {
|
||||
let dataset_forward = sp_std::vec![sp_std::vec![1, 1, 1], sp_std::vec![2, 2, 2]];
|
||||
let dataset_reversed = sp_std::vec![sp_std::vec![2, 2, 2], sp_std::vec![1, 1, 1]];
|
||||
|
||||
let hash_forward = cumulative_hash::<TestBlake2Hasher, _>(dataset_forward);
|
||||
let hash_reversed = cumulative_hash::<TestBlake2Hasher, _>(dataset_reversed);
|
||||
|
||||
assert_ne!(hash_forward, hash_reversed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cumulative_hash_with_slices() {
|
||||
let slice_data: &[&[u8]] = &[&[1, 2, 3], &[4, 5, 6]];
|
||||
let hash_from_slice = cumulative_hash::<TestBlake2Hasher, _>(slice_data.iter());
|
||||
assert_ne!(hash_from_slice, H256::zero());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequential_hash_empty() {
|
||||
let empty_list: Vec<Vec<u8>> = sp_std::vec![];
|
||||
let result = sequential_hash::<TestBlake2Hasher, _>(empty_list);
|
||||
assert_eq!(H256::zero(), result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequential_hash_single_element() {
|
||||
let single_item = sp_std::vec![sp_std::vec![1, 2, 3]];
|
||||
let result = sequential_hash::<TestBlake2Hasher, _>(single_item);
|
||||
let expected = TestBlake2Hasher::hash(&[1, 2, 3]);
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequential_hash_determinism_and_order() {
|
||||
let data_1 = sp_std::vec![sp_std::vec![1], sp_std::vec![2], sp_std::vec![3]];
|
||||
let data_2 = sp_std::vec![sp_std::vec![1], sp_std::vec![2], sp_std::vec![3]];
|
||||
let data_reversed = sp_std::vec![sp_std::vec![3], sp_std::vec![2], sp_std::vec![1]];
|
||||
|
||||
let hash_1 = sequential_hash::<TestBlake2Hasher, _>(data_1);
|
||||
let hash_2 = sequential_hash::<TestBlake2Hasher, _>(data_2);
|
||||
let hash_reversed = sequential_hash::<TestBlake2Hasher, _>(data_reversed);
|
||||
|
||||
assert_eq!(hash_1, hash_2);
|
||||
assert_ne!(hash_1, hash_reversed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequential_vs_cumulative_hash() {
|
||||
let dataset = sp_std::vec![sp_std::vec![1, 2, 3], sp_std::vec![4, 5, 6]];
|
||||
let seq_hash = sequential_hash::<TestBlake2Hasher, _>(dataset.clone());
|
||||
let cum_hash = cumulative_hash::<TestBlake2Hasher, _>(dataset);
|
||||
assert_ne!(seq_hash, cum_hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequential_hash_with_slices() {
|
||||
let slice_data: &[&[u8]] = &[&[10, 20], &[30, 40]];
|
||||
let result = sequential_hash::<TestBlake2Hasher, _>(slice_data.iter());
|
||||
assert_ne!(result, H256::zero());
|
||||
}
|
||||
run_hasher_tests!(SubstrateBlake2Hasher, blake2_hashing_tests);
|
||||
run_hasher_tests!(SubstrateKeccakHasher, keccak_hashing_tests);
|
||||
run_hasher_tests!(UtxoSha2Hasher, sha2_hashing_tests);
|
||||
|
||||
#[test]
|
||||
fn test_verify_in_current_block_with_empty_ancestry() {
|
||||
@ -234,7 +201,7 @@ mod tests {
|
||||
trusted_bytes.reverse();
|
||||
let trusted_top_block_hash = H256::from(trusted_bytes);
|
||||
|
||||
let result = verify_hash_ancestry::<TestSha2Hasher, &[[u8; 80]]>(
|
||||
let result = verify_hash_ancestry::<UtxoSha2Hasher, &[[u8; 80]]>(
|
||||
&tx_header,
|
||||
&[],
|
||||
trusted_top_block_hash,
|
||||
@ -256,7 +223,7 @@ mod tests {
|
||||
let trusted_top_block_hash = H256::from(trusted_bytes);
|
||||
|
||||
let ancestry = [header_101];
|
||||
let result = verify_hash_ancestry::<TestSha2Hasher, &[[u8; 80]]>(
|
||||
let result = verify_hash_ancestry::<UtxoSha2Hasher, &[[u8; 80]]>(
|
||||
&tx_header_100,
|
||||
&ancestry,
|
||||
trusted_top_block_hash,
|
||||
@ -284,7 +251,7 @@ mod tests {
|
||||
let trusted_top_block_hash = H256::from(trusted_bytes);
|
||||
|
||||
let ancestry = [header_101, header_102, header_103];
|
||||
let result = verify_hash_ancestry::<TestSha2Hasher, &[[u8; 80]]>(
|
||||
let result = verify_hash_ancestry::<UtxoSha2Hasher, &[[u8; 80]]>(
|
||||
&header_100,
|
||||
&ancestry,
|
||||
trusted_top_block_hash,
|
||||
@ -305,7 +272,7 @@ mod tests {
|
||||
let trusted_top_block_hash = H256::from(trusted_bytes);
|
||||
|
||||
let ancestry = [broken_header_101];
|
||||
let result = verify_hash_ancestry::<TestSha2Hasher, &[[u8; 80]]>(
|
||||
let result = verify_hash_ancestry::<UtxoSha2Hasher, &[[u8; 80]]>(
|
||||
&header_100,
|
||||
&ancestry,
|
||||
trusted_top_block_hash,
|
||||
|
||||
@ -49,53 +49,73 @@ where
|
||||
value - f
|
||||
}
|
||||
|
||||
pub struct SubstrateBlake2Hasher;
|
||||
impl GhostHasher for SubstrateBlake2Hasher {
|
||||
type Hash = H256;
|
||||
type HashBytes = [u8; 32];
|
||||
fn hash(data: &[u8]) -> Self::Hash {
|
||||
H256::from(blake2_256(data))
|
||||
}
|
||||
fn hash_len() -> usize {
|
||||
H256::len_bytes()
|
||||
}
|
||||
fn empty() -> Self::Hash {
|
||||
H256::zero()
|
||||
}
|
||||
macro_rules! impl_ghost_hasher {
|
||||
(
|
||||
struct $name:ident;
|
||||
hash_type: $hash_type:ty;
|
||||
hash_bytes_len: $hash_bytes_len:expr;
|
||||
fn hash($data:ident) -> $hash_res:expr
|
||||
) => {
|
||||
pub struct $name;
|
||||
|
||||
impl GhostHasher for $name {
|
||||
type Hash = $hash_type;
|
||||
type HashBytes = [u8; $hash_bytes_len];
|
||||
|
||||
fn hash($data: &[u8]) -> Self::Hash {
|
||||
$hash_res
|
||||
}
|
||||
|
||||
fn hash_len() -> usize {
|
||||
$hash_bytes_len
|
||||
}
|
||||
|
||||
fn empty() -> Self::Hash {
|
||||
<$hash_type>::zero()
|
||||
}
|
||||
|
||||
fn combine_hashes(left: Self::Hash, right: Self::Hash) -> Self::Hash {
|
||||
let mut combined = [0u8; $hash_bytes_len * 2];
|
||||
combined[..$hash_bytes_len].copy_from_slice(left.as_ref());
|
||||
combined[$hash_bytes_len..].copy_from_slice(right.as_ref());
|
||||
Self::hash(&combined)
|
||||
}
|
||||
|
||||
fn combine_hashes_prefixed(p: u8, l: Self::Hash, r: Self::Hash) -> Self::Hash {
|
||||
let mut combined = [p; $hash_bytes_len * 2 + 1];
|
||||
combined[1..1 + $hash_bytes_len].copy_from_slice(l.as_ref());
|
||||
combined[1 + $hash_bytes_len..].copy_from_slice(r.as_ref());
|
||||
Self::hash(&combined)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub struct SubstrateKeccakHasher;
|
||||
impl GhostHasher for SubstrateKeccakHasher {
|
||||
type Hash = H256;
|
||||
type HashBytes = [u8; 32];
|
||||
fn hash(data: &[u8]) -> Self::Hash {
|
||||
H256::from(keccak_256(data))
|
||||
}
|
||||
fn hash_len() -> usize {
|
||||
H256::len_bytes()
|
||||
}
|
||||
fn empty() -> Self::Hash {
|
||||
H256::zero()
|
||||
}
|
||||
}
|
||||
impl_ghost_hasher!(
|
||||
struct SubstrateBlake2Hasher;
|
||||
hash_type: H256;
|
||||
hash_bytes_len: 32;
|
||||
fn hash(data) -> H256::from(blake2_256(data))
|
||||
);
|
||||
|
||||
pub struct UtxoSha2Hasher;
|
||||
impl GhostHasher for UtxoSha2Hasher {
|
||||
type Hash = H256;
|
||||
type HashBytes = [u8; 32];
|
||||
fn hash(data: &[u8]) -> Self::Hash {
|
||||
impl_ghost_hasher!(
|
||||
struct SubstrateKeccakHasher;
|
||||
hash_type: H256;
|
||||
hash_bytes_len: 32;
|
||||
fn hash(data) -> H256::from(keccak_256(data))
|
||||
);
|
||||
|
||||
impl_ghost_hasher!(
|
||||
struct UtxoSha2Hasher;
|
||||
hash_type: H256;
|
||||
hash_bytes_len: 32;
|
||||
fn hash(data) -> {
|
||||
let first_pass: [u8; 32] = sha2_256(data);
|
||||
let second_pass: [u8; 32] = sha2_256(&first_pass);
|
||||
|
||||
H256::from(second_pass)
|
||||
}
|
||||
fn hash_len() -> usize {
|
||||
H256::len_bytes()
|
||||
}
|
||||
fn empty() -> Self::Hash {
|
||||
H256::zero()
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -878,23 +878,25 @@ impl<T: Config> NetworkDataMutateHandler<NetworkData, BalanceOf<T>> for Pallet<T
|
||||
.map(|network| network.incoming_share)
|
||||
.ok_or(())?;
|
||||
|
||||
GatekeeperAmounts::<T>::try_mutate(network_id, |gatekeeper_amount| -> Result<(), ()> {
|
||||
*gatekeeper_amount = gatekeeper_amount.checked_add(&amount).ok_or(())?;
|
||||
Ok(())
|
||||
})?;
|
||||
let increased_gatekeeper_amount = GatekeeperAmounts::<T>::get(network_id)
|
||||
.checked_add(&amount)
|
||||
.ok_or(())?;
|
||||
|
||||
let curve_share = Perbill::from_parts(incoming_share).mul_ceil(amount);
|
||||
let final_amount = amount.saturating_sub(curve_share);
|
||||
|
||||
NetworkImbalance::<T>::try_mutate(|imbalance_state| -> Result<(), ()> {
|
||||
imbalance_state.incoming = imbalance_state.incoming
|
||||
.checked_add(&final_amount)
|
||||
.ok_or(())?;
|
||||
imbalance_state.curve_share = imbalance_state.curve_share
|
||||
.checked_add(&curve_share)
|
||||
.ok_or(())?;
|
||||
Ok(())
|
||||
})?;
|
||||
let mut imbalance_state = NetworkImbalance::<T>::get();
|
||||
|
||||
imbalance_state.incoming = imbalance_state.incoming
|
||||
.checked_add(&final_amount)
|
||||
.ok_or(())?;
|
||||
|
||||
imbalance_state.curve_share = imbalance_state.curve_share
|
||||
.checked_add(&curve_share)
|
||||
.ok_or(())?;
|
||||
|
||||
GatekeeperAmounts::<T>::insert(network_id, increased_gatekeeper_amount);
|
||||
NetworkImbalance::<T>::put(imbalance_state);
|
||||
|
||||
Ok(final_amount)
|
||||
}
|
||||
@ -907,23 +909,25 @@ impl<T: Config> NetworkDataMutateHandler<NetworkData, BalanceOf<T>> for Pallet<T
|
||||
.map(|network| network.outgoing_share)
|
||||
.ok_or(())?;
|
||||
|
||||
GatekeeperAmounts::<T>::try_mutate(network_id, |gatekeeper_amount| -> Result<(), ()> {
|
||||
*gatekeeper_amount = gatekeeper_amount.checked_sub(&amount).ok_or(())?;
|
||||
Ok(())
|
||||
})?;
|
||||
let decreased_gatekeeper_amount = GatekeeperAmounts::<T>::get(network_id)
|
||||
.checked_sub(&amount)
|
||||
.ok_or(())?;
|
||||
|
||||
let curve_share = Perbill::from_parts(outgoing_share).mul_ceil(amount);
|
||||
let final_amount = amount.saturating_sub(curve_share);
|
||||
|
||||
NetworkImbalance::<T>::try_mutate(|imbalance_state| -> Result<(), ()> {
|
||||
imbalance_state.outgoing = imbalance_state.outgoing
|
||||
.checked_add(&final_amount)
|
||||
.ok_or(())?;
|
||||
imbalance_state.curve_share = imbalance_state.curve_share
|
||||
.checked_add(&curve_share)
|
||||
.ok_or(())?;
|
||||
Ok(())
|
||||
})?;
|
||||
let mut imbalance_state = NetworkImbalance::<T>::get();
|
||||
|
||||
imbalance_state.outgoing = imbalance_state.outgoing
|
||||
.checked_add(&final_amount)
|
||||
.ok_or(())?;
|
||||
|
||||
imbalance_state.curve_share = imbalance_state.curve_share
|
||||
.checked_add(&curve_share)
|
||||
.ok_or(())?;
|
||||
|
||||
GatekeeperAmounts::<T>::insert(network_id, decreased_gatekeeper_amount);
|
||||
NetworkImbalance::<T>::put(imbalance_state);
|
||||
|
||||
Ok(final_amount)
|
||||
}
|
||||
|
||||
@ -6,7 +6,14 @@ use sp_std::{
|
||||
vec::Vec,
|
||||
};
|
||||
|
||||
pub trait IdentifierConverter<A, E> {
|
||||
pub trait CiphersuiteSizes<A, E> {
|
||||
fn header_bytes_len(&self) -> usize;
|
||||
fn element_bytes_len(&self) -> usize;
|
||||
fn signature_bytes_len(&self) -> usize;
|
||||
fn scalar_bytes_len(&self) -> usize;
|
||||
}
|
||||
|
||||
pub trait IdentifierConverter<A, E>: CiphersuiteSizes<A, E> {
|
||||
fn non_zero_index(index: A) -> Result<A, E>;
|
||||
fn convert_identifier_to_index(bytes: &[u8]) -> Result<A, E>;
|
||||
}
|
||||
@ -15,11 +22,6 @@ pub trait FlexibleRoundOptimizedSchnorrThresholdSignature<A, E>: MerkleTreeBuild
|
||||
type Packages<'a>;
|
||||
type NoncePackages<'a>;
|
||||
|
||||
fn header_bytes_len(&self) -> usize;
|
||||
fn element_bytes_len(&self) -> usize;
|
||||
fn signature_bytes_len(&self) -> usize;
|
||||
fn scalar_bytes_len(&self) -> usize;
|
||||
|
||||
fn verify_signature_share(
|
||||
&self,
|
||||
i: A,
|
||||
@ -92,13 +94,14 @@ pub trait MerkleTreeBuilder<A, E>: IdentifierConverter<A, E> {
|
||||
type Hash;
|
||||
|
||||
fn build_merkle_tree<C, V, F>(
|
||||
size_hint: usize,
|
||||
verifying_shares: &BTreeMap<Identifier<C>, V>,
|
||||
serialize_fn: F,
|
||||
) -> Result<Vec<Self::Hash>, E>
|
||||
where
|
||||
C: frost_core::Ciphersuite,
|
||||
<<C as Ciphersuite>::Group as Group>::Field: frost_core::Field,
|
||||
F: Fn(&V) -> Result<Vec<u8>, E>;
|
||||
F: Fn(&V, &mut Vec<u8>) -> Result<(), E>;
|
||||
|
||||
fn generate_merkle_proof_from_tree<C, V, F>(
|
||||
verifying_shares: &BTreeMap<Identifier<C>, V>,
|
||||
|
||||
@ -21,6 +21,13 @@ pub trait GhostHasher {
|
||||
bytes
|
||||
}
|
||||
|
||||
fn combine_hashes(left: Self::Hash, right: Self::Hash) -> Self::Hash;
|
||||
fn combine_hashes_prefixed(
|
||||
prefix: u8,
|
||||
left: Self::Hash,
|
||||
right: Self::Hash,
|
||||
) -> Self::Hash;
|
||||
|
||||
fn hash(data: &[u8]) -> Self::Hash;
|
||||
fn empty() -> Self::Hash;
|
||||
fn hash_len() -> usize;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ghost-weaver"
|
||||
version = "0.0.16"
|
||||
version = "0.0.21"
|
||||
description = "Weaving a secure cryptographic tapestry across different external chains."
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
@ -35,6 +35,9 @@ fn prepare_pallet<T: Config>(
|
||||
T::NetworkDataHandler::register(network_id, network_data)
|
||||
.expect("network should be valid for insertion");
|
||||
|
||||
let current_block = T::BlockNumberProvider::current_block_number();
|
||||
Pallet::<T>::on_initialize(current_block);
|
||||
|
||||
(network_id, authority, 0)
|
||||
}
|
||||
|
||||
@ -53,6 +56,7 @@ mod benchmarks {
|
||||
let block_attestation = AttestationContext::default()
|
||||
.with_network_id(network_id)
|
||||
.with_authority_index(authority_index)
|
||||
.with_current_block(1337u16.into())
|
||||
.build_block_attestation(420);
|
||||
|
||||
let signature = authority
|
||||
@ -101,6 +105,7 @@ mod benchmarks {
|
||||
.with_network_id(network_id)
|
||||
.with_weaving_session(weaving_session)
|
||||
.with_authority_index(authority_index)
|
||||
.with_current_block(1337u16.into())
|
||||
.build_hash_attestation(root_hash, next_session);
|
||||
|
||||
let signature = authority
|
||||
@ -320,9 +325,12 @@ mod benchmarks {
|
||||
let first_sha = sp_io::hashing::sha2_256(&last_header[..80]);
|
||||
let mut native_le = sp_io::hashing::sha2_256(&first_sha);
|
||||
native_le.reverse();
|
||||
let dynamic_trusted_root = H256::from(native_le);
|
||||
|
||||
LoomStates::<T>::insert(&network_id, &session, dynamic_trusted_root);
|
||||
let at_block = 420;
|
||||
let dynamic_trusted_root = H256::from(native_le);
|
||||
let loom_state = LoomState { at_block, root_hash: dynamic_trusted_root };
|
||||
|
||||
LoomStates::<T>::insert(&network_id, &session, loom_state);
|
||||
|
||||
let utxo_thread_proof = UtxoThreadProof::new(
|
||||
gettxproof_bytes,
|
||||
@ -360,8 +368,11 @@ mod benchmarks {
|
||||
let root_string =
|
||||
hex::decode("07f4a5ba4750d9ddfc080429287cbcbde7464aa2f8ae13feaade0dcb45ca6129")
|
||||
.expect("EVM Root hex should be valid");
|
||||
|
||||
let at_block = 420;
|
||||
let expected_root = H256::from_slice(&root_string);
|
||||
LoomStates::<T>::insert(&network_id, &session, expected_root);
|
||||
let loom_state = LoomState { at_block, root_hash: expected_root };
|
||||
LoomStates::<T>::insert(&network_id, &session, loom_state);
|
||||
|
||||
let receiver_32: [u8; 32] =
|
||||
hex::decode("0ae3ba32f8555fe3031461e2cb6feeadb67029ef7490b982824fc90751a4cb3e")
|
||||
|
||||
@ -22,7 +22,7 @@ use sp_runtime::{
|
||||
storage::StorageValueRef,
|
||||
storage_lock::{StorageLock, Time},
|
||||
},
|
||||
traits::{BlockNumberProvider, UniqueSaturatedInto},
|
||||
traits::{BlockNumberProvider, Saturating, UniqueSaturatedInto},
|
||||
RuntimeAppPublic,
|
||||
};
|
||||
|
||||
@ -182,6 +182,15 @@ pub mod pallet {
|
||||
CouldNotRegisterIncoming,
|
||||
}
|
||||
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn attested_blocks)]
|
||||
pub(super) type AttestedBlocks<T: Config> = StorageMap<
|
||||
_,
|
||||
Twox64Concat, AuthIndex,
|
||||
BlockNumberFor<T>,
|
||||
ValueQuery,
|
||||
>;
|
||||
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn current_weaving_session)]
|
||||
pub(super) type CurrentWeavingSession<T: Config> =
|
||||
@ -202,7 +211,7 @@ pub mod pallet {
|
||||
_,
|
||||
Twox64Concat, NetworkIdOf<T>,
|
||||
Twox64Concat, WeavingSession,
|
||||
H256,
|
||||
LoomState,
|
||||
ValueQuery,
|
||||
>;
|
||||
|
||||
@ -288,7 +297,12 @@ pub mod pallet {
|
||||
);
|
||||
return;
|
||||
}
|
||||
LoomStates::<T>::insert(&data.0, data.1, data.2);
|
||||
let initial_loom_state = LoomState {
|
||||
at_block: 0u16.into(),
|
||||
root_hash: data.2,
|
||||
};
|
||||
|
||||
LoomStates::<T>::insert(&data.0, data.1, initial_loom_state);
|
||||
});
|
||||
|
||||
if !self.authorities.is_empty() {
|
||||
@ -330,26 +344,20 @@ pub mod pallet {
|
||||
|
||||
let external_block = block_attestation.external_block;
|
||||
|
||||
let current_authorities_count = Authorities::<T>::decode_len().
|
||||
unwrap_or_default();
|
||||
|
||||
NetworkAttestations::<T>::try_mutate(
|
||||
&network_id,
|
||||
|attestations| -> DispatchResult {
|
||||
if attestations.is_empty() {
|
||||
attestations.bounded_resize(current_authorities_count, None);
|
||||
}
|
||||
let index = authority_index as usize;
|
||||
|
||||
ensure!(
|
||||
(authority_index as usize) < attestations.len(),
|
||||
Error::<T>::TooManyAttestations,
|
||||
);
|
||||
|
||||
attestations[authority_index as usize] = Some(external_block);
|
||||
ensure!(index < attestations.len(), Error::<T>::TooManyAttestations);
|
||||
attestations[index] = Some(external_block);
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let current_block = T::BlockNumberProvider::current_block_number();
|
||||
AttestedBlocks::<T>::insert(&authority_index, current_block);
|
||||
|
||||
Self::deposit_event(Event::<T>::BlockAttestated {
|
||||
network_id,
|
||||
authority_index,
|
||||
@ -406,6 +414,9 @@ pub mod pallet {
|
||||
}
|
||||
});
|
||||
|
||||
let current_block = T::BlockNumberProvider::current_block_number();
|
||||
AttestedBlocks::<T>::insert(&authority_index, current_block);
|
||||
|
||||
Self::deposit_event(Event::<T>::HashAttestated {
|
||||
authority_index,
|
||||
next_session,
|
||||
@ -438,7 +449,7 @@ pub mod pallet {
|
||||
let network_data = T::NetworkDataHandler::get(&network_id)
|
||||
.ok_or(Error::<T>::NonExistentNetworkId)?;
|
||||
|
||||
let root_hash = LoomStates::<T>::get(&network_id, &session);
|
||||
let state = LoomStates::<T>::get(&network_id, &session);
|
||||
let pulled_thread_key = thread_proof.get_unique_key(session, network_id);
|
||||
|
||||
ensure!(
|
||||
@ -447,7 +458,7 @@ pub mod pallet {
|
||||
);
|
||||
|
||||
let (receiver_account, amount) = thread_proof
|
||||
.verify_thread_proof(root_hash, network_id, &network_data.gatekeeper)
|
||||
.verify_thread_proof(state.root_hash, network_id, &network_data.gatekeeper)
|
||||
.ok_or(Error::<T>::InvalidMerkleProof)?;
|
||||
|
||||
let receiver_bytes: &[u8; 32] = receiver_account.as_ref();
|
||||
@ -504,11 +515,13 @@ pub mod pallet {
|
||||
let current_session = CurrentWeavingSession::<T>::get(&network_id);
|
||||
let loom_state_changed =
|
||||
LoomStates::<T>::mutate(&network_id, ¤t_session, |loom_state| {
|
||||
if *loom_state != weaving_state.hash && threshold_reached {
|
||||
*loom_state = weaving_state.hash;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
if !threshold_reached { return false; }
|
||||
|
||||
let hash_changed = loom_state.root_hash != weaving_state.hash;
|
||||
loom_state.at_block = tapestry_draft.median;
|
||||
if hash_changed { loom_state.root_hash = weaving_state.hash; }
|
||||
|
||||
hash_changed
|
||||
});
|
||||
|
||||
if loom_state_changed && weaving_state.next_session != current_session {
|
||||
@ -518,8 +531,9 @@ pub mod pallet {
|
||||
CurrentWeavingSession::<T>::insert(&network_id, next_session);
|
||||
}
|
||||
|
||||
weight.saturating_accrue(T::DbWeight::get().writes(1));
|
||||
weight.saturating_accrue(T::DbWeight::get().writes(2));
|
||||
TapestryDrafts::<T>::remove(&network_id);
|
||||
WeavingStates::<T>::remove(&network_id);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
@ -532,9 +546,11 @@ pub mod pallet {
|
||||
weight.saturating_accrue(T::DbWeight::get().reads(1));
|
||||
let attestation_len = NetworkAttestations::<T>::decode_len(&network_id);
|
||||
|
||||
if attestation_len.unwrap_or(0) > len {
|
||||
weight.saturating_accrue(T::DbWeight::get().writes(1));
|
||||
NetworkAttestations::<T>::remove(&network_id);
|
||||
if attestation_len.unwrap_or(0) != len {
|
||||
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
|
||||
NetworkAttestations::<T>::mutate(&network_id, |attestations| {
|
||||
attestations.bounded_resize(len, None);
|
||||
});
|
||||
return weight;
|
||||
}
|
||||
|
||||
@ -616,6 +632,21 @@ pub mod pallet {
|
||||
.propagate(true)
|
||||
.build()
|
||||
}
|
||||
Call::pull_thread {
|
||||
network_id,
|
||||
session,
|
||||
thread_proof,
|
||||
} => {
|
||||
let thread_context =
|
||||
Self::validate_thread(network_id, session, thread_proof)?;
|
||||
|
||||
ValidTransaction::with_tag_prefix("WeaverThread")
|
||||
.priority(T::UnsignedPriority::get())
|
||||
.and_provides(thread_context.to_fixed_bytes())
|
||||
.longevity(LOCK_BLOCK_EXPIRATION)
|
||||
.propagate(true)
|
||||
.build()
|
||||
}
|
||||
_ => InvalidTransaction::Call.into(),
|
||||
}
|
||||
}
|
||||
@ -623,6 +654,31 @@ pub mod pallet {
|
||||
}
|
||||
|
||||
impl<T: Config> Pallet<T> {
|
||||
fn validate_thread(
|
||||
network_id: &NetworkIdOf<T>,
|
||||
session: &WeavingSession,
|
||||
thread_proof: &ThreadProof<BalanceOf<T>>,
|
||||
) -> Result<H256, InvalidTransaction> {
|
||||
let network_data = T::NetworkDataHandler::get(&network_id)
|
||||
.ok_or(InvalidTransaction::BadProof)?;
|
||||
|
||||
let root_hash = LoomStates::<T>::get(&network_id, &session).root_hash;
|
||||
if root_hash == Default::default() {
|
||||
return Err(InvalidTransaction::BadProof);
|
||||
}
|
||||
|
||||
thread_proof
|
||||
.verify_thread_proof(root_hash, *network_id, &network_data.gatekeeper)
|
||||
.ok_or(InvalidTransaction::BadProof)?;
|
||||
|
||||
let pulled_thread_key = thread_proof.get_unique_key(*session, *network_id);
|
||||
if PulledThreads::<T>::contains_key(&pulled_thread_key) {
|
||||
return Err(InvalidTransaction::Stale);
|
||||
}
|
||||
|
||||
Ok(pulled_thread_key)
|
||||
}
|
||||
|
||||
fn validate_attestation_signature<A>(
|
||||
attestation: &A,
|
||||
signature: &<T::AuthorityId as RuntimeAppPublic>::Signature,
|
||||
@ -632,16 +688,6 @@ impl<T: Config> Pallet<T> {
|
||||
A: Encode,
|
||||
{
|
||||
let authority_index = attestation.authority_index();
|
||||
let attestation_block = attestation.block();
|
||||
let network_id = attestation.network_id();
|
||||
|
||||
if DisabledAuthorities::<T>::get().contains(authority_index) {
|
||||
return Err(InvalidTransaction::BadSigner);
|
||||
}
|
||||
|
||||
if T::BlockNumberProvider::current_block_number() <= attestation_block {
|
||||
return Err(InvalidTransaction::BadProof);
|
||||
}
|
||||
|
||||
Authorities::<T>::get()
|
||||
.get(authority_index as usize)
|
||||
@ -653,6 +699,31 @@ impl<T: Config> Pallet<T> {
|
||||
.ok_or(InvalidTransaction::BadSigner)
|
||||
})?;
|
||||
|
||||
let attestation_block = attestation.block();
|
||||
let current_block = T::BlockNumberProvider::current_block_number();
|
||||
let lock: BlockNumberFor<T> = LOCK_BLOCK_EXPIRATION.unique_saturated_into();
|
||||
let block_expiration = attestation_block.saturating_add(lock);
|
||||
|
||||
let block_expired = current_block >= block_expiration;
|
||||
let block_attested = AttestedBlocks::<T>::get(authority_index)
|
||||
.ge(&attestation_block);
|
||||
|
||||
if block_expired || block_attested {
|
||||
return Err(InvalidTransaction::BadProof);
|
||||
}
|
||||
|
||||
let network_id = attestation.network_id();
|
||||
let current_attestation_len = NetworkAttestations::<T>::decode_len(&network_id)
|
||||
.unwrap_or(0);
|
||||
|
||||
if authority_index as usize >= current_attestation_len {
|
||||
return Err(InvalidTransaction::BadSigner.into());
|
||||
}
|
||||
|
||||
if DisabledAuthorities::<T>::get().contains(authority_index) {
|
||||
return Err(InvalidTransaction::BadSigner);
|
||||
}
|
||||
|
||||
if !T::NetworkDataHandler::contains_key(&network_id) {
|
||||
return Err(InvalidTransaction::BadProof);
|
||||
}
|
||||
|
||||
@ -76,6 +76,7 @@ fn should_successfully_compute_median_and_start_weaving_round() {
|
||||
let networks = vec![(network_id, network_data, Default::default())];
|
||||
|
||||
new_test_ext(authorities, networks).execute_with(|| {
|
||||
GhostWeaver::on_initialize(1);
|
||||
System::set_block_number(2);
|
||||
|
||||
let context = AttestationContext::default()
|
||||
@ -120,6 +121,7 @@ fn should_apply_cooldown_delay_on_consensus_failure() {
|
||||
let networks = vec![(network_id, network_data, Default::default())];
|
||||
|
||||
new_test_ext(authorities, networks).execute_with(|| {
|
||||
GhostWeaver::on_initialize(9);
|
||||
System::set_block_number(10);
|
||||
|
||||
let context = AttestationContext::default()
|
||||
@ -168,6 +170,7 @@ fn validate_unsigned_should_prevent_mempool_dos_via_tags() {
|
||||
let networks = vec![(network_id, network_data, Default::default())];
|
||||
|
||||
new_test_ext(authorities, networks).execute_with(|| {
|
||||
GhostWeaver::on_initialize(1);
|
||||
System::set_block_number(2);
|
||||
|
||||
let att = AttestationContext::default()
|
||||
@ -240,6 +243,9 @@ fn offchain_worker_should_fetch_block_and_submit_unsigned_tx() {
|
||||
ext.register_extension(TransactionPoolExt::new(pool));
|
||||
|
||||
ext.execute_with(|| {
|
||||
GhostWeaver::on_initialize(1);
|
||||
GhostWeaver::on_initialize(2);
|
||||
|
||||
let network_id_encoded = evm_network_id.encode();
|
||||
|
||||
let mut endpoint_key = b"ghost-weaver::".to_vec();
|
||||
@ -313,7 +319,6 @@ fn offchain_worker_should_fetch_block_and_submit_unsigned_tx() {
|
||||
ext.execute_with(|| {
|
||||
System::set_block_number(1u64);
|
||||
GhostWeaver::offchain_worker(1u64);
|
||||
System::set_block_number(2u64);
|
||||
|
||||
let state = pool_state.read();
|
||||
assert_eq!(state.transactions.len(), 1);
|
||||
@ -341,7 +346,6 @@ fn offchain_worker_should_fetch_block_and_submit_unsigned_tx() {
|
||||
ext.execute_with(|| {
|
||||
System::set_block_number(2u64);
|
||||
GhostWeaver::offchain_worker(2u64);
|
||||
System::set_block_number(3u64);
|
||||
|
||||
let state = pool_state.read();
|
||||
assert_eq!(state.transactions.len(), 2);
|
||||
@ -362,6 +366,7 @@ fn offchain_worker_should_fetch_block_and_submit_unsigned_tx() {
|
||||
assert_eq!(curr_evm_block, 25639556);
|
||||
|
||||
assert!(TapestryDrafts::<TestRuntime>::get(&evm_network_id).is_none());
|
||||
GhostWeaver::on_initialize(3u64);
|
||||
GhostWeaver::on_initialize(4u64);
|
||||
assert!(TapestryDrafts::<TestRuntime>::get(&evm_network_id).is_some());
|
||||
});
|
||||
@ -372,6 +377,9 @@ fn offchain_worker_should_fetch_hash_and_submit_unsigned_tx() {
|
||||
let evm_network_id = 1u32;
|
||||
let utxo_network_id = 69u32;
|
||||
|
||||
let median_utxo_block = 960129;
|
||||
let median_evm_block = 25639556;
|
||||
|
||||
let pair = AuthorityPair::from_string("//Alice", None).expect("Should be valid seed");
|
||||
|
||||
let new_evm_network_data = NetworkDataBuilder::default()
|
||||
@ -406,11 +414,12 @@ fn offchain_worker_should_fetch_hash_and_submit_unsigned_tx() {
|
||||
ext.register_extension(TransactionPoolExt::new(pool));
|
||||
|
||||
ext.execute_with(|| {
|
||||
GhostWeaver::on_initialize(1);
|
||||
GhostWeaver::on_initialize(2);
|
||||
|
||||
let tapestry_draft = TapestryDraftBuilder::<crate::ExternalBlockNumber, u32>::default();
|
||||
|
||||
let evm_tapestry_draft = tapestry_draft.with_median_external(25639556).build();
|
||||
|
||||
let utxo_tapestry_draft = tapestry_draft.with_median_external(960129).build();
|
||||
let evm_tapestry_draft = tapestry_draft.with_median_external(median_evm_block).build();
|
||||
let utxo_tapestry_draft = tapestry_draft.with_median_external(median_utxo_block).build();
|
||||
|
||||
CurrentWeavingSession::<TestRuntime>::insert(&evm_network_id, evm_session);
|
||||
CurrentWeavingSession::<TestRuntime>::insert(&utxo_network_id, utxo_session);
|
||||
@ -492,7 +501,6 @@ fn offchain_worker_should_fetch_hash_and_submit_unsigned_tx() {
|
||||
ext.execute_with(|| {
|
||||
System::set_block_number(1u64);
|
||||
GhostWeaver::offchain_worker(1u64);
|
||||
System::set_block_number(2u64);
|
||||
|
||||
let state = pool_state.read();
|
||||
assert_eq!(state.transactions.len(), 1);
|
||||
@ -518,14 +526,15 @@ fn offchain_worker_should_fetch_hash_and_submit_unsigned_tx() {
|
||||
GhostWeaver::on_initialize(3u64);
|
||||
let curr_state = LoomStates::<TestRuntime>::get(&utxo_network_id, &utxo_session);
|
||||
|
||||
assert_eq!(prev_state, H256::default());
|
||||
assert_eq!(curr_state, block_hash);
|
||||
assert_eq!(prev_state.root_hash, H256::default());
|
||||
assert_eq!(curr_state.root_hash, block_hash);
|
||||
assert_eq!(prev_state.at_block, 0);
|
||||
assert_eq!(curr_state.at_block, median_utxo_block);
|
||||
});
|
||||
|
||||
ext.execute_with(|| {
|
||||
System::set_block_number(2u64);
|
||||
GhostWeaver::offchain_worker(2u64);
|
||||
System::set_block_number(3u64);
|
||||
|
||||
let state = pool_state.read();
|
||||
assert_eq!(state.transactions.len(), 2);
|
||||
@ -542,17 +551,20 @@ fn offchain_worker_should_fetch_hash_and_submit_unsigned_tx() {
|
||||
assert_eq!(curr_weaving_state.next_session, evm_session + 1);
|
||||
|
||||
let bytes = hex::decode("f72b9ef0b66c8cc3952ffd11dc0b85f3b02e6edfa9236da400138f2fcba4668d")
|
||||
.expect("UTXO block hash should be valid");
|
||||
.expect("EVM block hash should be valid");
|
||||
let block_hash = H256::from_slice(&bytes);
|
||||
|
||||
assert_eq!(curr_weaving_state.hash, block_hash);
|
||||
|
||||
let prev_state = LoomStates::<TestRuntime>::get(&evm_network_id, &evm_session);
|
||||
GhostWeaver::on_initialize(3u64);
|
||||
GhostWeaver::on_initialize(4u64);
|
||||
let curr_state = LoomStates::<TestRuntime>::get(&evm_network_id, &evm_session);
|
||||
|
||||
assert_eq!(prev_state, H256::default());
|
||||
assert_eq!(curr_state, block_hash);
|
||||
assert_eq!(prev_state.root_hash, H256::default());
|
||||
assert_eq!(curr_state.root_hash, block_hash);
|
||||
assert_eq!(prev_state.at_block, 0);
|
||||
assert_eq!(curr_state.at_block, median_evm_block);
|
||||
});
|
||||
}
|
||||
|
||||
@ -635,14 +647,18 @@ fn should_successfully_pull_evm_thread_and_mint_currency() {
|
||||
];
|
||||
|
||||
new_test_ext(authorities, networks).execute_with(|| {
|
||||
GhostWeaver::on_initialize(1);
|
||||
|
||||
// https://sepolia.etherscan.io/address/0x7fec11e652f4d54e8cf11c4b52c360380332f2bd#readContract
|
||||
// getRoot: session 0, atBlock 11716130
|
||||
let session = 0;
|
||||
let root_string =
|
||||
hex::decode("07f4a5ba4750d9ddfc080429287cbcbde7464aa2f8ae13feaade0dcb45ca6129")
|
||||
.expect("Root hex should be valid");
|
||||
|
||||
let expected_root = H256::from_slice(&root_string);
|
||||
LoomStates::<TestRuntime>::insert(&network_id, &session, expected_root);
|
||||
let expected_loom_state = LoomState { at_block: 420, root_hash: expected_root };
|
||||
LoomStates::<TestRuntime>::insert(&network_id, &session, expected_loom_state);
|
||||
|
||||
let mut total_issuance = 0;
|
||||
|
||||
@ -755,7 +771,8 @@ fn should_successfully_pull_utxo_thread_and_mint_currency() {
|
||||
.expect("Bitcoin Root hex should be valid");
|
||||
|
||||
let expected_root = H256::from_slice(&block_hash);
|
||||
LoomStates::<TestRuntime>::insert(&network_id, &session, expected_root);
|
||||
let expected_loom_state = LoomState { at_block: 420, root_hash: expected_root };
|
||||
LoomStates::<TestRuntime>::insert(&network_id, &session, expected_loom_state);
|
||||
|
||||
let expected_receiver_bytes = hex::decode("1657090d02985f0cdb41436fe2d5a83a3acb1995d963a698e7e619e927bdcc5e").unwrap();
|
||||
let mut receiver_raw = [0u8; 32];
|
||||
@ -853,7 +870,8 @@ fn should_successfully_pull_utxo_thread_and_reject_nominal_varint_encoding() {
|
||||
.expect("Bitcoin Root hex should be valid");
|
||||
|
||||
let expected_root = H256::from_slice(&block_hash);
|
||||
LoomStates::<TestRuntime>::insert(&network_id, &session, expected_root);
|
||||
let expected_loom_state = LoomState { at_block: 420, root_hash: expected_root };
|
||||
LoomStates::<TestRuntime>::insert(&network_id, &session, expected_loom_state);
|
||||
|
||||
let expected_receiver_bytes = hex::decode("1657090d02985f0cdb41436fe2d5a83a3acb1995d963a698e7e619e927bdcc5e").unwrap();
|
||||
let mut receiver_raw = [0u8; 32];
|
||||
@ -928,6 +946,7 @@ fn on_initialize_should_finalize_session_when_timeout_is_reached() {
|
||||
|
||||
new_test_ext(authorities, networks).execute_with(|| {
|
||||
let current_substrate_block = 10;
|
||||
GhostWeaver::on_initialize(current_substrate_block);
|
||||
System::set_block_number(current_substrate_block + 1);
|
||||
|
||||
let tapestry_draft = TapestryDraftBuilder::default()
|
||||
@ -975,8 +994,96 @@ fn on_initialize_should_finalize_session_when_timeout_is_reached() {
|
||||
GhostWeaver::on_initialize(current_substrate_block);
|
||||
|
||||
let saved_loom = LoomStates::<TestRuntime>::get(&network_id, current_session);
|
||||
assert_ne!(saved_loom, target_hash);
|
||||
assert_eq!(saved_loom, saved_loom);
|
||||
assert_ne!(saved_loom.root_hash, target_hash);
|
||||
assert_eq!(saved_loom.at_block, 0);
|
||||
|
||||
let updated_session = CurrentWeavingSession::<TestRuntime>::get(&network_id);
|
||||
assert_eq!(updated_session, current_session);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_initialize_should_update_at_block_when_threshold_reached_with_same_hash() {
|
||||
let pair1 = AuthorityPair::from_string("//Alice", None).expect("Should be valid seed");
|
||||
let pair2 = AuthorityPair::from_string("//Bob", None).expect("Should be valid seed");
|
||||
let pair3 = AuthorityPair::from_string("//Charlie", None).expect("Should be valid seed");
|
||||
|
||||
let network_id = 1;
|
||||
|
||||
let new_network_data = NetworkDataBuilder::default()
|
||||
.with_network_type(NetworkType::Evm)
|
||||
.build();
|
||||
|
||||
let authorities = vec![pair1.clone(), pair2.clone(), pair3.clone()];
|
||||
let networks = vec![(network_id, new_network_data, 0u64)];
|
||||
|
||||
new_test_ext(authorities, networks).execute_with(|| {
|
||||
let current_substrate_block = 10;
|
||||
let current_session = CurrentWeavingSession::<TestRuntime>::get(&network_id);
|
||||
|
||||
let target_hash = H256::repeat_byte(0xAA);
|
||||
LoomStates::<TestRuntime>::insert(&network_id, ¤t_session, crate::LoomState {
|
||||
root_hash: target_hash,
|
||||
at_block: 0,
|
||||
});
|
||||
|
||||
System::set_block_number(current_substrate_block);
|
||||
GhostWeaver::on_initialize(current_substrate_block);
|
||||
|
||||
let tapestry_draft = TapestryDraftBuilder::default()
|
||||
.with_current_block(current_substrate_block)
|
||||
.with_block_delay(5u32)
|
||||
.with_median_external(100)
|
||||
.build();
|
||||
|
||||
TapestryDrafts::<TestRuntime>::insert(&network_id, tapestry_draft);
|
||||
|
||||
let attestation = AttestationContext::default()
|
||||
.with_current_block(current_substrate_block)
|
||||
.with_network_id(network_id)
|
||||
.with_weaving_session(current_session);
|
||||
|
||||
let hash_att1 = attestation
|
||||
.with_authority_index(0)
|
||||
.build_hash_attestation(target_hash, current_session);
|
||||
|
||||
let hash_att2 = attestation
|
||||
.with_authority_index(1)
|
||||
.build_hash_attestation(target_hash, current_session);
|
||||
|
||||
let hash_att3 = attestation
|
||||
.with_authority_index(2)
|
||||
.build_hash_attestation(target_hash, current_session);
|
||||
|
||||
assert!(GhostWeaver::weave_weft(
|
||||
RuntimeOrigin::none(),
|
||||
hash_att1,
|
||||
pair1.sign(&hash_att1.encode())
|
||||
)
|
||||
.is_ok());
|
||||
assert!(GhostWeaver::weave_weft(
|
||||
RuntimeOrigin::none(),
|
||||
hash_att2,
|
||||
pair2.sign(&hash_att2.encode())
|
||||
)
|
||||
.is_ok());
|
||||
assert!(GhostWeaver::weave_weft(
|
||||
RuntimeOrigin::none(),
|
||||
hash_att3,
|
||||
pair3.sign(&hash_att3.encode())
|
||||
)
|
||||
.is_ok());
|
||||
|
||||
let state_before = WeavingStates::<TestRuntime>::get(&network_id);
|
||||
assert_eq!(state_before.count, 3);
|
||||
assert_eq!(state_before.hash, target_hash);
|
||||
|
||||
GhostWeaver::on_initialize(current_substrate_block);
|
||||
|
||||
let saved_loom = LoomStates::<TestRuntime>::get(&network_id, current_session);
|
||||
|
||||
assert_eq!(saved_loom.root_hash, target_hash);
|
||||
assert_eq!(saved_loom.at_block, 100);
|
||||
|
||||
let updated_session = CurrentWeavingSession::<TestRuntime>::get(&network_id);
|
||||
assert_eq!(updated_session, current_session);
|
||||
|
||||
@ -14,7 +14,6 @@ use ghost_helpers::{
|
||||
merkle_tree::verify_tree_proof,
|
||||
SubstrateBlake2Hasher, SubstrateKeccakHasher, UtxoSha2Hasher,
|
||||
};
|
||||
use ghost_traits::hashing::GhostHasher;
|
||||
|
||||
use crate::{ExternalBlockNumber, ThreadId, WeavingSession};
|
||||
|
||||
@ -53,6 +52,25 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(
|
||||
Default,
|
||||
RuntimeDebug,
|
||||
Clone,
|
||||
Copy,
|
||||
Eq,
|
||||
PartialEq,
|
||||
Ord,
|
||||
PartialOrd,
|
||||
Encode,
|
||||
Decode,
|
||||
TypeInfo,
|
||||
MaxEncodedLen,
|
||||
)]
|
||||
pub struct LoomState {
|
||||
pub at_block: ExternalBlockNumber,
|
||||
pub root_hash: H256,
|
||||
}
|
||||
|
||||
#[derive(
|
||||
Default,
|
||||
RuntimeDebug,
|
||||
@ -350,8 +368,10 @@ where
|
||||
{
|
||||
if EVM_MERKLE_DEPTH as usize != self.proof.len() { return None; }
|
||||
|
||||
let preimage_hash = self.get_preimage_hash(network_id)?;
|
||||
|
||||
let proof_valid = verify_tree_proof::<SubstrateKeccakHasher, _>(
|
||||
&self.get_preimage_slice(network_id).to_fixed_bytes(),
|
||||
&preimage_hash.to_fixed_bytes(),
|
||||
self.proof.as_ref(),
|
||||
root_hash,
|
||||
self.proof_index,
|
||||
@ -362,22 +382,17 @@ where
|
||||
Some((self.receiver.clone(), self.amount))
|
||||
}
|
||||
|
||||
fn get_preimage_slice<NetworkId>(&self, network_id: NetworkId) -> H256
|
||||
fn get_preimage_hash<NetworkId>(&self, network_id: NetworkId) -> Option<H256>
|
||||
where
|
||||
NetworkId: Copy + Clone + Eq + PartialEq + UniqueSaturatedInto<u64>,
|
||||
{
|
||||
let slot_index_usize: usize = self.slot_index.unique_saturated_into();
|
||||
let mut slot_values: Vec<H256> = self.slots.to_vec();
|
||||
|
||||
match slot_values.get_mut(slot_index_usize) {
|
||||
Some(slot) => {
|
||||
*slot = self.compute_arguments_hash(network_id);
|
||||
cumulative_hash::<SubstrateKeccakHasher, _>(slot_values)
|
||||
}
|
||||
None => {
|
||||
SubstrateKeccakHasher::empty()
|
||||
}
|
||||
}
|
||||
self.slots.get(slot_index_usize)
|
||||
.filter(|&&provided_hash| {
|
||||
provided_hash == self.compute_arguments_hash(network_id)
|
||||
})
|
||||
.map(|_| cumulative_hash::<SubstrateKeccakHasher, _>(self.slots.iter()))
|
||||
}
|
||||
|
||||
pub fn get_unique_key<NetworkId>(
|
||||
|
||||
Loading…
Reference in New Issue
Block a user