Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐞✋ feat: add cellbase maturity verification #367

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions chain/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,9 @@ impl<CI: ChainIndex + 'static> ChainService<CI> {
.map(|x| resolve_transaction(x, &mut seen_inputs, &cell_provider))
.collect();

let cell_set = { chain_state.cell_set().inner.clone() };
let cellbase_maturity = { self.shared.consensus().cellbase_maturity() };

match txs_verifier.verify(
chain_state.mut_txs_verify_cache(),
&resolved,
Expand All @@ -479,6 +482,8 @@ impl<CI: ChainIndex + 'static> ChainService<CI> {
consensus: self.shared.consensus(),
},
b.header().number(),
cell_set,
cellbase_maturity,
) {
Ok(_) => {
cell_set_diff.push_new(b);
Expand Down
2 changes: 1 addition & 1 deletion chain/src/tests/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub(crate) fn start_chain(
) -> (ChainController, Shared<ChainKVStore<MemoryKeyValueDB>>) {
let builder = SharedBuilder::<MemoryKeyValueDB>::new();
let shared = builder
.consensus(consensus.unwrap_or_else(Default::default))
.consensus(consensus.unwrap_or_else(|| Consensus::default().set_cellbase_maturity(0)))
.build();

let notify = NotifyService::default().start::<&str>(None);
Expand Down
2 changes: 1 addition & 1 deletion shared/src/cell_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl CellProvider for CellSetDiff {

#[derive(Default, Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct CellSet {
inner: FnvHashMap<H256, TransactionMeta>,
pub inner: FnvHashMap<H256, TransactionMeta>,
}

impl CellSet {
Expand Down
10 changes: 8 additions & 2 deletions shared/src/chain_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,14 @@ impl<CI: ChainIndex> ChainState<CI> {
match ret {
Some(cycles) => Ok(cycles),
None => {
let cycles =
TransactionVerifier::new(&rtx, &self, self.tip_number()).verify(max_cycles)?;
let cycles = TransactionVerifier::new(
&rtx,
&self,
self.tip_number(),
&self.cell_set.inner,
self.consensus().cellbase_maturity,
)
.verify(max_cycles)?;
// write cache
self.txs_verify_cache.borrow_mut().insert(tx_hash, cycles);
Ok(cycles)
Expand Down
5 changes: 5 additions & 0 deletions spec/src/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,11 @@ impl Consensus {
self
}

pub fn set_cellbase_maturity(mut self, cellbase_maturity: usize) -> Self {
self.cellbase_maturity = cellbase_maturity;
self
}

pub fn genesis_block(&self) -> &Block {
&self.genesis_block
}
Expand Down
4 changes: 3 additions & 1 deletion sync/src/tests/relayer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,9 @@ fn setup_node(
.timestamp(unix_time_as_millis())
.difficulty(U256::from(1000u64)),
);
let consensus = Consensus::default().set_genesis_block(block.clone());
let consensus = Consensus::default()
.set_genesis_block(block.clone())
.set_cellbase_maturity(0);

let shared = SharedBuilder::<MemoryKeyValueDB>::new()
.consensus(consensus)
Expand Down
21 changes: 15 additions & 6 deletions verification/src/block_verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ use ckb_core::cell::ResolvedTransaction;
use ckb_core::header::Header;
use ckb_core::transaction::{Capacity, CellInput, Transaction};
use ckb_core::Cycle;
use ckb_core::{block::Block, BlockNumber};
use ckb_core::{block::Block, transaction_meta::TransactionMeta, BlockNumber};
use ckb_traits::{BlockMedianTimeContext, ChainProvider};
use fnv::FnvHashSet;
use fnv::{FnvHashMap, FnvHashSet};
use lru_cache::LruCache;
use numext_fixed_hash::H256;
use numext_fixed_uint::U256;
Expand Down Expand Up @@ -346,13 +346,16 @@ impl TransactionsVerifier {
TransactionsVerifier { max_cycles }
}

#[allow(clippy::too_many_arguments)]
pub fn verify<M>(
&self,
txs_verify_cache: &mut LruCache<H256, Cycle>,
resolved: &[ResolvedTransaction],
block_reward: Capacity,
block_median_time_context: M,
tip_number: BlockNumber,
cell_set: FnvHashMap<H256, TransactionMeta>,
cellbase_maturity: usize,
) -> Result<(), Error>
where
M: BlockMedianTimeContext + Sync,
Expand All @@ -377,10 +380,16 @@ impl TransactionsVerifier {
.map_err(|e| Error::Transactions((index, e)))
.map(|_| (None, *cycles))
} else {
TransactionVerifier::new(&tx, &block_median_time_context, tip_number)
.verify(self.max_cycles)
.map_err(|e| Error::Transactions((index, e)))
.map(|cycles| (Some(tx.transaction.hash()), cycles))
TransactionVerifier::new(
&tx,
&block_median_time_context,
tip_number,
&cell_set,
cellbase_maturity,
)
.verify(self.max_cycles)
.map_err(|e| Error::Transactions((index, e)))
.map(|cycles| (Some(tx.transaction.hash()), cycles))
}
})
.collect::<Result<Vec<_>, _>>()?;
Expand Down
1 change: 1 addition & 0 deletions verification/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,5 @@ pub enum TransactionError {
Immature,
/// Invalid ValidSince flags
InvalidValidSince,
CellbaseImmaturity,
}
57 changes: 57 additions & 0 deletions verification/src/transaction_verifier.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
use crate::error::TransactionError;
use ckb_core::transaction::{Capacity, Transaction, TX_VERSION};
use ckb_core::transaction_meta::TransactionMeta;
use ckb_core::{
cell::{CellMeta, CellStatus, ResolvedTransaction},
BlockNumber, Cycle,
};
use ckb_script::TransactionScriptsVerifier;
use ckb_traits::BlockMedianTimeContext;
use fnv::FnvHashMap;
use lru_cache::LruCache;
use numext_fixed_hash::H256;
use occupied_capacity::OccupiedCapacity;
use std::cell::RefCell;
use std::collections::HashSet;
Expand All @@ -15,6 +18,7 @@ pub struct TransactionVerifier<'a, M> {
pub version: VersionVerifier<'a>,
pub null: NullVerifier<'a>,
pub empty: EmptyVerifier<'a>,
pub maturity: MaturityVerifier<'a>,
pub capacity: CapacityVerifier<'a>,
pub duplicate_inputs: DuplicateInputsVerifier<'a>,
pub inputs: InputVerifier<'a>,
Expand All @@ -30,11 +34,19 @@ where
rtx: &'a ResolvedTransaction,
median_time_context: &'a M,
tip_number: BlockNumber,
cell_set: &'a FnvHashMap<H256, TransactionMeta>,
cellbase_maturity: usize,
) -> Self {
TransactionVerifier {
version: VersionVerifier::new(&rtx.transaction),
null: NullVerifier::new(&rtx.transaction),
empty: EmptyVerifier::new(&rtx.transaction),
maturity: MaturityVerifier::new(
&rtx.transaction,
tip_number,
cell_set,
cellbase_maturity,
),
duplicate_inputs: DuplicateInputsVerifier::new(&rtx.transaction),
script: ScriptVerifier::new(rtx),
capacity: CapacityVerifier::new(rtx),
Expand All @@ -47,6 +59,7 @@ where
self.version.verify()?;
self.empty.verify()?;
self.null.verify()?;
self.maturity.verify()?;
self.inputs.verify()?;
self.capacity.verify()?;
self.duplicate_inputs.verify()?;
Expand Down Expand Up @@ -140,6 +153,50 @@ impl<'a> EmptyVerifier<'a> {
}
}

pub struct MaturityVerifier<'a> {
transaction: &'a Transaction,
tip_number: BlockNumber,
cell_set: &'a FnvHashMap<H256, TransactionMeta>,
cellbase_maturity: usize,
}

impl<'a> MaturityVerifier<'a> {
pub fn new(
transaction: &'a Transaction,
tip_number: BlockNumber,
cell_set: &'a FnvHashMap<H256, TransactionMeta>,
cellbase_maturity: usize,
) -> Self {
MaturityVerifier {
transaction,
tip_number,
cell_set,
cellbase_maturity,
}
}

pub fn verify(&self) -> Result<(), TransactionError> {
let immature_spend = self.transaction.inputs().iter().any(|input| {
match self.cell_set.get(&input.previous_output.hash) {
Some(ref meta)
if meta.is_cellbase()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not every cell outpoint in cellbase need to be maturity, I think we need more discussion on this?

Consider the UDT tx fee design, maybe we should leave more rooms for upper UDT contracts?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not every cell outpoint in cellbase need to be maturity, I think we need more discussion on this?

Consider the UDT tx fee design, maybe we should leave more rooms for upper UDT contracts?

I think it should be because of the block confirmation. The UDT tx fee would be included in the cellbase?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not decide yet.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seem your implement is correct due to the explanation of maturity in this link https://bitcoin.stackexchange.com/questions/1991/what-is-the-block-maturation-time

Anyway please hold this PR until #372 merged, 372 introduce few refactoring about tx verification.

&& self.tip_number
< meta.block_number() + self.cellbase_maturity as u64 =>
{
true
}
_ => false,
}
});

if immature_spend {
Err(TransactionError::CellbaseImmaturity)
} else {
Ok(())
}
}
}

pub struct DuplicateInputsVerifier<'a> {
transaction: &'a Transaction,
}
Expand Down