From eae0ab6b2a5babe908b720787f35d09d006469e5 Mon Sep 17 00:00:00 2001
From: Antioch Peverell <apeverell@protonmail.com>
Date: Mon, 3 Sep 2018 11:09:53 +0100
Subject: [PATCH] take write lock on txhashet earlier when processing blocks
 (#1456)

* take write lock on txhashet earlier when processing blocks

* no txhashset lock in process_block_header
---
 chain/src/pipe.rs | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/chain/src/pipe.rs b/chain/src/pipe.rs
index ebde26242..2f82f02cb 100644
--- a/chain/src/pipe.rs
+++ b/chain/src/pipe.rs
@@ -75,6 +75,14 @@ pub fn process_block(
 		b.outputs().len(),
 		b.kernels().len(),
 	);
+
+	// First thing we do is take a write lock on the txhashset.
+	// We may receive the same block from multiple peers simultaneously.
+	// We want to process the first one fully to avoid redundant work
+	// processing the duplicates.
+	let txhashset = ctx.txhashset.clone();
+	let mut txhashset = txhashset.write().unwrap();
+
 	check_known(b.hash(), ctx)?;
 
 	validate_header(&b.header, ctx)?;
@@ -99,14 +107,8 @@ pub fn process_block(
 	}
 
 	// validate the block itself
-	// we can do this now before interacting with the txhashset
 	let _sums = validate_block(b, ctx, verifier_cache)?;
 
-	// header and block both valid, and we have a previous block
-	// so take the lock on the txhashset
-	let local_txhashset = ctx.txhashset.clone();
-	let mut txhashset = local_txhashset.write().unwrap();
-
 	// update head now that we're in the lock
 	ctx.head = ctx.store.head()?;