Skip to content

Commit

Permalink
Introduce new CLI command
Browse files Browse the repository at this point in the history
  • Loading branch information
mertwole committed Aug 20, 2024
1 parent f7ca72f commit 3c36551
Show file tree
Hide file tree
Showing 10 changed files with 95 additions and 15 deletions.
4 changes: 1 addition & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ _obj
cache/
out/

!/broadcast
**/broadcast/*/31337/
**/broadcast/**/dry-run/
ethereum/broadcast

.env
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion gear-rpc-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ edition.workspace = true
[dependencies]
hex.workspace = true
futures-util.workspace = true

anyhow.workspace = true
blake2.workspace = true
gsdk.workspace = true
subxt.workspace = true
sc-consensus-grandpa.workspace = true
Expand Down
6 changes: 6 additions & 0 deletions gear-rpc-client/src/dto.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const ED25519_PUBLIC_KEY_SIZE: usize = 32;
const ED25519_SIGNATURE_SIZE: usize = 64;
const KECCAK_HASH_SIZE: usize = 32;
const BLAKE2_HASH_SIZE: usize = 32;

pub struct PreCommit {
pub public_key: [u8; ED25519_PUBLIC_KEY_SIZE],
Expand Down Expand Up @@ -57,3 +58,8 @@ pub struct Message {
pub struct UserMessageSent {
pub payload: Vec<u8>,
}

pub struct AuthoritySetState {
pub authority_set_id: u64,
pub authority_set_hash: [u8; BLAKE2_HASH_SIZE],
}
48 changes: 42 additions & 6 deletions gear-rpc-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
#![feature(generic_const_exprs)]

use anyhow::anyhow;
use dto::BranchNodeData;
use blake2::{
digest::{Update, VariableOutput},
Blake2bVar,
};
use dto::{AuthoritySetState, BranchNodeData};
use gsdk::{
metadata::{
gear::Event as GearEvent,
Expand Down Expand Up @@ -85,12 +89,44 @@ impl GearApi {
Ok(self.api.rpc().chain_get_finalized_head().await?)
}

/// Fetch authority set id for the given block.
pub async fn authority_set_id(&self, block: H256) -> anyhow::Result<u64> {
let block = (*self.api).blocks().at(block).await?;
let set_id_address = gsdk::Api::storage_root(GrandpaStorage::CurrentSetId);
Self::fetch_from_storage(&block, &set_id_address).await
}

/// Get authority set state for specified block. If block is not specified
/// the latest finalized block is taken.
pub async fn authority_set_state(
&self,
block: Option<H256>,
) -> anyhow::Result<AuthoritySetState> {
let block = match block {
Some(block) => block,
None => self.latest_finalized_block().await?,
};

let block = (*self.api).blocks().at(block).await?;
let set_id_address = gsdk::Api::storage_root(GrandpaStorage::CurrentSetId);
let set_id = Self::fetch_from_storage(&block, &set_id_address).await?;

let authority_set = self.fetch_authority_set(set_id).await?;
let authority_set_data: Vec<_> = authority_set.into_iter().flatten().collect();

let mut hasher = Blake2bVar::new(32).expect("Failed to instantiate Blake2bVar");
hasher.update(&authority_set_data);
let mut hash = [0; 32];
hasher
.finalize_variable(&mut hash)
.expect("Hash is of incorrect size");

Ok(AuthoritySetState {
authority_set_hash: hash,
authority_set_id: set_id,
})
}

/// Find authority set id that have signed given `block`.
pub async fn signed_by_authority_set_id(&self, block: H256) -> anyhow::Result<u64> {
let stored_set_id = self.authority_set_id(block).await?;
Expand Down Expand Up @@ -151,10 +187,10 @@ impl GearApi {

pub async fn fetch_finality_proof_for_session(
&self,
validator_set_id: u64,
authority_set_id: u64,
) -> anyhow::Result<(H256, dto::BlockFinalityProof)> {
let block = self
.search_for_authority_set_block(validator_set_id)
.search_for_authority_set_block(authority_set_id)
.await?;

self.fetch_finality_proof(block).await
Expand All @@ -166,7 +202,7 @@ impl GearApi {
&self,
after_block: H256,
) -> anyhow::Result<(H256, dto::BlockFinalityProof)> {
let required_validator_set_id = self.signed_by_authority_set_id(after_block).await?;
let required_authority_set_id = self.signed_by_authority_set_id(after_block).await?;

let after_block_number = self.block_hash_to_number(after_block).await?;
let finality: Option<String> = self
Expand All @@ -190,7 +226,7 @@ impl GearApi {

let signed_data = sp_consensus_grandpa::localized_payload(
justification.round,
required_validator_set_id,
required_authority_set_id,
&sp_consensus_grandpa::Message::<GearHeader>::Precommit(Precommit::<GearHeader>::new(
finality.block,
fetched_block_number,
Expand All @@ -202,7 +238,7 @@ impl GearApi {
assert!(pc.signature.verify(&signed_data[..], &pc.id));
}

let validator_set = self.fetch_authority_set(required_validator_set_id).await?;
let validator_set = self.fetch_authority_set(required_authority_set_id).await?;

let pre_commits: Vec<_> = justification
.commit
Expand Down
2 changes: 1 addition & 1 deletion prover/src/final_proof/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ impl FinalProof {

let desired_genesis_validator_set_hash = Blake2TargetGoldilocks::parse_exact(
&mut genesis_config
.validator_set_hash
.authority_set_hash
.iter()
.map(|el| builder.constant(F::from_noncanonical_u64(*el))),
);
Expand Down
2 changes: 1 addition & 1 deletion prover/src/latest_validator_set/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ impl Circuit {
) -> ProofWithCircuitData<LatestValidatorSetTarget> {
let genesis_data_pis = vec![config.authority_set_id]
.into_iter()
.chain(config.validator_set_hash)
.chain(config.authority_set_hash)
.map(F::from_noncanonical_u64)
.enumerate()
.collect();
Expand Down
2 changes: 1 addition & 1 deletion prover/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ pub mod proving {
#[derive(Clone, Copy)]
pub struct GenesisConfig {
pub authority_set_id: u64,
pub validator_set_hash: [u64; BLAKE2_DIGEST_SIZE_IN_GOLDILOCKS_FIELD_ELEMENTS],
pub authority_set_hash: [u64; BLAKE2_DIGEST_SIZE_IN_GOLDILOCKS_FIELD_ELEMENTS],
}

/// Prove very first transition from genesis authority set to the subsequent.
Expand Down
23 changes: 23 additions & 0 deletions relayer/src/fetch_authority_set_state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use gear_rpc_client::GearApi;

pub async fn fetch(gear_api: GearApi, block: Option<u32>) -> anyhow::Result<()> {
let block = match block {
Some(bn) => Some(
gear_api
.block_number_to_hash(bn)
.await
.expect("Failed to fetch block hash by number"),
),
None => None,
};

let state = gear_api.authority_set_state(block).await.unwrap();

println!("Authority set id: {}", state.authority_set_id);
println!(
"Authority set hash: {}",
hex::encode(&state.authority_set_hash)

Check failure on line 19 in relayer/src/fetch_authority_set_state.rs

View workflow job for this annotation

GitHub Actions / lints

the borrowed expression implements the required traits
);

Ok(())
}
20 changes: 18 additions & 2 deletions relayer/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use relay_merkle_roots::MerkleRootRelayer;
use utils_prometheus::MetricsBuilder;

mod ethereum_checkpoints;
mod fetch_authority_set_state;
mod message_relayer;
mod proof_storage;
mod prover_interface;
Expand All @@ -24,7 +25,7 @@ const DEFAULT_PROMETHEUS_ENDPOINT: &str = "0.0.0.0:9090";
const GENESIS_CONFIG: GenesisConfig = GenesisConfig {
authority_set_id: 1,
// 0xb9853ab2fb585702dfd9040ee8bc9f94dc5b0abd8b0f809ec23fdc0265b21e24
validator_set_hash: [
authority_set_hash: [
0xb9853ab2, 0xfb585702, 0xdfd9040e, 0xe8bc9f94, 0xdc5b0abd, 0x8b0f809e, 0xc23fdc02,
0x65b21e24,
],
Expand All @@ -49,6 +50,9 @@ enum CliCommands {
RelayMessages(RelayMessagesArgs),
/// Start service constantly relaying Ethereum checkpoints to the Vara program
RelayCheckpoints(RelayCheckpointsArgs),
/// Fetch authority set hash and id at specified block
#[clap(visible_alias("fs"))]
FetchAuthoritySetState(FetchAuthoritySetStateArgs),
}

#[derive(Args)]
Expand Down Expand Up @@ -79,6 +83,13 @@ struct RelayMerkleRootsArgs {
proof_storage_args: ProofStorageArgs,
}

#[derive(Args)]
struct FetchAuthoritySetStateArgs {
#[clap(flatten)]
vara_endpoint: VaraEndpointArg,
block_number: Option<u32>,
}

#[derive(Args)]
struct VaraEndpointArg {
/// Address of the VARA RPC endpoint
Expand Down Expand Up @@ -235,8 +246,13 @@ async fn main() {

relayer.run().await.unwrap();
}

CliCommands::RelayCheckpoints(args) => ethereum_checkpoints::relay(args).await,
CliCommands::FetchAuthoritySetState(args) => {
let gear_api = create_gear_client(&args.vara_endpoint).await;
fetch_authority_set_state::fetch(gear_api, args.block_number)
.await
.expect("Failed to fetch authority set state");
}
};
}

Expand Down

0 comments on commit 3c36551

Please sign in to comment.