Skip to content

Commit 8a28fd8

Browse files
zhangsoledaddoitian
authored andcommitted
fix: chain index
* fix chain index * clean network log * use yamux * fix: spawn timer
1 parent 765ea25 commit 8a28fd8

30 files changed

Lines changed: 183 additions & 112 deletions

Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

chain/src/chain.rs

Lines changed: 51 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use bigint::H256;
1+
use bigint::{H256, U256};
22
use chain_spec::consensus::Consensus;
33
use channel::{self, Receiver, Sender};
44
use ckb_notify::{ForkBlocks, NotifyController, NotifyService};
@@ -16,6 +16,7 @@ use std::cmp;
1616
use std::sync::Arc;
1717
use std::thread::{self, JoinHandle};
1818
use time::now_ms;
19+
use util::RwLockUpgradableReadGuard;
1920
use verification::{BlockVerifier, Verifier};
2021

2122
pub struct ChainService<CI> {
@@ -129,8 +130,14 @@ impl<CI: ChainIndex + 'static> ChainService<CI> {
129130

130131
fn insert_block(&self, block: &Block) -> Result<BlockInsertionResult, SharedError> {
131132
let mut new_best_block = false;
133+
let mut output_root = H256::zero();
134+
let mut total_difficulty = U256::zero();
135+
132136
let mut old_cumulative_blks = Vec::new();
133137
let mut new_cumulative_blks = Vec::new();
138+
139+
let tip_header = self.shared.tip_header().upgradable_read();
140+
let tip_number = tip_header.number();
134141
self.shared.store().save_with_batch(|batch| {
135142
let root = self.check_transactions(batch, block)?;
136143
let parent_ext = self
@@ -150,41 +157,50 @@ impl<CI: ChainIndex + 'static> ChainService<CI> {
150157
self.shared.store().insert_output_root(batch, block.header().hash(), root);
151158
self.shared.store().insert_block_ext(batch, &block.header().hash(), &ext);
152159

153-
{
154-
debug!(target: "chain", "acquire lock");
155-
let mut tip_header = self.shared.tip_header().write();
156-
let current_total_difficulty = tip_header.total_difficulty();
157-
debug!(
158-
"difficulty diff = {}; current = {}, cannon = {}",
159-
cannon_total_difficulty.low_u64() as i64
160-
- current_total_difficulty.low_u64() as i64,
161-
current_total_difficulty,
162-
cannon_total_difficulty,
163-
);
160+
let current_total_difficulty = tip_header.total_difficulty();
161+
debug!(
162+
"difficulty diff = {}; current = {}, cannon = {}",
163+
cannon_total_difficulty.low_u64() as i64
164+
- current_total_difficulty.low_u64() as i64,
165+
current_total_difficulty,
166+
cannon_total_difficulty,
167+
);
164168

165-
if cannon_total_difficulty > current_total_difficulty
166-
|| (current_total_difficulty == cannon_total_difficulty
167-
&& block.header().hash() < tip_header.hash())
168-
{
169-
debug!(target: "chain", "new best block found: {} => {}", block.header().number(), block.header().hash());
170-
new_best_block = true;
171-
let new_tip_header = TipHeader::new(
172-
block.header().clone(),
173-
cannon_total_difficulty,
174-
root,
175-
);
176-
177-
self.update_index(batch, tip_header.number(), block, &mut old_cumulative_blks, &mut new_cumulative_blks);
178-
// TODO: Move out
179-
*tip_header = new_tip_header;
180-
self.shared.store().insert_tip_header(batch, &block.header());
181-
self.shared.store().rebuild_tree(root);
182-
}
183-
debug!(target: "chain", "lock release");
169+
if cannon_total_difficulty > current_total_difficulty
170+
|| (current_total_difficulty == cannon_total_difficulty
171+
&& block.header().hash() < tip_header.hash())
172+
{
173+
debug!(target: "chain", "new best block found: {} => {}", block.header().number(), block.header().hash());
174+
new_best_block = true;
175+
output_root = root;
176+
total_difficulty = cannon_total_difficulty;
184177
}
185178
Ok(())
186179
})?;
187180

181+
if new_best_block {
182+
debug!(target: "chain", "update index");
183+
let mut guard = RwLockUpgradableReadGuard::upgrade(tip_header);
184+
let new_tip_header =
185+
TipHeader::new(block.header().clone(), total_difficulty, output_root);
186+
self.shared.store().save_with_batch(|batch| {
187+
self.update_index(
188+
batch,
189+
tip_number,
190+
block,
191+
&mut old_cumulative_blks,
192+
&mut new_cumulative_blks,
193+
);
194+
self.shared
195+
.store()
196+
.insert_tip_header(batch, &block.header());
197+
self.shared.store().rebuild_tree(output_root);
198+
Ok(())
199+
})?;
200+
*guard = new_tip_header;
201+
debug!(target: "chain", "update index release");
202+
}
203+
188204
Ok(BlockInsertionResult {
189205
new_best_block,
190206
fork_blks: ForkBlocks::new(old_cumulative_blks, new_cumulative_blks),
@@ -220,11 +236,11 @@ impl<CI: ChainIndex + 'static> ChainService<CI> {
220236
old_cumulative_blks: &mut Vec<Block>,
221237
new_cumulative_blks: &mut Vec<Block>,
222238
) {
223-
let mut number = block.header().number() - 1;
239+
let mut number = block.header().number();
224240

225241
// The old fork may longer than new fork
226-
if number < tip_number {
227-
for n in number..tip_number + 1 {
242+
if tip_number >= number {
243+
for n in number..=tip_number {
228244
let hash = self.shared.block_hash(n).unwrap();
229245
let old_block = self.shared.block(&hash).unwrap();
230246
self.shared.store().delete_block_hash(batch, n);
@@ -253,7 +269,7 @@ impl<CI: ChainIndex + 'static> ChainService<CI> {
253269
}
254270

255271
let mut hash = block.header().parent_hash();
256-
272+
number -= 1;
257273
loop {
258274
if let Some(old_hash) = self.shared.block_hash(number) {
259275
if old_hash == hash {

chain/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ extern crate ckb_verification as verification;
1919
extern crate log;
2020
#[macro_use]
2121
extern crate crossbeam_channel as channel;
22+
extern crate ckb_util as util;
2223

2324
#[cfg(test)]
2425
extern crate rand;

miner/src/miner.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,6 @@ impl MinerService {
117117
let mut new_transactions_counter = 0;
118118
let mut nonce: u64 = thread_rng().gen();
119119
loop {
120-
debug!(target: "miner", "mining {}", nonce);
121120
loop {
122121
select! {
123122
recv(self.new_tx_receiver, msg) => match msg {

network/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ rand = "0.5"
99
fnv = "1.0"
1010
serde = "1.0"
1111
serde_derive = "1.0"
12-
parking_lot = "0.6"
12+
ckb-util = { path = "../util" }
1313
unsigned-varint = {git = "https://github.com/paritytech/unsigned-varint", features = ["codec"]}
1414
log = "0.4.5"
1515
bytes = "0.4.9"

network/src/ckb_protocol.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ where
104104
Ok(result) => result,
105105
Err(err) => {
106106
return {
107-
error!("failed to upgrade ckb_protocol");
107+
error!(target: "network", "failed to upgrade ckb_protocol");
108108
future::err(IoError::new(IoErrorKind::Other, err))
109109
}
110110
}
@@ -118,7 +118,7 @@ where
118118
outgoing_msg_channel,
119119
incoming_stream,
120120
};
121-
trace!("success to upgrade ckb_protocol");
121+
trace!(target: "network", "success to upgrade ckb_protocol");
122122

123123
future::ok((out, remote_addr))
124124
}

network/src/ckb_protocol_handler.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use super::errors::{Error, ErrorKind};
22
use super::{Network, SessionInfo, Timer};
33
use super::{PeerIndex, ProtocolId, TimerToken};
4-
use parking_lot::Mutex;
54
use std::sync::Arc;
65
use std::time::Duration;
6+
use util::Mutex;
77

88
#[derive(Clone, Debug)]
99
pub enum Severity<'a> {
@@ -83,7 +83,7 @@ impl CKBProtocolContext for DefaultCKBProtocolContext {
8383
// report peer behaviour
8484
fn report_peer(&self, peer_index: PeerIndex, reason: Severity) {
8585
// TODO combinate this interface with peer score
86-
info!("report peer {} reason: {:?}", peer_index, reason);
86+
info!(target: "network", "report peer {} reason: {:?}", peer_index, reason);
8787
self.disconnect(peer_index);
8888
}
8989
// ban peer

network/src/ckb_service.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ impl CKBService {
4646
};
4747
if protocol_connec.state() == UniqueConnecState::Full {
4848
error!(
49+
target: "network",
4950
"we already connected peer {:?} with {:?}, stop handling",
5051
peer_id, protocol_id
5152
);
@@ -99,6 +100,7 @@ impl CKBService {
99100
let protocol_id = protocol_id;
100101
move |val| {
101102
info!(
103+
target: "network",
102104
"Disconnect! peer {:?} protocol_id {:?} reason {:?}",
103105
peer_id, protocol_id, val
104106
);
@@ -122,6 +124,7 @@ impl CKBService {
122124
};
123125

124126
info!(
127+
target: "network",
125128
"Connected to peer {:?} with protocol_id {:?} version {}",
126129
peer_id, protocol_id, protocol_version
127130
);

network/src/discovery_service.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ use libp2p::core::{upgrade, MuxedTransport, PeerId};
88
use libp2p::core::{Endpoint, Multiaddr, UniqueConnec};
99
use libp2p::core::{PublicKey, SwarmController};
1010
use libp2p::{kad, Transport};
11-
use parking_lot::Mutex;
1211
use peer_store::Status;
1312
use protocol::Protocol;
1413
use protocol_service::ProtocolService;
@@ -25,6 +24,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
2524
use tokio::timer::Interval;
2625
use tokio::timer::Timeout;
2726
use transport::TransportOutput;
27+
use util::Mutex;
2828

2929
pub struct DiscoveryService {
3030
timeout: Duration,
@@ -111,7 +111,7 @@ impl<T: Send> ProtocolService<T> for DiscoveryService {
111111
let kad_upgrade = self.kad_upgrade.clone();
112112
// dial kad peer
113113
move |peer_id| {
114-
debug!("Initialize kad search peers from peer {:?}", peer_id);
114+
debug!(target: "network", "Initialize kad search peers from peer {:?}", peer_id);
115115
Self::dial_kad_peer(
116116
Arc::clone(&kad_manage),
117117
kad_upgrade.clone(),
@@ -223,7 +223,7 @@ impl DiscoveryService {
223223
_endpoint: Endpoint,
224224
kademlia_stream: Box<Stream<Item = kad::KadIncomingRequest, Error = IoError> + Send>,
225225
) -> Result<Box<Future<Item = (), Error = IoError> + Send>, IoError> {
226-
debug!("client_addr is {:?}", client_addr);
226+
debug!(target: "network", "client_addr is {:?}", client_addr);
227227
//let peer_id = match convert_addr_into_peer_id(client_addr) {
228228
// Some(peer_id) => peer_id,
229229
// None => {
@@ -247,7 +247,7 @@ impl DiscoveryService {
247247
Timeout::new(next_future, timeout)
248248
.map_err({
249249
move |err| {
250-
info!("kad timeout error {:?}", err.description());
250+
info!(target: "network", "kad timeout error {:?}", err.description());
251251
IoError::new(
252252
IoErrorKind::Other,
253253
format!("discovery request timeout {:?}", err.description()),
@@ -278,6 +278,7 @@ impl DiscoveryService {
278278
let peer_id = peer_id.clone();
279279
move |val| {
280280
trace!(
281+
target: "network",
281282
"Kad connection closed when handling peer {:?} reason: {:?}",
282283
peer_id,
283284
val
@@ -314,7 +315,8 @@ impl DiscoveryService {
314315
let network = Arc::clone(&network);
315316
move |peer_id| {
316317
if peer_id == *kad_system.local_peer_id() {
317-
info!(
318+
debug!(
319+
target: "network",
318320
"response self address to kad {:?}",
319321
network.listened_addresses.read().clone()
320322
);
@@ -336,7 +338,8 @@ impl DiscoveryService {
336338
Status::Connected => kad::KadConnectionType::Connected,
337339
_ => kad::KadConnectionType::NotConnected,
338340
};
339-
info!(
341+
debug!(
342+
target: "network",
340343
"response other address to kad {:?} {:?}",
341344
peer_id,
342345
multiaddrs.clone()
@@ -404,6 +407,7 @@ impl DiscoveryService {
404407
Some(Some(addr)) => addr.to_owned(),
405408
_ => {
406409
debug!(
410+
target: "network",
407411
"dial kad error, can't find dial address for peer_id {:?}",
408412
peer_id
409413
);

network/src/identify_service.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
use super::Network;
44
use super::PeerId;
5-
use futures::future::{self, lazy, Future};
5+
use futures::future::{self, Future};
66
use futures::Stream;
77
use libp2p::core::Multiaddr;
88
use libp2p::core::SwarmController;
@@ -51,6 +51,7 @@ impl IdentifyService {
5151
})
5252
}
5353
None => error!(
54+
target: "network",
5455
"can't find peer_id {:?} during process identify info",
5556
peer_id
5657
),
@@ -61,13 +62,14 @@ impl IdentifyService {
6162
for original_address in network.original_listened_addresses.read().iter() {
6263
let transport = libp2p::tcp::TcpConfig::new();
6364
trace!(
65+
target: "network",
6466
"try get address use original_address {:?} and observed_address {:?}",
6567
original_address,
6668
observed_addr
6769
);
6870
// get an external addrs for our node
6971
if let Some(mut ext_addr) = transport.nat_traversal(original_address, &observed_addr) {
70-
debug!("get new external address {:?}", ext_addr);
72+
debug!(target: "network", "get new external address {:?}", ext_addr);
7173
let mut listened_addresses = network.listened_addresses.write();
7274
if !listened_addresses.iter().any(|a| a == &ext_addr) {
7375
listened_addresses.push(ext_addr.clone());
@@ -182,7 +184,7 @@ where
182184
Instant::now() + Duration::from_secs(5),
183185
self.identify_interval,
184186
).map_err(|err| {
185-
debug!("identify periodic error {:?}", err);
187+
debug!(target: "network", "identify periodic error {:?}", err);
186188
IoError::new(
187189
IoErrorKind::Other,
188190
format!("identify periodic error {:?}", err),
@@ -200,6 +202,7 @@ where
200202
}
201203
}
202204
trace!(
205+
target: "network",
203206
"request identify to peer {:?} {:?}",
204207
peer_id,
205208
peer.remote_addresses
@@ -210,15 +213,16 @@ where
210213
let _ = swarm_controller.dial(addr.clone(), transport.clone());
211214
} else {
212215
error!(
216+
target: "network",
213217
"error when prepare identify : can't find addresses for peer {:?}",
214218
peer_id
215219
);
216220
}
217221
}
218-
Box::new(lazy(|| future::ok(()))) as Box<Future<Item = _, Error = _> + Send>
222+
Ok(())
219223
}
220224
}).then(|err| {
221-
warn!("Identify service stopped, reason: {:?}", err);
225+
warn!(target: "network", "Identify service stopped, reason: {:?}", err);
222226
err
223227
});
224228
Box::new(periodic_identify_future) as Box<Future<Item = _, Error = _> + Send>

0 commit comments

Comments
 (0)