Search in sources :

Example 1 with BlockId

use of org.tron.core.capsule.BlockCapsule.BlockId in project java-tron by tronprotocol.

the class NodeImpl method onHandleBlockMessage.

private void onHandleBlockMessage(PeerConnection peer, BlockMessage blkMsg) {
    // logger.info("on handle block message");
    // peer.setLastBlockPeerKnow((BlockId) blkMsg.getMessageId());
    HashMap<Sha256Hash, Long> advObjWeRequested = peer.getAdvObjWeRequested();
    HashMap<BlockId, Long> syncBlockRequested = peer.getSyncBlockRequested();
    BlockId blockId = blkMsg.getBlockId();
    if (advObjWeRequested.containsKey(blockId)) {
        // broadcast mode
        advObjWeRequested.remove(blockId);
        processAdvBlock(peer, blkMsg.getBlockCapsule());
        startFetchItem();
    } else if (syncBlockRequested.containsKey(blockId)) {
        // sync mode
        syncBlockRequested.remove(blockId);
        // peer.getSyncBlockToFetch().remove(blockId);
        syncBlockIdWeRequested.remove(blockId);
        // TODO: maybe use consume pipe here better
        blockWaitToProcBak.add(blkMsg);
        // processSyncBlock(blkMsg.getBlockCapsule());
        if (!peer.isBusy()) {
            if (peer.getUnfetchSyncNum() > 0 && peer.getSyncBlockToFetch().size() < NodeConstant.SYNC_FETCH_BATCH_NUM) {
                syncNextBatchChainIds(peer);
            } else {
            // TODO: here should be a loop do this thing
            // startFetchSyncBlock();
            }
        }
    }
}
Also used : Sha256Hash(org.tron.common.utils.Sha256Hash) BlockId(org.tron.core.capsule.BlockCapsule.BlockId)

Example 2 with BlockId

use of org.tron.core.capsule.BlockCapsule.BlockId in project java-tron by tronprotocol.

the class NodeImpl method onHandleSyncBlockChainMessage.

private void onHandleSyncBlockChainMessage(PeerConnection peer, SyncBlockChainMessage syncMsg) {
    // logger.info("on handle sync block chain message");
    peer.setTronState(TronState.SYNCING);
    LinkedList<BlockId> blockIds;
    List<BlockId> summaryChainIds = syncMsg.getBlockIds();
    long remainNum = 0;
    try {
        blockIds = del.getLostBlockIds(summaryChainIds);
    } catch (UnReachBlockException e) {
        // TODO: disconnect this peer casue this peer can not switch
        logger.debug(e.getMessage(), e);
        return;
    }
    if (blockIds.isEmpty()) {
        peer.setNeedSyncFromUs(false);
    } else if (blockIds.size() == 1 && !summaryChainIds.isEmpty() && summaryChainIds.contains(blockIds.peekFirst())) {
        peer.setNeedSyncFromUs(false);
    } else {
        peer.setNeedSyncFromUs(true);
        remainNum = del.getHeadBlockId().getNum() - blockIds.peekLast().getNum();
    }
    if (!peer.isNeedSyncFromPeer() && !summaryChainIds.isEmpty() && !del.contain(Iterables.getLast(summaryChainIds), MessageTypes.BLOCK)) {
        startSyncWithPeer(peer);
    }
    peer.sendMessage(new ChainInventoryMessage(blockIds, remainNum));
}
Also used : UnReachBlockException(org.tron.core.exception.UnReachBlockException) ChainInventoryMessage(org.tron.core.net.message.ChainInventoryMessage) BlockId(org.tron.core.capsule.BlockCapsule.BlockId)

Example 3 with BlockId

use of org.tron.core.capsule.BlockCapsule.BlockId 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);
    }
}
Also used : BlockMessage(org.tron.core.net.message.BlockMessage) PeerConnection(org.tron.core.net.peer.PeerConnection) BlockId(org.tron.core.capsule.BlockCapsule.BlockId) TraitorPeerException(org.tron.core.exception.TraitorPeerException) LinkedList(java.util.LinkedList)

Example 4 with BlockId

use of org.tron.core.capsule.BlockCapsule.BlockId 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();
}
Also used : Autowired(org.springframework.beans.factory.annotation.Autowired) BlockCapsule(org.tron.core.capsule.BlockCapsule) ConcurrentSet(io.netty.util.internal.ConcurrentSet) BlockId(org.tron.core.capsule.BlockCapsule.BlockId) NodeHandler(org.tron.common.overlay.discover.NodeHandler) TransactionMessage(org.tron.core.net.message.TransactionMessage) NodeConstant(org.tron.core.config.Parameter.NodeConstant) Pair(javafx.util.Pair) InventoryMessage(org.tron.core.net.message.InventoryMessage) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) MessageTypes(org.tron.core.net.message.MessageTypes) UnReachBlockException(org.tron.core.exception.UnReachBlockException) ExecutorLoop(org.tron.common.utils.ExecutorLoop) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Executors(java.util.concurrent.Executors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Entry(java.util.Map.Entry) Queue(java.util.Queue) TronException(org.tron.core.exception.TronException) BlockConstant(org.tron.core.config.Parameter.BlockConstant) BadTransactionException(org.tron.core.exception.BadTransactionException) Iterables(com.google.common.collect.Iterables) SyncBlockChainMessage(org.tron.core.net.message.SyncBlockChainMessage) ItemNotFound(org.tron.core.net.message.ItemNotFound) HashMap(java.util.HashMap) Deque(java.util.Deque) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TronState(org.tron.common.overlay.server.Channel.TronState) PeerConnectionDelegate(org.tron.core.net.peer.PeerConnectionDelegate) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) BadBlockException(org.tron.core.exception.BadBlockException) LinkedList(java.util.LinkedList) Sha256Hash(org.tron.common.utils.Sha256Hash) BlockMessage(org.tron.core.net.message.BlockMessage) Message(org.tron.common.overlay.message.Message) BlockInventoryMessage(org.tron.core.net.message.BlockInventoryMessage) InventoryType(org.tron.protos.Protocol.Inventory.InventoryType) NetConstants(org.tron.core.config.Parameter.NetConstants) SyncPool(org.tron.common.overlay.server.SyncPool) FetchInvDataMessage(org.tron.core.net.message.FetchInvDataMessage) TraitorPeerException(org.tron.core.exception.TraitorPeerException) ChainInventoryMessage(org.tron.core.net.message.ChainInventoryMessage) TimeUnit(java.util.concurrent.TimeUnit) TronMessage(org.tron.core.net.message.TronMessage) PeerConnection(org.tron.core.net.peer.PeerConnection) Component(org.springframework.stereotype.Component) ReasonCode(org.tron.common.overlay.message.ReasonCode) Time(org.tron.common.utils.Time) UnLinkedBlockException(org.tron.core.exception.UnLinkedBlockException) PeerConnection(org.tron.core.net.peer.PeerConnection) FetchInvDataMessage(org.tron.core.net.message.FetchInvDataMessage) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Sha256Hash(org.tron.common.utils.Sha256Hash) LinkedList(java.util.LinkedList) BlockId(org.tron.core.capsule.BlockCapsule.BlockId) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet)

Example 5 with BlockId

use of org.tron.core.capsule.BlockCapsule.BlockId in project java-tron by tronprotocol.

the class NodeImpl method syncNextBatchChainIds.

private void syncNextBatchChainIds(PeerConnection peer) {
    try {
        Deque<BlockId> chainSummary = del.getBlockChainSummary(peer.getHeadBlockWeBothHave(), ((LinkedList<BlockId>) peer.getSyncBlockToFetch()));
        peer.setSyncChainRequested(new Pair<>((LinkedList<BlockId>) chainSummary, System.currentTimeMillis()));
        peer.sendMessage(new SyncBlockChainMessage((LinkedList<BlockId>) chainSummary));
    } catch (Exception e) {
        // TODO: use tron excpetion here
        logger.debug(e.getMessage(), e);
        // TODO: unlink?
        disconnectPeer(peer, ReasonCode.BAD_PROTOCOL);
    }
}
Also used : SyncBlockChainMessage(org.tron.core.net.message.SyncBlockChainMessage) BlockId(org.tron.core.capsule.BlockCapsule.BlockId) LinkedList(java.util.LinkedList) UnReachBlockException(org.tron.core.exception.UnReachBlockException) TronException(org.tron.core.exception.TronException) BadTransactionException(org.tron.core.exception.BadTransactionException) BadBlockException(org.tron.core.exception.BadBlockException) TraitorPeerException(org.tron.core.exception.TraitorPeerException) UnLinkedBlockException(org.tron.core.exception.UnLinkedBlockException)

Aggregations

BlockId (org.tron.core.capsule.BlockCapsule.BlockId)6 LinkedList (java.util.LinkedList)4 UnReachBlockException (org.tron.core.exception.UnReachBlockException)4 Sha256Hash (org.tron.common.utils.Sha256Hash)3 BadBlockException (org.tron.core.exception.BadBlockException)3 BadTransactionException (org.tron.core.exception.BadTransactionException)3 TraitorPeerException (org.tron.core.exception.TraitorPeerException)3 UnLinkedBlockException (org.tron.core.exception.UnLinkedBlockException)3 BlockMessage (org.tron.core.net.message.BlockMessage)3 Deque (java.util.Deque)2 List (java.util.List)2 Slf4j (lombok.extern.slf4j.Slf4j)2 Message (org.tron.common.overlay.message.Message)2 BlockCapsule (org.tron.core.capsule.BlockCapsule)2 NodeConstant (org.tron.core.config.Parameter.NodeConstant)2 TronException (org.tron.core.exception.TronException)2 MessageTypes (org.tron.core.net.message.MessageTypes)2 SyncBlockChainMessage (org.tron.core.net.message.SyncBlockChainMessage)2 TransactionMessage (org.tron.core.net.message.TransactionMessage)2 PeerConnection (org.tron.core.net.peer.PeerConnection)2