Search in sources :

Example 1 with INode

use of org.aion.p2p.INode in project aion by aionnetwork.

the class NodeMgr method moveInboundToActive.

/**
 * @param _channelHashCode int
 * @param _p2pMgr P2pMgr
 */
void moveInboundToActive(int _channelHashCode, final P2pMgr _p2pMgr) {
    Node node = inboundNodes.remove(_channelHashCode);
    if (node != null) {
        node.setConnection("inbound");
        node.setFromBootList(seedIps.contains(node.getIpStr()));
        INode previous = activeNodes.putIfAbsent(node.getIdHash(), node);
        if (previous != null)
            _p2pMgr.closeSocket(node.getChannel());
        else {
            if (_p2pMgr.showLog)
                System.out.println("<p2p action=move-inbound-to-active channel-id=" + _channelHashCode + ">");
        }
    }
}
Also used : INode(org.aion.p2p.INode) INode(org.aion.p2p.INode)

Example 2 with INode

use of org.aion.p2p.INode in project aion by aionnetwork.

the class TaskGetHeaders method run.

@Override
public void run() {
    Set<Integer> ids = new HashSet<>();
    Collection<INode> preFilter = this.p2p.getActiveNodes().values();
    List<INode> filtered = preFilter.stream().filter((n) -> n.getTotalDifficulty() != null && n.getTotalDifficulty().compareTo(this.selfTd) >= 0).collect(Collectors.toList());
    if (filtered.size() > 0) {
        Random r = new Random(System.currentTimeMillis());
        for (int i = 0; i < 2; i++) {
            INode node = filtered.get(r.nextInt(filtered.size()));
            if (!ids.contains(node.getIdHash())) {
                ids.add(node.getIdHash());
                ReqBlocksHeaders rbh = new ReqBlocksHeaders(this.fromBlock, this.syncMax);
                if (log.isDebugEnabled()) {
                    log.debug("<get-headers from-num={} size={} node={}>", fromBlock, syncMax, node.getIdShort());
                }
                this.p2p.send(node.getIdHash(), rbh);
            }
        }
    }
}
Also used : BigInteger(java.math.BigInteger) IP2pMgr(org.aion.p2p.IP2pMgr) java.util(java.util) Logger(org.slf4j.Logger) INode(org.aion.p2p.INode) ReqBlocksHeaders(org.aion.zero.impl.sync.msg.ReqBlocksHeaders) BigInteger(java.math.BigInteger) Collectors(java.util.stream.Collectors) INode(org.aion.p2p.INode) ReqBlocksHeaders(org.aion.zero.impl.sync.msg.ReqBlocksHeaders)

Example 3 with INode

use of org.aion.p2p.INode in project aion by aionnetwork.

the class ResStatusHandler method receive.

@Override
public void receive(int _nodeIdHashcode, String _displayId, final byte[] _msgBytes) {
    // for runtime survey information
    long startTime, duration;
    if (_msgBytes == null || _msgBytes.length == 0)
        return;
    startTime = System.nanoTime();
    ResStatus rs = ResStatus.decode(_msgBytes);
    if (rs == null) {
        this.log.error("<res-status decode-error from {} len: {}>", _displayId, _msgBytes.length);
        if (this.log.isTraceEnabled()) {
            this.log.trace("res-status decode-error dump: {}", ByteUtil.toHexString(_msgBytes));
        }
    }
    this.syncMgr.getSyncStats().updateResponseTime(_displayId, System.nanoTime(), RequestType.STATUS);
    this.syncMgr.getSyncStats().updatePeerBlocks(_displayId, 1, BlockType.RECEIVED);
    INode node = this.p2pMgr.getActiveNodes().get(_nodeIdHashcode);
    if (node != null && rs != null) {
        if (log.isDebugEnabled()) {
            this.log.debug("<res-status node={} best-blk={}>", _displayId, rs.getBestBlockNumber());
        }
        long remoteBestBlockNumber = rs.getBestBlockNumber();
        byte[] remoteBestBlockHash = rs.getBestHash();
        byte[] remoteTdBytes = rs.getTotalDifficulty();
        byte apiVersion = rs.getApiVersion();
        short peerCount = rs.getPeerCount();
        byte[] pendingTcBytes = rs.getPendingTxCount();
        int latency = rs.getLatency();
        if (remoteTdBytes != null && remoteBestBlockHash != null) {
            BigInteger remoteTotalDifficulty = new BigInteger(1, remoteTdBytes);
            int pendingTxCount = new BigInteger(1, pendingTcBytes).intValue();
            node.updateStatus(remoteBestBlockNumber, remoteBestBlockHash, remoteTotalDifficulty, apiVersion, peerCount, pendingTxCount, latency);
            syncMgr.updateNetworkStatus(_displayId, remoteBestBlockNumber, remoteBestBlockHash, remoteTotalDifficulty, apiVersion, peerCount, pendingTxCount, latency);
        }
    }
    duration = System.nanoTime() - startTime;
    surveyLog.debug("Receive Stage 1: process status, duration = {} ns.", duration);
}
Also used : INode(org.aion.p2p.INode) ResStatus(org.aion.zero.impl.sync.msg.ResStatus) BigInteger(java.math.BigInteger)

Example 4 with INode

use of org.aion.p2p.INode in project aion by aionnetwork.

the class BlockPropagationTest method testPropagateBlockToPeer.

// given two peers, and one sends you a new block, propagate to the other
@Test
public void testPropagateBlockToPeer() {
    List<ECKey> accounts = generateDefaultAccounts();
    StandaloneBlockchain.Bundle bundle = new StandaloneBlockchain.Builder().withValidatorConfiguration("simple").withDefaultAccounts(accounts).build();
    MiningBlock block = bundle.bc.createNewMiningBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
    assertThat(block.getNumber()).isEqualTo(1);
    byte[] sender = HashUtil.h256("node1".getBytes());
    byte[] receiver = HashUtil.h256("receiver".getBytes());
    NodeMock senderMock = new NodeMock(sender, 1);
    NodeMock receiverMock = new NodeMock(receiver, 0);
    Map<Integer, INode> node = new HashMap<>();
    node.put(1, senderMock);
    node.put(2, receiverMock);
    AtomicInteger times = new AtomicInteger();
    P2pMock p2pMock = new P2pMock(node) {

        @Override
        public void send(int _nodeId, String s, Msg _msg) {
            if (_nodeId != receiverMock.getIdHash()) {
                throw new RuntimeException("should only send to receiver");
            }
            times.getAndIncrement();
        }
    };
    StandaloneBlockchain.Bundle anotherBundle = new StandaloneBlockchain.Builder().withValidatorConfiguration("simple").withDefaultAccounts(accounts).withEventManger(this.loadEventMgr()).build();
    assertThat(bundle.bc.genesis.getHash()).isEqualTo(anotherBundle.bc.genesis.getHash());
    assertThat(block.getParentHash()).isEqualTo(bundle.bc.genesis.getHash());
    assertThat(block.getParentHash()).isEqualTo(anotherBundle.bc.genesis.getHash());
    Block bestBlock = bundle.bc.getBestBlock();
    assertThat(bestBlock.getHash()).isEqualTo(anotherBundle.bc.genesis.getHash());
    SyncStats syncStats = new SyncStats(bestBlock.getNumber(), true);
    BlockPropagationHandler handler = new BlockPropagationHandler(1024, // NOTE: not the same blockchain that generated the block
    anotherBundle.bc, syncStats, p2pMock, anotherBundle.bc.getBlockHeaderValidator(), false, (byte) 2, new AionPendingStateImpl(anotherBundle.bc, blockEnergyUpperBound, pendingTransactionTimeout, enablePoolBackup, enableSeedMode, enablePoolDump, new PendingTxCallback(new ArrayList<>()), new NetworkBestBlockCallback(AionImpl.inst()), new TransactionBroadcastCallback(AionImpl.inst()), true));
    // block is processed
    assertThat(handler.processIncomingBlock(senderMock.getIdHash(), "test", block)).isEqualTo(BlockPropagationHandler.PropStatus.PROP_CONNECTED);
    assertThat(times.get()).isEqualTo(1);
}
Also used : INode(org.aion.p2p.INode) TransactionBroadcastCallback(org.aion.zero.impl.blockchain.AionImpl.TransactionBroadcastCallback) HashMap(java.util.HashMap) ECKey(org.aion.crypto.ECKey) MiningBlock(org.aion.zero.impl.types.MiningBlock) Msg(org.aion.p2p.Msg) AionPendingStateImpl(org.aion.zero.impl.pendingState.AionPendingStateImpl) BlockPropagationHandler(org.aion.zero.impl.sync.handler.BlockPropagationHandler) NetworkBestBlockCallback(org.aion.zero.impl.blockchain.AionImpl.NetworkBestBlockCallback) PendingTxCallback(org.aion.zero.impl.blockchain.AionImpl.PendingTxCallback) StandaloneBlockchain(org.aion.zero.impl.blockchain.StandaloneBlockchain) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MiningBlock(org.aion.zero.impl.types.MiningBlock) Block(org.aion.zero.impl.types.Block) Test(org.junit.Test)

Example 5 with INode

use of org.aion.p2p.INode in project aion by aionnetwork.

the class BlockPropagationTest method testBlockPropagationReceiver.

/**
 * Test that we don't propagate back to the sender
 */
@Test
public void testBlockPropagationReceiver() {
    List<ECKey> accounts = generateDefaultAccounts();
    StandaloneBlockchain.Bundle bundle = new StandaloneBlockchain.Builder().withValidatorConfiguration("simple").withDefaultAccounts(accounts).build();
    MiningBlock block = bundle.bc.createNewMiningBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
    assertThat(block.getNumber()).isEqualTo(1);
    byte[] sender = HashUtil.h256("node1".getBytes());
    NodeMock senderMock = new NodeMock(sender, 1);
    Map<Integer, INode> node = new HashMap<>();
    node.put(1, senderMock);
    SyncStats syncStats = new SyncStats(block.getNumber(), true);
    P2pMock p2pMock = new P2pMock(node) {

        @Override
        public void send(int _nodeId, String s, Msg _msg) {
            throw new RuntimeException("should not have called send");
        }
    };
    StandaloneBlockchain.Bundle anotherBundle = new StandaloneBlockchain.Builder().withValidatorConfiguration("simple").withDefaultAccounts(accounts).withEventManger(this.loadEventMgr()).build();
    BlockPropagationHandler handler = new BlockPropagationHandler(1024, // NOTE: not the same blockchain that generated the block
    anotherBundle.bc, syncStats, p2pMock, anotherBundle.bc.getBlockHeaderValidator(), false, (byte) 2, new AionPendingStateImpl(anotherBundle.bc, blockEnergyUpperBound, pendingTransactionTimeout, enablePoolBackup, enableSeedMode, enablePoolDump, new PendingTxCallback(new ArrayList<>()), new NetworkBestBlockCallback(AionImpl.inst()), new TransactionBroadcastCallback(AionImpl.inst()), true));
    assertThat(handler.processIncomingBlock(senderMock.getIdHash(), "test", block)).isEqualTo(BlockPropagationHandler.PropStatus.CONNECTED);
}
Also used : Msg(org.aion.p2p.Msg) AionPendingStateImpl(org.aion.zero.impl.pendingState.AionPendingStateImpl) INode(org.aion.p2p.INode) TransactionBroadcastCallback(org.aion.zero.impl.blockchain.AionImpl.TransactionBroadcastCallback) BlockPropagationHandler(org.aion.zero.impl.sync.handler.BlockPropagationHandler) HashMap(java.util.HashMap) NetworkBestBlockCallback(org.aion.zero.impl.blockchain.AionImpl.NetworkBestBlockCallback) PendingTxCallback(org.aion.zero.impl.blockchain.AionImpl.PendingTxCallback) ECKey(org.aion.crypto.ECKey) StandaloneBlockchain(org.aion.zero.impl.blockchain.StandaloneBlockchain) MiningBlock(org.aion.zero.impl.types.MiningBlock) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) Test(org.junit.Test)

Aggregations

INode (org.aion.p2p.INode)55 Test (org.junit.Test)30 BigInteger (java.math.BigInteger)11 ArrayList (java.util.ArrayList)9 HashMap (java.util.HashMap)8 Map (java.util.Map)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 ECKey (org.aion.crypto.ECKey)4 IP2pMgr (org.aion.p2p.IP2pMgr)4 Msg (org.aion.p2p.Msg)4 NetworkBestBlockCallback (org.aion.zero.impl.blockchain.AionImpl.NetworkBestBlockCallback)4 PendingTxCallback (org.aion.zero.impl.blockchain.AionImpl.PendingTxCallback)4 TransactionBroadcastCallback (org.aion.zero.impl.blockchain.AionImpl.TransactionBroadcastCallback)4 StandaloneBlockchain (org.aion.zero.impl.blockchain.StandaloneBlockchain)4 AionPendingStateImpl (org.aion.zero.impl.pendingState.AionPendingStateImpl)4 BlockHeader (org.aion.zero.impl.types.BlockHeader)4 IOException (java.io.IOException)3 ByteBuffer (java.nio.ByteBuffer)3 SelectionKey (java.nio.channels.SelectionKey)3 ServerSocketChannel (java.nio.channels.ServerSocketChannel)3