Skip to content
This repository has been archived by the owner on Nov 9, 2022. It is now read-only.

feat: optimize Godwoken finality mechanism #132

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions c-uint256-tests/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ fn main() {
.file("../c/rust-binding/uint256_wrapper.c")
.static_flag(true)
.flag("-O3")
.flag("-Wl,-static")
.flag("-Wl,--gc-sections")
// .flag("-Wl,-static")
keroro520 marked this conversation as resolved.
Show resolved Hide resolved
// .flag("-Wl,--gc-sections")
.include("../c/")
.flag("-Wall")
.flag("-Werror")
.flag("-Wno-unused-parameter")
.flag("-Wno-nonnull")
.flag("-Wno-nonnull-compare")
// .flag("-Wno-nonnull-compare")
.flag("-Wno-unused-function")
.define("__SHARED_LIBRARY__", None)
.compile("c-uint256.a");
Expand Down
16 changes: 8 additions & 8 deletions contracts/Cargo.lock

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

14 changes: 9 additions & 5 deletions contracts/custodian-lock/src/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ use crate::ckb_std::{
high_level::load_script, high_level::load_witness_args,
};
use gw_types::{
core::ScriptHashType,
core::{ScriptHashType, Timepoint},
packed::{
CustodianLockArgs, CustodianLockArgsReader, UnlockCustodianViaRevertWitness,
UnlockCustodianViaRevertWitnessReader,
},
prelude::*,
};
use gw_utils::finality::is_finalized;
use gw_utils::gw_types;

use crate::error::Error;
Expand Down Expand Up @@ -58,11 +59,14 @@ pub fn main() -> Result<(), Error> {
Some(state) => state,
None => return Err(Error::RollupCellNotFound),
};
let config = load_rollup_config(&global_state.rollup_config_hash().unpack())?;

let deposit_block_number: u64 = lock_args.deposit_block_number().unpack();
let last_finalized_block_number: u64 = global_state.last_finalized_block_number().unpack();

if deposit_block_number <= last_finalized_block_number {
let is_finalized = is_finalized(
&config,
&global_state,
&Timepoint::from_full_value(lock_args.deposit_block_number().unpack()),
);
if is_finalized {
// this custodian lock is already finalized, rollup will handle the logic
return Ok(());
}
Expand Down
4 changes: 2 additions & 2 deletions contracts/gw-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ edition = "2018"

[dependencies]
ckb-std = "0.9.0"
gw-types = { git = "https://github.com/nervosnetwork/godwoken.git", rev = "91c324544424292b4d715ce376d31bc45aa3cb5d", default-features = false }
gw-common = { git = "https://github.com/nervosnetwork/godwoken.git", rev = "91c324544424292b4d715ce376d31bc45aa3cb5d", default-features = false }
gw-types = { git = "https://github.com/keroro520/godwoken.git", branch = "new-finality-rule-based-on-timestamp", default-features = false }
gw-common = { git = "https://github.com/keroro520/godwoken.git", branch = "new-finality-rule-based-on-timestamp", default-features = false }
2 changes: 2 additions & 0 deletions contracts/gw-utils/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ pub enum Error {
DuplicatedScriptHash = 42,
RegistryAddressNotFound = 43,
DuplicatedRegistryAddress = 44,
NotFinalized = 45,
HeaderDepsNotFound = 46,
}

impl From<SysError> for Error {
Expand Down
72 changes: 72 additions & 0 deletions contracts/gw-utils/src/finality.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//! # How to check finality
//!
//! To determine a block-number-based timepoint is finalized, compare it with
//! `prev_global_state.block.count - 1 + FINALITY_REQUIREMENT`.
//!
//! To determine a timestamp-based timepoint is finalized,
//! - If prev_global_state.last_finalized_block_number is also timestamp-based,
//! compare them directly;
//! - Otherwise, we know it is switching versions, so the corresponding entity
//! is surely not finalized.

use ckb_std::{
ckb_constants::Source,
debug,
high_level::{load_header, QueryIter},
};
use gw_types::core::Timepoint;
use gw_types::packed::{GlobalState, RollupConfig};
use gw_types::prelude::{Entity, Unpack};

// 7 * 24 * 60 * 60 / 16800 * 1000 = 36000
keroro520 marked this conversation as resolved.
Show resolved Hide resolved
const BLOCK_INTERVAL_IN_MILLISECONDS: u64 = 36000;

pub fn is_finalized(
rollup_config: &RollupConfig,
prev_global_state: &GlobalState,
timepoint: &Timepoint,
) -> bool {
match timepoint {
Timepoint::BlockNumber(block_number) => {
is_block_number_finalized(rollup_config, prev_global_state, *block_number)
}
Timepoint::Timestamp(timestamp) => is_timestamp_finalized(prev_global_state, *timestamp),
}
}

pub fn is_timestamp_finalized(prev_global_state: &GlobalState, timestamp: u64) -> bool {
match Timepoint::from_full_value(prev_global_state.last_finalized_block_number().unpack()) {
Timepoint::BlockNumber(_) => {
debug!("[is_timestamp_finalized] switching version, prev_global_state.last_finalized_block_number is number-based");
false
}
Timepoint::Timestamp(finalized) => timestamp <= finalized,
}
}

pub fn is_block_number_finalized(
rollup_config: &RollupConfig,
prev_global_state: &GlobalState,
block_number: u64,
) -> bool {
let finality_blocks: u64 = rollup_config.finality_blocks().unpack();
let tip_number: u64 = prev_global_state.block().count().unpack().saturating_sub(1);
block_number.saturating_add(finality_blocks) <= tip_number
}

pub fn finality_as_duration(rollup_config: &RollupConfig) -> u64 {
keroro520 marked this conversation as resolved.
Show resolved Hide resolved
let finality_blocks = rollup_config.finality_blocks().unpack();
finality_blocks.saturating_mul(BLOCK_INTERVAL_IN_MILLISECONDS)
}

/// Obtain the max timestamp of the header-deps
pub fn obtain_max_timestamp_of_header_deps() -> Option<u64> {
keroro520 marked this conversation as resolved.
Show resolved Hide resolved
let mut buf = [0u8; 8];
QueryIter::new(load_header, Source::HeaderDep)
.map(|header| {
buf.copy_from_slice(header.raw().timestamp().as_slice());
let timestamp: u64 = u64::from_le_bytes(buf);
timestamp
})
.max()
}
1 change: 1 addition & 0 deletions contracts/gw-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub use gw_types;

pub mod cells;
pub mod error;
pub mod finality;
pub mod signature;
pub mod type_id;
pub mod withdrawal;
15 changes: 10 additions & 5 deletions contracts/stake-lock/src/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ use crate::ckb_std::{
};

use gw_utils::cells::{
rollup::{search_rollup_cell, search_rollup_state},
rollup::{load_rollup_config, search_rollup_cell, search_rollup_state},
utils::search_lock_hash,
};
use gw_utils::finality::is_finalized;
use gw_utils::gw_types;

use gw_types::{
core::Timepoint,
packed::{StakeLockArgs, StakeLockArgsReader},
prelude::*,
};
Expand Down Expand Up @@ -52,12 +54,15 @@ pub fn main() -> Result<(), Error> {
// Unlock by User
// read global state from rollup cell in deps
if let Some(global_state) = search_rollup_state(&rollup_type_hash, Source::CellDep)? {
let stake_block_number: u64 = lock_args.stake_block_number().unpack();
let last_finalized_block_number: u64 = global_state.last_finalized_block_number().unpack();

// 1. check if stake_block_number is finalized
// 2. check if owner_lock_hash exists in input cells
if stake_block_number <= last_finalized_block_number
let config = load_rollup_config(&global_state.rollup_config_hash().unpack())?;
let is_finalized = is_finalized(
&config,
&global_state,
&Timepoint::from_full_value(lock_args.stake_block_number().unpack()),
);
if is_finalized
&& search_lock_hash(&lock_args.owner_lock_hash().unpack(), Source::Input).is_some()
{
return Ok(());
Expand Down
2 changes: 1 addition & 1 deletion contracts/state-validator/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ pub struct WithdrawalRequest {
}
pub struct BlockContext {
pub number: u64,
pub finalized_number: u64,
pub timestamp: u64,
pub block_hash: H256,
pub rollup_type_hash: H256,
pub prev_account_root: H256,
pub post_version: u8,
}
19 changes: 15 additions & 4 deletions contracts/state-validator/src/verifications/challenge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use gw_types::{
packed::{GlobalState, RollupConfig},
prelude::*,
};
use gw_utils::finality::{is_block_number_finalized, is_timestamp_finalized};
use gw_utils::{
cells::lock_cells::{collect_burn_cells, find_challenge_cell},
ckb_std::{ckb_constants::Source, debug},
Expand Down Expand Up @@ -38,13 +39,23 @@ pub fn verify_enter_challenge(
// check that challenge target is exists
let witness = args.witness();
let challenged_block = witness.raw_l2block();

// check challenged block isn't finazlied
if prev_global_state.last_finalized_block_number().unpack()
>= challenged_block.number().unpack()
{
debug!("enter challenge finalized block error");
let post_version: u8 = post_global_state.version().into();
let is_block_finalized = if post_version < 2 {
is_block_number_finalized(
config,
post_global_state,
challenged_block.number().unpack(),
)
} else {
is_timestamp_finalized(post_global_state, challenged_block.timestamp().unpack())
};
if is_block_finalized {
debug!("cannot challenge a finalized block");
return Err(Error::InvalidChallengeTarget);
}

let valid = {
let merkle_proof = CompiledMerkleProof(witness.block_proof().unpack());
let leaves = vec![(
Expand Down
23 changes: 17 additions & 6 deletions contracts/state-validator/src/verifications/revert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ use gw_common::{
H256,
};
use gw_types::{
core::Status,
core::{Status, Timepoint},
packed::{BlockMerkleState, Byte32, GlobalState, RawL2Block, RollupConfig},
prelude::*,
};
use gw_utils::finality::{finality_as_duration, obtain_max_timestamp_of_header_deps};
use gw_utils::gw_types;
use gw_utils::{
cells::{
Expand Down Expand Up @@ -247,12 +248,22 @@ fn check_reverted_blocks(
};
let account_merkle_state = reverted_blocks[0].prev_account();
let tip_block_hash = reverted_blocks[0].parent_block_hash();
let last_finalized_block_number = {
let number: u64 = reverted_blocks[0].number().unpack();
number
let post_version: u8 = post_global_state.version().into();
let last_finalized = if post_version < 2 {
let tip_number: u64 = reverted_blocks[0].number().unpack();
let finalized_number = tip_number
.saturating_sub(1)
.saturating_sub(config.finality_blocks().unpack())
.saturating_sub(config.finality_blocks().unpack());
Timepoint::from_block_number(finalized_number)
} else {
let l1_timestamp = match obtain_max_timestamp_of_header_deps() {
keroro520 marked this conversation as resolved.
Show resolved Hide resolved
Some(timestamp) => timestamp,
None => return Err(Error::HeaderDepsNotFound),
};
let finalized_timestamp = l1_timestamp.saturating_sub(finality_as_duration(&config));
Timepoint::from_timestamp(finalized_timestamp)
};

let new_tip_block = revert_args.new_tip_block();
if new_tip_block.hash() != tip_block_hash.as_slice() {
debug!("[verify revert] reverted new_tip_block doesn't match");
Expand All @@ -269,7 +280,7 @@ fn check_reverted_blocks(
.block(block_merkle_state)
.tip_block_hash(tip_block_hash.to_entity())
.tip_block_timestamp(tip_block_timestamp.to_entity())
.last_finalized_block_number(last_finalized_block_number.pack())
.last_finalized_block_number(last_finalized.full_value().pack())
.reverted_block_root(reverted_block_root)
.status(status.into())
.build()
Expand Down
Loading