Skip to content

Commit

Permalink
feat ✨: RPC method to return head consensus block
Browse files Browse the repository at this point in the history
ISSUE: #60
  • Loading branch information
emailnjv committed Jan 17, 2025
1 parent 1245b7a commit 9c9673e
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 5 deletions.
8 changes: 8 additions & 0 deletions app/src/auxpow_miner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ use ethereum_types::Address as EvmAddress;
use eyre::{Report, Result};
use serde::{de::Error as _, ser::Error as _, Deserialize, Deserializer, Serialize, Serializer};
use std::{collections::BTreeMap, marker::PhantomData, sync::Arc, thread, time::Duration};
use execution_layer::ExecutionBlock;
use store::ItemStore;
use tokio::runtime::Handle;
use tokio::time::sleep;
use tracing::*;
use types::{MainnetEthSpec, Uint256};
use crate::block::SignedConsensusBlock;
use crate::error::AuxPowMiningError::HashRetrievalError;

fn compact_target_to_hex<S>(bits: &CompactTarget, s: S) -> Result<S::Ok, S::Error>
Expand Down Expand Up @@ -71,6 +73,7 @@ pub struct AuxBlock {
_target: Target,
}

// TODO: Either move this struct out of auxpow__miner or modularize between mining related functionalities, and basic chain functionality
#[async_trait::async_trait]
pub trait ChainManager<BI> {
async fn get_aggregate_hashes(&self) -> Result<Vec<BlockHash>>;
Expand All @@ -91,6 +94,7 @@ pub trait ChainManager<BI> {
fn set_target_override(&self, target: CompactTarget);
fn get_target_override(&self) -> Option<CompactTarget>;
async fn is_synced(&self) -> bool;
fn get_head(&self) -> Result<SignedConsensusBlock<MainnetEthSpec>, Error>;
}

pub trait BlockIndex {
Expand Down Expand Up @@ -381,6 +385,10 @@ impl<BI: BlockIndex, CM: ChainManager<BI>> AuxPowMiner<BI, CM> {
)
.await
}

pub fn get_head(&self) -> Result<SignedConsensusBlock<MainnetEthSpec>, Error> {
self.chain.get_head()
}
}

pub fn spawn_background_miner<DB: ItemStore<MainnetEthSpec>>(chain: Arc<Chain<DB>>) {
Expand Down
12 changes: 10 additions & 2 deletions app/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::network::{ApproveBlock, Client as NetworkClient, OutboundRequest};
use crate::signatures::CheckedIndividualApproval;
use crate::spec::ChainSpec;
use crate::store::BlockRef;
use crate::{aura::Aura, block::SignedConsensusBlock, error::Error, store::Storage};
use crate::{aura::Aura, block::SignedConsensusBlock, chain, error::Error, store::Storage};
use bitcoin::{BlockHash, CompactTarget, Transaction as BitcoinTransaction, Txid};
use bls::PublicKey;
use bridge::SingleMemberTransactionSignatures;
Expand All @@ -31,6 +31,7 @@ use tokio::sync::broadcast::error::RecvError;
use tokio::sync::RwLock;
use tracing::*;
use types::{ExecutionBlockHash, Hash256, MainnetEthSpec};
use crate::error::Error::ChainError;

pub(crate) type BitcoinWallet = UtxoManager<Tree>;

Expand Down Expand Up @@ -481,7 +482,10 @@ impl<DB: ItemStore<MainnetEthSpec>> Chain<DB> {
return Err(Error::InvalidBlock);
}

debug!("consensus block parent hash: {}\nexecution block parent hash: {}\nexecution block hash: {}", unverified_block.message.parent_hash, unverified_block.message.execution_payload.parent_hash, unverified_block.message.execution_payload.block_hash);

let prev = self.get_parent(&unverified_block)?;
debug!("parent execution block hash: {}\nparent execution block timestamp: {}\nparent execution block parent hash: {}", prev.message.execution_payload.block_hash, prev.message.execution_payload.timestamp, prev.message.execution_payload.parent_hash);
let prev_payload_hash_according_to_consensus = prev.message.execution_payload.block_hash;
let prev_payload_hash = unverified_block.message.execution_payload.parent_hash;
// unverified_block.prev().payload must match unverified_block.payload.prev()
Expand Down Expand Up @@ -608,7 +612,7 @@ impl<DB: ItemStore<MainnetEthSpec>> Chain<DB> {
"Found {} pegouts in block after filtering",
required_outputs.len()
);

let block_number = unverified_block.message.execution_payload.block_number;

if block_number > 285450 {
Expand Down Expand Up @@ -1500,6 +1504,10 @@ impl<DB: ItemStore<MainnetEthSpec>> ChainManager<ConsensusBlock<MainnetEthSpec>>
block.message
}

fn get_head(&self) -> Result<SignedConsensusBlock<MainnetEthSpec>, Error> {
Ok(self.storage.get_block(&self.storage.get_head()?.ok_or(Error::ChainError(BlockErrorBlockTypes::Head.into()))?.hash)?.ok_or(Error::ChainError(BlockErrorBlockTypes::Head.into()))?)
}

async fn push_auxpow(
&self,
start_hash: bitcoin::BlockHash,
Expand Down
2 changes: 2 additions & 0 deletions app/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ pub enum BlockErrorBlockTypes {
LastFinalized,
#[error("Failed to retrieve the head block")]
Head,
#[error("Failed to retrieve the previous head block")]
PreviousHead,
#[error("Failed to retrieve the block with hash `{0}`")]
GenericHash(String),
#[error("Failed to retrieve the genesis block")]
Expand Down
24 changes: 24 additions & 0 deletions app/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use std::net::SocketAddr;
use std::sync::Arc;
use store::ItemStore;
use tokio::sync::Mutex;
use tracing::{error, trace};
use types::MainnetEthSpec;

#[derive(Debug, Clone, Deserialize)]
Expand Down Expand Up @@ -256,6 +257,29 @@ async fn http_req_json_rpc<BI: BlockIndex, CM: ChainManager<BI>>(
)
}
}
"get_head_block" => {
match miner.get_head() {
Ok(head) => Response::builder().status(hyper::StatusCode::OK).body(
JsonRpcResponseV1 {
result: Some(json!(head)),
error: None,
id,
}
.into(),
),
Err(e) => {
error!("{}", e.to_string());
Response::builder().status(hyper::StatusCode::OK).body(
JsonRpcResponseV1 {
result: None,
error: Some(JsonRpcErrorV1::block_not_found()),
id,
}
.into(),
)
}
}
}
// "getaccumulatedfees" => {
// let args = params.get();
// let block_hash;
Expand Down
17 changes: 14 additions & 3 deletions app/src/store.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use crate::{block::*, error::Error};
use crate::{
block::*,
error::{BlockErrorBlockTypes, Error},
};
use bitcoin::CompactTarget;
use ethers_core::types::U256;
use serde_derive::{Deserialize, Serialize};
use ssz::{Decode, Encode};
use ssz_derive::{Decode, Encode};
use std::{fs, marker::PhantomData, path::PathBuf};
use std::{fs, marker::PhantomData, path::PathBuf, thread::current};
use store::{get_key_for_col, ItemStore, KeyValueStoreOp, LevelDB, MemoryStore};
use strum::{EnumString, IntoStaticStr};
use tracing::*;
Expand Down Expand Up @@ -104,7 +107,15 @@ impl<DB: ItemStore<MainnetEthSpec>> Storage<MainnetEthSpec, DB> {
}

pub fn get_head(&self) -> Result<Option<BlockRef>, Error> {
self.get_ref(HEAD_KEY.as_bytes())
self.get_ref(HEAD_KEY.as_bytes()).map_err(|_| Error::ChainError(BlockErrorBlockTypes::Head.into()))
}

fn get_previous_head(&self, head_ref: &BlockRef) -> Result<Option<BlockRef>, Error> {
let previous_head = self.get_block(&head_ref.hash)?.unwrap().message.parent_hash;
Ok(Some(BlockRef {
hash: previous_head,
height: head_ref.height - 1,
}))
}

pub fn get_latest_pow_block(&self) -> Result<Option<BlockRef>, Error> {
Expand Down

0 comments on commit 9c9673e

Please sign in to comment.