use of org.tron.core.net.peer.PeerConnection in project java-tron by tronprotocol.
the class SyncPool method prepareActive.
private synchronized void prepareActive() {
List<Channel> managerActive = new ArrayList<>(channelManager.getActivePeers());
NodeSelector nodeSelector = new NodeSelector();
List<PeerConnection> active = new ArrayList<>();
for (Channel channel : managerActive) {
if (nodeSelector.test(nodeManager.getNodeHandler(channel.getNode()))) {
active.add((PeerConnection) channel);
}
}
if (active.isEmpty())
return;
active.sort(Comparator.comparingDouble(c -> c.getPeerStats().getAvgLatency()));
for (PeerConnection channel : active) {
if (!activePeers.contains(channel)) {
peerDel.onConnectPeer(channel);
}
}
activePeers.clear();
activePeers.addAll(active);
}
use of org.tron.core.net.peer.PeerConnection in project java-tron by tronprotocol.
the class SyncPool method logActivePeers.
synchronized void logActivePeers() {
logger.info("-------- active node.");
for (NodeHandler nodeHandler : nodeManager.getActiveNodes()) {
logger.info(nodeHandler.toString());
}
logger.info("-------- active channel {}, node in user size {}", channelManager.getActivePeers().size(), channelManager.nodesInUse().size());
for (Channel channel : channelManager.getActivePeers()) {
logger.info(channel.toString());
}
if (logger.isInfoEnabled()) {
StringBuilder sb = new StringBuilder("Peer stats:\n");
sb.append("Active peers\n");
sb.append("============\n");
Set<Node> activeSet = new HashSet<>();
for (PeerConnection peer : new ArrayList<>(activePeers)) {
sb.append(peer.logSyncStats()).append('\n');
activeSet.add(peer.getNode());
}
sb.append("Other connected peers\n");
sb.append("============\n");
for (Channel peer : new ArrayList<>(channelManager.getActivePeers())) {
if (!activeSet.contains(peer.getNode())) {
sb.append(peer.logSyncStats()).append('\n');
}
}
logger.info(sb.toString());
}
}
use of org.tron.core.net.peer.PeerConnection in project java-tron by tronprotocol.
the class NodeImpl method processAdvBlock.
private void processAdvBlock(PeerConnection peer, BlockCapsule block) {
// TODO: lack the complete flow.
if (!freshBlockId.contains(block.getBlockId())) {
try {
LinkedList<Sha256Hash> trxIds = del.handleBlock(block, false);
freshBlockId.offer(block.getBlockId());
trxIds.forEach(trxId -> advObjToFetch.remove(trxId));
// TODO:save message cache again.
getActivePeer().stream().filter(p -> p.getAdvObjSpreadToUs().containsKey(block.getBlockId())).forEach(p -> {
p.setHeadBlockWeBothHave(block.getBlockId());
p.setHeadBlockTimeWeBothHave(block.getTimeStamp());
});
getActivePeer().forEach(p -> p.cleanInvGarbage());
// rebroadcast
broadcast(new BlockMessage(block));
} catch (BadBlockException e) {
badAdvObj.put(block.getBlockId(), System.currentTimeMillis());
} catch (UnLinkedBlockException e) {
// reSync
startSyncWithPeer(peer);
}
}
}
use of org.tron.core.net.peer.PeerConnection in project java-tron by tronprotocol.
the class NodeImpl method onHandleChainInventoryMessage.
private void onHandleChainInventoryMessage(PeerConnection peer, ChainInventoryMessage msg) {
// logger.info("on handle block chain inventory message");
try {
if (peer.getSyncChainRequested() != null) {
// List<BlockId> blockIds = msg.getBlockIds();
Deque<BlockId> blockIdWeGet = new LinkedList<>(msg.getBlockIds());
// check if the peer is a traitor
if (!blockIdWeGet.isEmpty()) {
long num = blockIdWeGet.peek().getNum();
for (BlockId id : blockIdWeGet) {
if (id.getNum() != num++) {
throw new TraitorPeerException("We get a not continuous block inv from " + peer);
}
}
if (peer.getSyncChainRequested().getKey().isEmpty()) {
if (blockIdWeGet.peek().getNum() != 1) {
throw new TraitorPeerException("We want a block inv starting from beginning from " + peer);
}
} else {
boolean isFound = false;
for (BlockId id : blockIdWeGet) {
if (id.equals(blockIdWeGet.peek())) {
isFound = true;
}
}
if (!isFound) {
throw new TraitorPeerException("We get a unlinked block chain from " + peer);
}
}
}
// check finish
// here this peer's answer is legal
peer.setSyncChainRequested(null);
if (msg.getRemainNum() == 0 && (blockIdWeGet.isEmpty() || (blockIdWeGet.size() == 1 && del.containBlock(blockIdWeGet.peek()))) && peer.getSyncBlockToFetch().isEmpty() && peer.getUnfetchSyncNum() == 0) {
peer.setNeedSyncFromPeer(false);
unSyncNum = getUnSyncNum();
if (unSyncNum == 0) {
del.syncToCli(0);
}
// TODO: if sync finish call del.syncToCli();
return;
}
if (!blockIdWeGet.isEmpty() && peer.getSyncBlockToFetch().isEmpty()) {
boolean isFound = false;
for (PeerConnection peerToCheck : getActivePeer()) {
if (!peerToCheck.equals(peer) && !peerToCheck.getSyncBlockToFetch().isEmpty() && peerToCheck.getSyncBlockToFetch().peekFirst().equals(blockIdWeGet.peekFirst())) {
isFound = true;
break;
}
}
if (!isFound) {
while (!blockIdWeGet.isEmpty() && del.containBlock(blockIdWeGet.peek())) {
peer.setHeadBlockWeBothHave(blockIdWeGet.peek());
peer.setHeadBlockTimeWeBothHave(del.getBlockTime(blockIdWeGet.peek()));
blockIdWeGet.poll();
}
}
} else if (!blockIdWeGet.isEmpty()) {
while (!peer.getSyncBlockToFetch().isEmpty()) {
if (!peer.getSyncBlockToFetch().peekLast().equals(blockIdWeGet.peekFirst())) {
blockIdWeGet.pop();
} else {
break;
}
}
if (peer.getSyncBlockToFetch().isEmpty()) {
updateBlockWeBothHave(peer, ((BlockMessage) del.getData(blockIdWeGet.peek(), MessageTypes.BLOCK)).getBlockCapsule());
}
// poll the block we both have.
blockIdWeGet.pop();
}
// sew it
peer.getSyncBlockToFetch().addAll(blockIdWeGet);
peer.setUnfetchSyncNum(msg.getRemainNum());
long newUnSyncNum = getUnSyncNum();
if (unSyncNum != newUnSyncNum) {
unSyncNum = newUnSyncNum;
del.syncToCli(unSyncNum);
}
if (msg.getRemainNum() == 0) {
if (!peer.getSyncBlockToFetch().isEmpty()) {
startFetchSyncBlock();
} else {
// let peer know we are sync.
syncNextBatchChainIds(peer);
}
} else {
if (peer.getSyncBlockToFetch().size() > NodeConstant.SYNC_FETCH_BATCH_NUM) {
// one batch by one batch.
startFetchSyncBlock();
} else {
syncNextBatchChainIds(peer);
}
}
// TODO: check head block time is legal here
// TODO: refresh sync status to cli. call del.syncToCli() here
} else {
throw new TraitorPeerException("We don't send sync request to " + peer);
}
} catch (TraitorPeerException e) {
banTraitorPeer(peer);
}
}
use of org.tron.core.net.peer.PeerConnection in project java-tron by tronprotocol.
the class NodeImpl method startFetchSyncBlock.
private synchronized void startFetchSyncBlock() {
// TODO: check how many block is processing and decide if fetch more
HashMap<PeerConnection, List<BlockId>> send = new HashMap<>();
HashSet<BlockId> request = new HashSet<>();
getActivePeer().stream().filter(peer -> peer.isNeedSyncFromPeer() && !peer.isBusy()).forEach(peer -> {
if (!send.containsKey(peer)) {
// TODO: Attention multi thread here
send.put(peer, new LinkedList<>());
}
for (BlockId blockId : peer.getSyncBlockToFetch()) {
if (// TODO: clean processing block
!request.contains(blockId) && !syncBlockIdWeRequested.containsKey(blockId)) {
send.get(peer).add(blockId);
request.add(blockId);
// TODO: check max block num to fetch from one peer.
// if (send.get(peer).size() > 200) { //Max Blocks peer get one time
// break;
// }
}
}
});
send.forEach((peer, blockIds) -> {
// TODO: use collector
blockIds.forEach(blockId -> {
syncBlockIdWeRequested.put(blockId, System.currentTimeMillis());
peer.getSyncBlockRequested().put(blockId, System.currentTimeMillis());
});
List<Sha256Hash> ids = new LinkedList<>();
ids.addAll(blockIds);
peer.sendMessage(new FetchInvDataMessage(ids, InventoryType.BLOCK));
});
send.clear();
}
Aggregations