Skip to content

Commit

Permalink
implements rooch finality
Browse files Browse the repository at this point in the history
  • Loading branch information
baichuan3 committed Dec 1, 2024
1 parent 32aaaaa commit 1667f07
Show file tree
Hide file tree
Showing 28 changed files with 774 additions and 1,438 deletions.
3 changes: 0 additions & 3 deletions Cargo.lock

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

6 changes: 6 additions & 0 deletions crates/rooch-db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use rooch_store::{
RoochStore, META_SEQUENCER_INFO_COLUMN_FAMILY_NAME, STATE_CHANGE_SET_COLUMN_FAMILY_NAME,
TRANSACTION_COLUMN_FAMILY_NAME, TX_SEQUENCE_INFO_MAPPING_COLUMN_FAMILY_NAME,
};
use rooch_types::finality_block::L2BlockRef;
use rooch_types::indexer::state::{
collect_revert_object_change_ids, handle_revert_object_change, IndexerObjectStateChangeSet,
IndexerObjectStatesIndexGenerator,
Expand Down Expand Up @@ -409,4 +410,9 @@ impl RoochDB {
// TODO repair the changeset sync and indexer store
Ok((issues, fixed))
}

//TODO implements this after proposer generate blocks
pub fn l2_block_ref_by_number(&self, block_number: u64) -> Result<L2BlockRef> {
return Ok(L2BlockRef::default());
}
}
5 changes: 0 additions & 5 deletions crates/rooch-finality/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,24 @@ tracing = { workspace = true }
prometheus = { workspace = true }
function_name = { workspace = true }
tonic = { workspace = true, features = ["codegen", "prost"] }
#tonic = { version = "0.12.3", features = ["codegen", "prost"]}
prost = { workspace = true }
prost-types = { workspace = true }
#protobuf = { workspace = true }

moveos-types = { workspace = true }
moveos-eventbus = { workspace = true }
accumulator = { workspace = true }
metrics = { workspace = true }
raw-store = { workspace = true }

rooch-types = { workspace = true }
rooch-store = { workspace = true }
rooch-config = { workspace = true }
rooch-db = { workspace = true }
rooch-genesis = { workspace = true }
rooch-event = { workspace = true }

[build-dependencies]
prost-build = { workspace = true }
prost-types = { workspace = true }
protox = "0.7.1"
#tonic-build = { version = "0.12.3", features = [ "prost" ]}
tonic-build = { workspace = true, features = [ "prost" ]}

#[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
Expand Down
8 changes: 4 additions & 4 deletions crates/rooch-finality/build.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
//! A build script generating rust types from protobuf definitions.
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

//! A build script generating rust types from protobuf definitions.
use prost_types::FileDescriptorSet;
use std::collections::HashSet;

static OUT_DIR: &str = "src/proto";
const PROTO_FILES: &[&str] = &[
Expand All @@ -25,6 +24,7 @@ fn protox_compile() -> FileDescriptorSet {
protox::compile(PROTO_FILES, INCLUDES).expect("protox failed to build")
}

#[allow(dead_code)]
// #[cfg(not(feature = "tonic"))]
fn prost_build(fds: FileDescriptorSet) {
let mut config = prost_build::Config::new();
Expand All @@ -43,7 +43,7 @@ fn tonic_build(fds: FileDescriptorSet) {
let mut prost_config = prost_build::Config::new();
prost_config.enable_type_names();

let mut tonic_config = tonic_build::configure()
let tonic_config = tonic_build::configure()
// .include_file("mod.rs")
.build_client(true)
.build_server(false)
Expand Down
146 changes: 146 additions & 0 deletions crates/rooch-finality/src/actor/finality.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

use std::ops::Deref;
use std::sync::Arc;
use std::time::SystemTime;

use crate::finality::finalizer::{Config, Finalizer, FinalizerL1Mock};
use crate::messages::FinalityMessage;
use crate::metrics::FinalityMetrics;
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use coerce::actor::{context::ActorContext, message::Handler, Actor, LocalActorRef};
use function_name::named;
use moveos_eventbus::bus::EventData;
use prometheus::Registry;
use rooch_db::RoochDB;
use rooch_event::actor::{EventActor, EventActorSubscribeMessage};
use rooch_event::event::ServiceStatusEvent;
use rooch_types::finality_block::Block;
use rooch_types::service_status::ServiceStatus;
use tracing::info;

pub struct FinalityActor {
// rooch_store: RoochStore,
finalizer: Finalizer,
rooch_db: RoochDB,
service_status: ServiceStatus,
metrics: Arc<FinalityMetrics>,
event_actor: Option<LocalActorRef<EventActor>>,
}

impl FinalityActor {
pub fn new(
rooch_db: RoochDB,
service_status: ServiceStatus,
registry: &Registry,
event_actor: Option<LocalActorRef<EventActor>>,
) -> Result<Self, anyhow::Error> {
let babylon_finality_gadget_rpc_str = "";
let config = Config {
babylon_finality_gadget_rpc: babylon_finality_gadget_rpc_str.to_string(),
};
//TODO implements finalize L1 service
let finalizer_L1_Mock = Arc::new(FinalizerL1Mock::default());
let finalizer = Finalizer::new(&config, finalizer_L1_Mock, rooch_db.clone())
.map_err(|e| anyhow!(format!("New finality actor error: {:?}", e)))?;

Ok(Self {
finalizer,
rooch_db,
service_status,
metrics: Arc::new(FinalityMetrics::new(registry)),
event_actor,
})
}

pub async fn subscribe_event(
&self,
event_actor_ref: LocalActorRef<EventActor>,
executor_actor_ref: LocalActorRef<FinalityActor>,
) {
let service_status_event = ServiceStatusEvent::default();
let actor_subscribe_message = EventActorSubscribeMessage::new(
service_status_event,
"finality".to_string(),
Box::new(executor_actor_ref),
);
let _ = event_actor_ref.send(actor_subscribe_message).await;
}

#[named]
pub async fn finality(&mut self, block: Block) -> Result<()> {
let fn_name = function_name!();
let _timer = self
.metrics
.finality_latency_seconds
.with_label_values(&[fn_name])
.start_timer();

// match self.service_status {
// ServiceStatus::ReadOnlyMode => {
// return Err(anyhow::anyhow!("The service is in read-only mode"));
// }
// ServiceStatus::DateImportMode => {
// if !tx_data.is_l1_block() && !tx_data.is_l1_tx() {
// return Err(anyhow::anyhow!(
// "The service is in date import mode, only allow l1 block and l1 tx"
// ));
// }
// }
// ServiceStatus::Maintenance => {
// // Only the sequencer can send transactions in maintenance mode
// if let Some(sender) = tx_data.sender() {
// if sender != self.sequencer_key.public().rooch_address()? {
// return Err(anyhow::anyhow!("The service is in maintenance mode"));
// }
// } else {
// return Err(anyhow::anyhow!("The service is in maintenance mode"));
// }
// }
// _ => {}
// }

let now = SystemTime::now();
let _tx_timestamp = now.duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as u64;

self.finalizer.try_finalize().await?;
info!(
"rooch finality finalize block_hash: {} block_number: {:?}",
block.block_hash, block.block_height
);

Ok(())
}
}

#[async_trait]
impl Actor for FinalityActor {
async fn started(&mut self, ctx: &mut ActorContext) {
let local_actor_ref: LocalActorRef<Self> = ctx.actor_ref();
if let Some(event_actor) = self.event_actor.clone() {
let _ = self.subscribe_event(event_actor, local_actor_ref).await;
}
}
}

#[async_trait]
impl Handler<FinalityMessage> for FinalityActor {
async fn handle(&mut self, msg: FinalityMessage, _ctx: &mut ActorContext) -> Result<()> {
self.finality(msg.block).await
}
}

#[async_trait]
impl Handler<EventData> for FinalityActor {
async fn handle(&mut self, msg: EventData, _ctx: &mut ActorContext) -> Result<()> {
if let Ok(service_status_event) = msg.data.downcast::<ServiceStatusEvent>() {
let service_status = service_status_event.deref().status;
tracing::warn!("FinalityActor set self status to {:?}", service_status);
self.service_status = service_status;
}

Ok(())
}
}
2 changes: 1 addition & 1 deletion crates/rooch-finality/src/actor/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

pub mod sequencer;
pub mod finality;
Loading

0 comments on commit 1667f07

Please sign in to comment.