Skip to content

Commit

Permalink
Merge branch 'master' into feature/add_integration_test
Browse files Browse the repository at this point in the history
  • Loading branch information
jolestar authored Apr 6, 2022
2 parents a49c1fa + f759246 commit a368767
Show file tree
Hide file tree
Showing 49 changed files with 1,002 additions and 166 deletions.
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/01_BUG_REPORT.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
name: Bug Report
about: Create a report to help Starcoin to improve
title: "bug: "
title: "[Bug Report]"
labels: "bug"
assignees: ""
---
Expand Down
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/02_FEATURE_REQUEST.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
name: Feature Request
about: Suggest an idea for this project
title: "feat: "
title: "[Feature Request]"
labels: "enhancement"
assignees: ""
---
Expand Down
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/03_CODEBASE_IMPROVEMENT.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
name: Codebase improvement
about: Provide your feedback for the existing codebase. Suggest a better solution for algorithms, development tools, etc.
title: "dev: "
title: "[Dev]"
labels: "enhancement"
assignees: ""
---
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
blank_issues_enabled: false
contact_links:
- name: Starcoin Community Support
url: https://github.com/starcoinorg/starcoin/discussions
url: https://github.com/starcoinorg/starcoin-cookbook/issues/new?labels=question&template=02_QUESTION.md&title=%5Bquestion%5D
about: Please ask and answer questions here.
7 changes: 5 additions & 2 deletions Cargo.lock

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

8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,20 @@ starcoin -n main console

## Connect to remote node

Connect main network seed nodes:
Connect to the main network seed nodes:

```shell
starcoin --connect ws://main.seed.starcoin.org:9870 console
```

>note: Account-related commands cannot be used when connecting remotely
Connect to the main network seed nodes and use a local account database for using Account-related commands

```shell
starcoin --connect ws://main.seed.starcoin.org:9870 --local-account-dir ~/.starcoin/account_vaults console
```

More detailed test network info please read [Join starcoin test network](https://developer.starcoin.org/en/setup/runnetwork/).


Expand Down
2 changes: 2 additions & 0 deletions chain/api/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ pub enum ChainRequest {
event_index: Option<u64>,
access_path: Option<AccessPath>,
},
GetBlockInfos(Vec<HashValue>),
}

impl ServiceRequest for ChainRequest {
Expand Down Expand Up @@ -86,4 +87,5 @@ pub enum ChainResponse {
MainEvents(Vec<ContractEventInfo>),
HashVec(Vec<HashValue>),
TransactionProof(Box<Option<TransactionInfoWithProof>>),
BlockInfoVec(Box<Vec<Option<BlockInfo>>>),
}
13 changes: 13 additions & 0 deletions chain/api/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ pub trait ReadableChainService {
event_index: Option<u64>,
access_path: Option<AccessPath>,
) -> Result<Option<TransactionInfoWithProof>>;

fn get_block_infos(&self, ids: Vec<HashValue>) -> Result<Vec<Option<BlockInfo>>>;
}

/// Writeable block chain service trait
Expand Down Expand Up @@ -129,6 +131,8 @@ pub trait ChainAsyncService:
event_index: Option<u64>,
access_path: Option<AccessPath>,
) -> Result<Option<TransactionInfoWithProof>>;

async fn get_block_infos(&self, hashes: Vec<HashValue>) -> Result<Vec<Option<BlockInfo>>>;
}

#[async_trait::async_trait]
Expand Down Expand Up @@ -416,4 +420,13 @@ where
bail!("get transactin proof error")
}
}

async fn get_block_infos(&self, hashes: Vec<HashValue>) -> Result<Vec<Option<BlockInfo>>> {
let response = self.send(ChainRequest::GetBlockInfos(hashes)).await??;
if let ChainResponse::BlockInfoVec(block_infos) = response {
Ok(*block_infos)
} else {
bail!("get block_infos error")
}
}
}
8 changes: 8 additions & 0 deletions chain/service/src/chain_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,9 @@ impl ServiceHandler<Self, ChainRequest> for ChainReaderService {
access_path,
)?,
))),
ChainRequest::GetBlockInfos(ids) => Ok(ChainResponse::BlockInfoVec(Box::new(
self.inner.get_block_infos(ids)?,
))),
}
}
}
Expand Down Expand Up @@ -298,6 +301,7 @@ impl ReadableChainService for ChainReaderServiceInner {
self.storage.get_blocks(ids)
}

// XXX FIXME different get_blocks
fn get_headers(&self, ids: Vec<HashValue>) -> Result<Vec<BlockHeader>> {
let mut headers = Vec::new();
self.get_blocks(ids)?.into_iter().for_each(|block| {
Expand Down Expand Up @@ -406,6 +410,10 @@ impl ReadableChainService for ChainReaderServiceInner {
access_path,
)
}

fn get_block_infos(&self, ids: Vec<HashValue>) -> Result<Vec<Option<BlockInfo>>> {
self.storage.get_block_infos(ids)
}
}

#[cfg(test)]
Expand Down
47 changes: 29 additions & 18 deletions chain/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

use crate::verifier::{BlockVerifier, FullVerifier};
use anyhow::{ensure, format_err, Result};
use anyhow::{bail, ensure, format_err, Result};
use consensus::Consensus;
use crypto::hash::PlainCryptoHash;
use crypto::HashValue;
Expand Down Expand Up @@ -566,14 +566,24 @@ impl ChainReader for BlockChain {
None => self.current_header().number(),
Some(number) => number,
};
let end_num_exclusive = end_num.saturating_add(1);
(end_num_exclusive.saturating_sub(count)..end_num_exclusive)
.rev()
.map(|idx| {
self.get_block_by_number(idx)?
.ok_or_else(|| format_err!("Can not find block by number {}", idx))
})
.collect()

let num_leaves = self.block_accumulator.num_leaves();
if end_num > num_leaves {
bail!("Can not find block by number {}", end_num);
}
let ids = self.get_block_ids(end_num, true, count)?;
let block_opts = self.storage.get_blocks(ids)?;
let mut blocks = vec![];
for (idx, block) in block_opts.into_iter().enumerate() {
match block {
Some(block) => blocks.push(block),
None => bail!(
"Can not find block by number {}",
end_num.saturating_sub(idx as u64)
),
}
}
Ok(blocks)
}

fn get_block(&self, hash: HashValue) -> Result<Option<Block>> {
Expand Down Expand Up @@ -746,19 +756,20 @@ impl ChainReader for BlockChain {
max_size: u64,
) -> Result<Vec<RichTransactionInfo>> {
let chain_header = self.current_header();
let hash_list = self
let hashes = self
.txn_accumulator
.get_leaves(start_index, reverse, max_size)?;
let mut infos = vec![];
for hash in hash_list {
let info = self.storage.get_transaction_info(hash)?.ok_or_else(|| {
anyhow::anyhow!(format!(
"cannot find hash({}) on main chain(head: {})",
hash,
let txn_infos = self.storage.get_transaction_infos(hashes.clone())?;
for (i, info) in txn_infos.into_iter().enumerate() {
match info {
Some(info) => infos.push(info),
None => bail!(
"cannot find hash({:?}) on head: {}",
hashes.get(i),
chain_header.id()
))
})?;
infos.push(info);
),
}
}
Ok(infos)
}
Expand Down
9 changes: 0 additions & 9 deletions chain/src/verifier/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,15 +171,6 @@ impl BlockVerifier for BasicVerifier {
new_block_header.number()
);

verify_block!(
VerifyBlockField::Header,
current_id == new_block_parent,
"Invalid block: Parent id mismatch, expect:{}, got: {}, number:{}.",
current_id,
new_block_parent,
new_block_header.number()
);

verify_block!(
VerifyBlockField::Header,
new_block_header.timestamp() > current.timestamp(),
Expand Down
38 changes: 18 additions & 20 deletions chain/tests/test_block_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,13 +202,11 @@ fn product_a_block(branch: &BlockChain, miner: &AccountInfo, uncles: Vec<BlockHe
}

#[stest::test(timeout = 120)]
#[allow(clippy::vec_init_then_push)]
fn test_uncle() {
let (mut mock_chain, _, uncle_block_header) = gen_uncle();
let miner = mock_chain.miner();
// 3. mock chain apply
let mut uncles = Vec::new();
uncles.push(uncle_block_header.clone());
let uncles = vec![uncle_block_header.clone()];
let block = product_a_block(mock_chain.head(), miner, uncles);
mock_chain.apply(block).unwrap();
assert!(mock_chain.head().head_block().block.uncles().is_some());
Expand All @@ -223,13 +221,11 @@ fn test_uncle() {
}

#[stest::test(timeout = 120)]
#[allow(clippy::vec_init_then_push)]
fn test_uncle_exist() {
let (mut mock_chain, _, uncle_block_header) = gen_uncle();
let miner = mock_chain.miner().clone();
// 3. mock chain apply
let mut uncles = Vec::new();
uncles.push(uncle_block_header.clone());
let uncles = vec![uncle_block_header.clone()];
let block = product_a_block(mock_chain.head(), &miner, uncles);
mock_chain.apply(block).unwrap();
assert!(mock_chain.head().head_block().block.uncles().is_some());
Expand All @@ -243,14 +239,12 @@ fn test_uncle_exist() {
assert_eq!(mock_chain.head().current_epoch_uncles_size(), 1);

// 4. uncle exist
let mut uncles = Vec::new();
uncles.push(uncle_block_header);
let uncles = vec![uncle_block_header];
let block = product_a_block(mock_chain.head(), &miner, uncles);
assert!(mock_chain.apply(block).is_err());
}

#[stest::test(timeout = 120)]
#[allow(clippy::vec_init_then_push)]
fn test_uncle_son() {
let (mut mock_chain, mut fork_block_chain, _) = gen_uncle();
let miner = mock_chain.miner();
Expand All @@ -260,36 +254,31 @@ fn test_uncle_son() {
fork_block_chain.apply(uncle_son).unwrap();

// 4. mock chain apply
let mut uncles = Vec::new();
uncles.push(uncle_son_block_header);
let uncles = vec![uncle_son_block_header];
let block = product_a_block(mock_chain.head(), miner, uncles);
assert!(mock_chain.apply(block).is_err());
assert_eq!(mock_chain.head().current_epoch_uncles_size(), 0);
}

#[stest::test(timeout = 120)]
#[allow(clippy::vec_init_then_push)]
fn test_random_uncle() {
let (mut mock_chain, _, _) = gen_uncle();
let miner = mock_chain.miner();

// 3. random BlockHeader and apply
let mut uncles = Vec::new();
uncles.push(BlockHeader::random());
let uncles = vec![BlockHeader::random()];
let block = product_a_block(mock_chain.head(), miner, uncles);
assert!(mock_chain.apply(block).is_err());
assert_eq!(mock_chain.head().current_epoch_uncles_size(), 0);
}

#[stest::test(timeout = 480)]
#[allow(clippy::vec_init_then_push)]
fn test_switch_epoch() {
let (mut mock_chain, _, uncle_block_header) = gen_uncle();
let miner = mock_chain.miner().clone();

// 3. mock chain apply
let mut uncles = Vec::new();
uncles.push(uncle_block_header.clone());
let uncles = vec![uncle_block_header.clone()];
let block = product_a_block(mock_chain.head(), &miner, uncles);
mock_chain.apply(block).unwrap();
assert!(mock_chain.head().head_block().block.uncles().is_some());
Expand Down Expand Up @@ -322,7 +311,6 @@ fn test_switch_epoch() {
}

#[stest::test(timeout = 480)]
#[allow(clippy::vec_init_then_push)]
fn test_uncle_in_diff_epoch() {
let (mut mock_chain, _, uncle_block_header) = gen_uncle();
let miner = mock_chain.miner().clone();
Expand All @@ -347,8 +335,7 @@ fn test_uncle_in_diff_epoch() {
assert_eq!(mock_chain.head().current_epoch_uncles_size(), 0);

// 5. mock chain apply
let mut uncles = Vec::new();
uncles.push(uncle_block_header);
let uncles = vec![uncle_block_header];
let block = product_a_block(mock_chain.head(), &miner, uncles);
assert!(mock_chain.apply(block).is_err());
}
Expand Down Expand Up @@ -473,5 +460,16 @@ fn test_get_blocks_by_number() -> Result<()> {
.head()
.get_blocks_by_number(None, u64::max_value())?;
assert_eq!(blocks.len(), 11);

let number = blocks.len() as u64;
let number = number.saturating_add(1);
let result = mock_chain
.head()
.get_blocks_by_number(Some(blocks.len() as u64 + 1), u64::max_value());
assert!(
result.is_err(),
"result cannot find block by number {}",
number
);
Ok(())
}
Loading

0 comments on commit a368767

Please sign in to comment.