Skip to content

Commit

Permalink
feat: move valid_since field from tx to CellInput
Browse files Browse the repository at this point in the history
  • Loading branch information
jjyr committed Apr 11, 2019
1 parent 04d7dde commit 644f7aa
Show file tree
Hide file tree
Showing 35 changed files with 631 additions and 300 deletions.
8 changes: 4 additions & 4 deletions benches/benches/process_block.rs
Expand Up @@ -134,15 +134,15 @@ fn new_chain() -> (
TempDir,
) {
let cellbase = TransactionBuilder::default()
.input(CellInput::new_cellbase_input(0))
.input(CellInput::new_cellbase_input(0, 0))
.output(CellOutput::new(0, vec![], Script::default(), None))
.build();

// create genesis block with 100 tx
let commit_transactions: Vec<Transaction> = (0..100)
.map(|i| {
TransactionBuilder::default()
.input(CellInput::new(OutPoint::null(), vec![]))
.input(CellInput::new(OutPoint::null(), 0, vec![]))
.output(CellOutput::new(
50000,
vec![i],
Expand Down Expand Up @@ -183,7 +183,7 @@ fn gen_block(blocks: &mut Vec<Block>, parent_index: usize) {
);

let cellbase = TransactionBuilder::default()
.input(CellInput::new_cellbase_input(number))
.input(CellInput::new_cellbase_input(number, 0))
.output(CellOutput::new(0, vec![], Script::default(), None))
.build();

Expand Down Expand Up @@ -231,6 +231,6 @@ fn create_transaction(hash: H256) -> Transaction {
Script::always_success(),
None,
))
.input(CellInput::new(OutPoint::new(hash, 0), vec![]))
.input(CellInput::new(OutPoint::new(hash, 0), 0, vec![]))
.build()
}
50 changes: 22 additions & 28 deletions chain/src/chain.rs
Expand Up @@ -16,7 +16,7 @@ use ckb_shared::index::ChainIndex;
use ckb_shared::shared::Shared;
use ckb_shared::store::StoreBatch;
use ckb_traits::{BlockMedianTimeContext, ChainProvider};
use ckb_verification::{BlockContext, BlockVerifier, TransactionsVerifier, Verifier};
use ckb_verification::{BlockVerifier, TransactionsVerifier, Verifier};
use crossbeam_channel::{self, select, Receiver, Sender};
use failure::Error as FailureError;
use faketime::unix_time_as_millis;
Expand Down Expand Up @@ -106,29 +106,28 @@ struct ForkContext<'a, CI> {
}

impl<'a, CI: ChainIndex> ForkContext<'a, CI> {
fn get_header(&self, hash: &H256) -> Option<Header> {
self.fork_blocks
fn get_header(&self, number: BlockNumber) -> Option<Header> {
match self
.fork_blocks
.iter()
.find(|b| &b.header().hash() == hash)
.map_or_else(
|| self.store.get_header(hash),
|b| Some(b.header().to_owned()),
)
.find(|b| b.header().number() == number)
{
Some(block) => Some(block.header().to_owned()),
None => self
.store
.get_block_hash(number)
.and_then(|hash| self.store.get_header(&hash)),
}
}
}

impl<'a, CI: ChainIndex> BlockMedianTimeContext for ForkContext<'a, CI> {
fn block_count(&self) -> u32 {
self.consensus.median_time_block_count() as u32
}

fn timestamp(&self, hash: &H256) -> Option<u64> {
self.get_header(hash).map(|header| header.timestamp())
fn median_block_count(&self) -> u64 {
self.consensus.median_time_block_count() as u64
}

fn parent_hash(&self, hash: &H256) -> Option<H256> {
self.get_header(hash)
.map(|header| header.parent_hash().to_owned())
fn timestamp(&self, number: BlockNumber) -> Option<u64> {
self.get_header(number).map(|header| header.timestamp())
}
}

Expand Down Expand Up @@ -465,16 +464,6 @@ impl<CI: ChainIndex + 'static> ChainService<CI> {
let block_cp = BlockCellProvider::new(b);
let cell_provider = OverlayCellProvider::new(&block_cp, &cell_set_diff_cp);

let block_context = BlockContext {
tip_number: b.header().number(),
tip_hash: b.header().hash(),
block_median_time_context: ForkContext {
fork_blocks: &fork.attached_blocks,
store: Arc::clone(self.shared.store()),
consensus: self.shared.consensus(),
},
};

let resolved: Vec<ResolvedTransaction> = b
.commit_transactions()
.iter()
Expand All @@ -485,7 +474,12 @@ impl<CI: ChainIndex + 'static> ChainService<CI> {
chain_state.mut_txs_verify_cache(),
&resolved,
self.shared.block_reward(b.header().number()),
block_context,
ForkContext {
fork_blocks: &fork.attached_blocks,
store: Arc::clone(self.shared.store()),
consensus: self.shared.consensus(),
},
b.header().number(),
) {
Ok(_) => {
cell_set_diff.push_new(b);
Expand Down
11 changes: 7 additions & 4 deletions chain/src/tests/basic.rs
Expand Up @@ -2,7 +2,7 @@ use crate::tests::util::{create_transaction, gen_block, start_chain};
use ckb_chain_spec::consensus::Consensus;
use ckb_core::block::Block;
use ckb_core::block::BlockBuilder;
use ckb_core::cell::{CellProvider, CellStatus};
use ckb_core::cell::{CellMeta, CellProvider, CellStatus};
use ckb_core::header::HeaderBuilder;
use ckb_core::script::Script;
use ckb_core::transaction::{CellInput, CellOutput, OutPoint, TransactionBuilder};
Expand All @@ -14,7 +14,7 @@ use std::sync::Arc;
#[test]
fn test_genesis_transaction_spend() {
let tx = TransactionBuilder::default()
.input(CellInput::new(OutPoint::null(), Default::default()))
.input(CellInput::new(OutPoint::null(), 0, Default::default()))
.outputs(vec![
CellOutput::new(
100_000_000,
Expand Down Expand Up @@ -173,7 +173,10 @@ fn test_transaction_spend_in_same_block() {
.chain_state()
.lock()
.cell(&OutPoint::new(tx2_hash, 0)),
CellStatus::Live(tx2_output)
CellStatus::Live(CellMeta {
cell_output: tx2_output,
block_number: Some(4)
})
);
}

Expand Down Expand Up @@ -344,7 +347,7 @@ fn test_transaction_conflict_in_different_blocks() {
#[test]
fn test_genesis_transaction_fetch() {
let tx = TransactionBuilder::default()
.input(CellInput::new(OutPoint::null(), Default::default()))
.input(CellInput::new(OutPoint::null(), 0, Default::default()))
.outputs(vec![
CellOutput::new(
100_000_000,
Expand Down
4 changes: 2 additions & 2 deletions chain/src/tests/util.rs
Expand Up @@ -35,7 +35,7 @@ pub(crate) fn start_chain(

fn create_cellbase(number: BlockNumber) -> Transaction {
TransactionBuilder::default()
.input(CellInput::new_cellbase_input(number))
.input(CellInput::new_cellbase_input(number, 0))
.output(CellOutput::new(
5000,
vec![],
Expand Down Expand Up @@ -81,6 +81,6 @@ pub(crate) fn create_transaction(parent: H256, unique_data: u8) -> Transaction {
Script::always_success(),
None,
))
.input(CellInput::new(OutPoint::new(parent, 0), vec![]))
.input(CellInput::new(OutPoint::new(parent, 0), 0, vec![]))
.build()
}
38 changes: 25 additions & 13 deletions core/src/cell.rs
Expand Up @@ -6,10 +6,16 @@ use numext_fixed_hash::H256;
use std::iter::Chain;
use std::slice;

#[derive(Clone, PartialEq, Debug)]
pub struct CellMeta {
pub cell_output: CellOutput,
pub block_number: Option<u64>,
}

#[derive(Clone, PartialEq, Debug)]
pub enum CellStatus {
/// Cell exists and has not been spent.
Live(CellOutput),
Live(CellMeta),
/// Cell exists and has been spent.
Dead,
/// Cell does not exist.
Expand All @@ -32,14 +38,14 @@ impl CellStatus {
self == &CellStatus::Unknown
}

pub fn get_live(&self) -> Option<&CellOutput> {
pub fn get_live(&self) -> Option<&CellMeta> {
match *self {
CellStatus::Live(ref output) => Some(output),
_ => None,
}
}

pub fn take_live(self) -> Option<CellOutput> {
pub fn take_live(self) -> Option<CellMeta> {
match self {
CellStatus::Live(output) => Some(output),
_ => None,
Expand Down Expand Up @@ -114,7 +120,10 @@ impl<'a> CellProvider for BlockCellProvider<'a> {
.outputs()
.get(out_point.index as usize)
{
Some(x) => CellStatus::Live(x.clone()),
Some(x) => CellStatus::Live(CellMeta {
cell_output: x.clone(),
block_number: Some(self.block.header().number()),
}),
None => CellStatus::Unknown,
}
} else {
Expand Down Expand Up @@ -191,8 +200,8 @@ impl ResolvedTransaction {
self.input_cells
.iter()
.filter_map(|cell_status| {
if let CellStatus::Live(cell_output) = cell_status {
Some(cell_output.capacity)
if let CellStatus::Live(cell_meta) = cell_status {
Some(cell_meta.cell_output.capacity)
} else {
None
}
Expand All @@ -209,12 +218,12 @@ mod tests {
use std::collections::HashMap;

struct CellMemoryDb {
cells: HashMap<OutPoint, Option<CellOutput>>,
cells: HashMap<OutPoint, Option<CellMeta>>,
}
impl CellProvider for CellMemoryDb {
fn cell(&self, o: &OutPoint) -> CellStatus {
match self.cells.get(o) {
Some(&Some(ref cell_output)) => CellStatus::Live(cell_output.clone()),
Some(&Some(ref cell)) => CellStatus::Live(cell.clone()),
Some(&None) => CellStatus::Dead,
None => CellStatus::Unknown,
}
Expand All @@ -239,11 +248,14 @@ mod tests {
hash: H256::zero(),
index: 3,
};
let o = CellOutput {
capacity: 2,
data: vec![],
lock: Script::default(),
type_: None,
let o = CellMeta {
block_number: Some(1),
cell_output: CellOutput {
capacity: 2,
data: vec![],
lock: Script::default(),
type_: None,
},
};

db.cells.insert(p1.clone(), Some(o.clone()));
Expand Down
22 changes: 8 additions & 14 deletions core/src/transaction.rs
Expand Up @@ -63,32 +63,36 @@ impl OutPoint {
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, OccupiedCapacity)]
pub struct CellInput {
pub previous_output: OutPoint,
pub valid_since: u64,
// Depends on whether the operation is Transform or Destroy, this is the proof to transform
// lock or destroy lock.
pub args: Vec<Vec<u8>>,
}

impl CellInput {
pub fn new(previous_output: OutPoint, args: Vec<Vec<u8>>) -> Self {
pub fn new(previous_output: OutPoint, valid_since: u64, args: Vec<Vec<u8>>) -> Self {
CellInput {
previous_output,
valid_since,
args,
}
}

pub fn new_cellbase_input(block_number: BlockNumber) -> Self {
pub fn new_cellbase_input(block_number: BlockNumber, valid_since: u64) -> Self {
CellInput {
previous_output: OutPoint::null(),
valid_since,
args: vec![block_number.to_le_bytes().to_vec()],
}
}

pub fn destruct(self) -> (OutPoint, Vec<Vec<u8>>) {
pub fn destruct(self) -> (OutPoint, u64, Vec<Vec<u8>>) {
let CellInput {
previous_output,
valid_since,
args,
} = self;
(previous_output, args)
(previous_output, valid_since, args)
}
}

Expand Down Expand Up @@ -146,7 +150,6 @@ pub type Witness = Vec<Vec<u8>>;
#[derive(Clone, Serialize, Deserialize, Eq, Debug, Default, OccupiedCapacity)]
pub struct Transaction {
version: Version,
valid_since: u64,
deps: Vec<OutPoint>,
inputs: Vec<CellInput>,
outputs: Vec<CellOutput>,
Expand Down Expand Up @@ -179,10 +182,6 @@ impl Transaction {
self.version
}

pub fn valid_since(&self) -> u64 {
self.valid_since
}

pub fn deps(&self) -> &[OutPoint] {
&self.deps
}
Expand Down Expand Up @@ -283,11 +282,6 @@ impl TransactionBuilder {
self
}

pub fn valid_since(mut self, valid_since: u64) -> Self {
self.inner.valid_since = valid_since;
self
}

pub fn dep(mut self, dep: OutPoint) -> Self {
self.inner.deps.push(dep);
self
Expand Down
4 changes: 4 additions & 0 deletions core/src/transaction_meta.rs
Expand Up @@ -47,6 +47,10 @@ impl TransactionMeta {
self.dead_cell.len()
}

pub fn block_number(&self) -> u64 {
self.block_number
}

pub fn is_empty(&self) -> bool {
self.dead_cell.is_empty()
}
Expand Down
4 changes: 2 additions & 2 deletions miner/src/block_assembler.rs
Expand Up @@ -317,7 +317,7 @@ impl<CI: ChainIndex + 'static> BlockAssembler<CI> {
lock: Script,
) -> Result<Transaction, FailureError> {
// NOTE: To generate different cellbase txid, we put header number in the input script
let input = CellInput::new_cellbase_input(header.number() + 1);
let input = CellInput::new_cellbase_input(header.number() + 1, 0);
// NOTE: We could've just used byteorder to serialize u64 and hex string into bytes,
// but the truth is we will modify this after we designed lock script anyway, so let's
// stick to the simpler way and just convert everything to a single string, then to UTF8
Expand Down Expand Up @@ -569,7 +569,7 @@ mod tests {

fn create_cellbase(number: BlockNumber) -> Transaction {
TransactionBuilder::default()
.input(CellInput::new_cellbase_input(number))
.input(CellInput::new_cellbase_input(number, 0))
.output(CellOutput::new(0, vec![], Script::default(), None))
.build()
}
Expand Down
2 changes: 1 addition & 1 deletion protocol/src/builder.rs
Expand Up @@ -104,7 +104,6 @@ impl<'a> FbsTransaction<'a> {

let mut builder = TransactionBuilder::new(fbb);
builder.add_version(transaction.version());
builder.add_valid_since(transaction.valid_since());
builder.add_deps(deps);
builder.add_inputs(inputs);
builder.add_outputs(outputs);
Expand Down Expand Up @@ -157,6 +156,7 @@ impl<'a> FbsCellInput<'a> {
let mut builder = CellInputBuilder::new(fbb);
builder.add_hash(&hash);
builder.add_index(cell_input.previous_output.index);
builder.add_valid_since(cell_input.valid_since);
builder.add_args(args);
builder.finish()
}
Expand Down

0 comments on commit 644f7aa

Please sign in to comment.