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

fix: orphan block pool deadlock #2074

Merged
merged 1 commit into from
May 18, 2020
Merged
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
36 changes: 33 additions & 3 deletions sync/src/orphan_block_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,10 @@ impl OrphanBlockPool {
}

pub fn get_block(&self, hash: &packed::Byte32) -> Option<core::BlockView> {
self.parents.write().get(hash).and_then(|parent_hash| {
self.blocks
.write()
// acquire the `blocks` read lock first, guarantee ordering of acquisition is same as `remove_blocks_by_parent`, avoids deadlocking
let guard = self.blocks.read();
self.parents.read().get(hash).and_then(|parent_hash| {
guard
.get(parent_hash)
.and_then(|value| value.get(hash).map(|v| v.1.clone()))
})
Expand All @@ -76,6 +77,8 @@ mod tests {
use faketime::unix_time_as_millis;
use std::collections::HashSet;
use std::iter::FromIterator;
use std::sync::Arc;
use std::thread;

fn gen_block(parent_header: &HeaderView) -> BlockView {
BlockBuilder::default()
Expand Down Expand Up @@ -106,4 +109,31 @@ mod tests {
let block: HashSet<BlockView> = HashSet::from_iter(blocks.into_iter());
assert_eq!(orphan, block)
}

#[test]
fn test_remove_blocks_by_parent_and_get_block_should_not_deadlock() {
let consensus = ConsensusBuilder::default().build();
let pool = OrphanBlockPool::with_capacity(1024);
let mut header = consensus.genesis_block().header();
let mut hashes = Vec::new();
for _ in 1..1024 {
let new_block = gen_block(&header);
pool.insert(PeerIndex::new(0usize), new_block.clone());
header = new_block.header();
hashes.push(header.hash());
}

let pool_arc1 = Arc::new(pool);
let pool_arc2 = Arc::clone(&pool_arc1);

let thread1 = thread::spawn(move || {
pool_arc1.remove_blocks_by_parent(&consensus.genesis_block().hash());
});

for hash in hashes.iter().rev() {
pool_arc2.get_block(hash);
}

thread1.join().unwrap();
}
}