org.aion.p2p.INode

Here are the examples of the java api org.aion.p2p.INode taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

63 Examples 7

19 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test
public void testTempNodesTake() {
    String ip = "127.0.0.1";
    String[] nodes = new String[] { "p2p://" + UUID.randomUUID() + "@127.0.0.1:30123", "p2p://" + UUID.randomUUID() + "@127.0.0.1:30321" };
    for (String nodeL : nodes) {
        Node node = Node.parseP2p(nodeL);
        replacedertNotNull(node);
        nMgr.addTempNode(node);
        nMgr.seedIpAdd(node.getIpStr());
    }
    replacedertEquals(2, nMgr.tempNodesSize());
    INode node;
    while (nMgr.tempNodesSize() != 0) {
        node = nMgr.tempNodesTake();
        replacedertEquals(ip, node.getIpStr());
        replacedertTrue(node.getIfFromBootList());
        replacedertTrue(nMgr.isSeedIp(ip));
    }
    replacedertEquals(0, nMgr.tempNodesSize());
}

19 Source : NodeMgrTest.java
with MIT License
from aionnetwork

private Runnable moveTempNodeToInbound(Deque<INode> inbound) {
    return () -> {
        INode tempNode = nMgr.tempNodesTake();
        if (tempNode != null) {
            nMgr.addInboundNode(tempNode);
            inbound.addLast(tempNode);
        }
    };
}

19 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test
public void testTempNodeMax() {
    String[] nodes_max = new String[MAX_TEMP_NODES];
    int ip = 0;
    int port = 10000;
    for (int i = 0; i < nodes_max.length; i++) {
        nodes_max[i] = "p2p://" + UUID.randomUUID() + "@255.255.255." + ip++ + ":" + port++;
    }
    for (String nodeL : nodes_max) {
        INode node = Node.parseP2p(nodeL);
        replacedertNotNull(node);
        nMgr.addTempNode(node);
        nMgr.seedIpAdd(node.getIpStr());
    }
    replacedertEquals(MAX_TEMP_NODES, nMgr.tempNodesSize());
    // future nodes will be rejected due to the reached limit
    ip = 0;
    for (int i = 0; i < nodes_max.length; i++) {
        nodes_max[i] = "p2p://" + UUID.randomUUID() + "@255.255.254." + ip++ + ":" + port++;
    }
    for (String nodeL : nodes_max) {
        INode node = Node.parseP2p(nodeL);
        replacedertNotNull(node);
        nMgr.addTempNode(node);
        nMgr.seedIpAdd(node.getIpStr());
        replacedertEquals(MAX_TEMP_NODES, nMgr.tempNodesSize());
    }
}

19 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testAllocate() {
    INode node = nMgr.allocNode(ip2, 1);
    replacedertNotNull(node);
    replacedertFalse(node.getIfFromBootList());
    nMgr.seedIpAdd(ip2);
    node = nMgr.allocNode(ip2, 1);
    replacedertNotNull(node);
    replacedertTrue(node.getIfFromBootList());
}

19 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 10_000)
public void testTempNode() {
    nMgr.addTempNode(node);
    replacedertEquals(1, nMgr.tempNodesSize());
    nMgr.addTempNode(node);
    replacedertEquals(1, nMgr.tempNodesSize());
    String nl = "p2p://" + nodeId1 + "@" + ip1 + ":" + port1;
    INode node = Node.parseP2p(nl);
    nMgr.addTempNode(node);
    replacedertEquals(2, nMgr.tempNodesSize());
}

19 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testGetRandom() {
    replacedertNull(nMgr.getRandom());
    INode node = nMgr.allocNode(ip2, 1);
    addNodetoInbound(node, UUID.fromString(nodeId1));
    nMgr.movePeerToActive(node.getChannel().hashCode(), "inbound");
    INode nodeRandom = nMgr.getRandom();
    replacedertNotNull(node);
    replacedertEquals(node, nodeRandom);
}

19 Source : NodeMgrTest.java
with MIT License
from aionnetwork

private Runnable moveTempNodeToOutbound(Deque<INode> outbound) {
    return () -> {
        INode tempNode = nMgr.tempNodesTake();
        if (tempNode != null) {
            nMgr.addOutboundNode(tempNode);
            outbound.addLast(tempNode);
        }
    };
}

19 Source : NodeMgr.java
with MIT License
from aionnetwork

/**
 * @param selfShortId String
 */
@Override
public String dumpNodeInfo(String selfShortId, boolean completeInfo) {
    StringBuilder sb = new StringBuilder();
    sb.append("\n");
    sb.append(String.format("=========================================================================== p2p-status-%6s =============================================================================\n", selfShortId));
    sb.append(String.format(" temp[%3d] inbound[%3d] outbound[%3d] active[%3d]                           id - node short id, s - seed node, td - total difficulty, # - block number, bv - binary version\n", tempNodesSize(), inboundNodes.size(), outboundNodes.size(), activeNodes.size()));
    sb.append(appendColumnFormat());
    if (myNode != null) {
        sb.append(appendNodeInfo(myNode)).append("\n");
    }
    List<INode> sorted = new ArrayList<>(activeNodes.values());
    if (sorted.size() > 0) {
        sorted.sort((n1, n2) -> {
            int tdCompare = n2.getTotalDifficulty().compareTo(n1.getTotalDifficulty());
            if (tdCompare == 0) {
                Long n2Bn = n2.getBestBlockNumber();
                Long n1Bn = n1.getBestBlockNumber();
                return n2Bn.compareTo(n1Bn);
            } else {
                return tdCompare;
            }
        });
        for (INode n : sorted) {
            try {
                if (!completeInfo && !n.getIfFromBootList()) {
                    continue;
                }
                sb.append(appendNodeInfo(n));
            } catch (Exception ex) {
                p2pLOG.error("<NodeMgr dumpNodeInfo exception>", ex);
            }
        }
    }
    return sb.toString();
}

19 Source : NodeMgr.java
with MIT License
from aionnetwork

@Override
public void addTempNode(final INode _n) {
    if (_n == null)
        return;
    int key = _n.getIdHash();
    // The bootlist node will be added back into the tempNodes incase all the connections dropped.
    if (!tempNodesKeys.contains(key) && (notActiveNode(key) || _n.getIfFromBootList())) {
        if (tempNodes.offerLast(_n)) {
            tempNodesKeys.add(key);
        }
    }
}

19 Source : NodeMgr.java
with MIT License
from aionnetwork

private String appendNodeInfo(INode n) {
    return String.format(" %6s %c %39s %8d %64s %15s %5d %8s %16s\n", n.getIdShort(), n.getIfFromBootList() ? 'y' : ' ', n.getTotalDifficulty().toString(10), n.getBestBlockNumber(), n.getBestBlockHash() == null ? "" : bytesToHex(n.getBestBlockHash()), n.getIpStr(), n.getPort(), n.getConnection(), n.getBinaryVersion());
}

19 Source : NodeMgr.java
with MIT License
from aionnetwork

@Override
public void addOutboundNode(final INode _n) {
    if (p2pLOG.isTraceEnabled()) {
        p2pLOG.trace("<addOutboundNode {}>", _n.toString());
    }
    outboundNodes.put(_n.getIdHash(), _n);
}

19 Source : NodeMgr.java
with MIT License
from aionnetwork

@Override
public void addInboundNode(final INode _n) {
    if (p2pLOG.isTraceEnabled()) {
        p2pLOG.trace("<addInboundNode {}>", _n.toString());
    }
    INode node = inboundNodes.put(_n.getChannel().hashCode(), _n);
    if (node != null) {
        p2pLOG.error("The inbound node={} was overwritten by node={}.", node, _n);
    }
}

19 Source : SyncHeaderRequestManager.java
with MIT License
from aionnetwork

/**
 * Checks that the peer's total difficulty is higher than or equal to the local chain.
 */
private static boolean isAdequateTotalDifficulty(INode peer, BigInteger totalDifficulty) {
    return peer.getTotalDifficulty() != null && peer.getTotalDifficulty().compareTo(totalDifficulty) >= 0;
}

19 Source : NodeWrapper.java
with MIT License
from aionnetwork

/**
 * Facilitates preplaceding peer information to the API without relying on the p2p module interfaces.
 */
public clreplaced NodeWrapper {

    INode peer;

    public NodeWrapper(INode peer) {
        this.peer = peer;
    }

    public String getIdShort() {
        return peer.getIdShort();
    }

    public byte[] getId() {
        return peer.getId();
    }

    public int getIdHash() {
        return peer.getIdHash();
    }

    public String getBinaryVersion() {
        return peer.getBinaryVersion();
    }

    public long getBestBlockNumber() {
        return peer.getBestBlockNumber();
    }

    public BigInteger getTotalDifficulty() {
        return peer.getTotalDifficulty();
    }

    public byte[] getIp() {
        return peer.getIp();
    }

    public String getIpStr() {
        return peer.getIpStr();
    }

    public int getPort() {
        return peer.getPort();
    }

    public long getTimestamp() {
        return peer.getTimestamp();
    }
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testMoveInboundToActive() {
    INode node = nMgr.allocNode(ip2, 1);
    addNodetoInbound(node, UUID.fromString(nodeId1));
    nMgr.movePeerToActive(node.getChannel().hashCode(), "inbound");
    replacedertNull(nMgr.getInboundNode(node.getChannel().hashCode()));
    INode activeNode = nMgr.getActiveNode(node.getIdHash());
    replacedertNotNull(activeNode);
    replacedertEquals(node, activeNode);
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test
public void testTimeoutInbound() {
    INode node = nMgr.allocNode(ip2, 1);
    addNodetoInbound(node, UUID.fromString(nodeId1));
    nMgr.timeoutCheck(System.currentTimeMillis() + NodeMgr.TIMEOUT_INBOUND_NODES + 1);
    replacedertNull(nMgr.getInboundNode(channel.hashCode()));
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test
public void testTimeoutActive() {
    INode node = nMgr.allocNode(ip2, 1);
    addNodetoInbound(node, UUID.fromString(nodeId1));
    nMgr.movePeerToActive(node.getChannel().hashCode(), "inbound");
    INode activeNode = nMgr.getActiveNode(node.getIdHash());
    replacedertNotNull(activeNode);
    replacedertEquals(node, activeNode);
    nMgr.timeoutCheck(System.currentTimeMillis() + NodeMgr.MIN_TIMEOUT_ACTIVE_NODES + 1);
    replacedertNull(nMgr.getActiveNode(node.getIdHash()));
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testDumpNodeInfo() {
    String dump = nMgr.dumpNodeInfo("testId", false);
    replacedertNotNull(dump);
    INode node = nMgr.allocNode(ip1, 1);
    addNodetoOutbound(node, UUID.randomUUID());
    nMgr.movePeerToActive(node.getIdHash(), "outbound");
    String dump2 = nMgr.dumpNodeInfo("testId", false);
    replacedertEquals(dump.length(), dump2.length());
    String dump3 = nMgr.dumpNodeInfo("testId", true);
    replacedertTrue(dump3.length() > dump2.length());
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test
public void testMoveSelfToActive() {
    INode node = nMgr.allocNode(ip2, 1);
    addNodetoOutbound(node, UUID.fromString(nodeId1));
    when(p2p.isSelf(node)).thenReturn(true);
    nMgr.movePeerToActive(node.getIdHash(), "outbound");
    replacedertTrue(nMgr.getActiveNodesMap().isEmpty());
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test
public void testMovePeerToActiveFromInbound() {
    INode node = nMgr.allocNode(ip2, 1);
    node.setChannel(channel);
    nMgr.movePeerToActive(node.getChannel().hashCode(), "inbound");
    replacedertTrue(nMgr.getActiveNodesMap().isEmpty());
    nMgr.addInboundNode(node);
    // wrong type & key
    nMgr.movePeerToActive(node.getChannel().hashCode(), "outbound");
    replacedertTrue(nMgr.getActiveNodesMap().isEmpty());
    // move from inbound
    nMgr.movePeerToActive(node.getChannel().hashCode(), "inbound");
    replacedertEquals(1, nMgr.getActiveNodesMap().size());
    // move same node again
    nMgr.movePeerToActive(node.getChannel().hashCode(), "inbound");
    replacedertEquals(1, nMgr.getActiveNodesMap().size());
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testMoveOutboundToActive() {
    INode node = nMgr.allocNode(ip2, 1);
    addNodetoOutbound(node, UUID.fromString(nodeId1));
    nMgr.movePeerToActive(node.getIdHash(), "outbound");
    replacedertNull(nMgr.getOutboundNode(node.getIdHash()));
    INode activeNode = nMgr.getActiveNode(node.getIdHash());
    replacedertNotNull(activeNode);
    replacedertEquals(node, activeNode);
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test
public void testTimeoutOutbound() {
    INode node = nMgr.allocNode(ip2, 1);
    addNodetoOutbound(node, UUID.fromString(nodeId1));
    nMgr.timeoutCheck(System.currentTimeMillis() + NodeMgr.TIMEOUT_OUTBOUND_NODES + 1);
    replacedertNull(nMgr.getOutboundNode(node.getIdHash()));
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testShutDown() {
    INode node = nMgr.allocNode(ip2, 1);
    addNodetoOutbound(node, UUID.randomUUID());
    node = nMgr.allocNode(ip1, 1);
    addNodetoOutbound(node, UUID.randomUUID());
    nMgr.movePeerToActive(node.getIdHash(), "outbound");
    node = nMgr.allocNode("1.1.1.1", 1);
    addNodetoInbound(node, UUID.randomUUID());
    replacedertEquals(1, nMgr.activeNodesSize());
    nMgr.shutdown();
    replacedertTrue(nMgr.getActiveNodesMap().isEmpty());
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

private Runnable movePeerToActive(Deque<INode> inbound, Deque<INode> outbound) {
    return () -> {
        INode newNode;
        boolean fromInbound = r.nextBoolean();
        if (fromInbound) {
            newNode = inbound.pollFirst();
            if (newNode != null) {
                nMgr.movePeerToActive(newNode.getChannel().hashCode(), "inbound");
            }
        } else {
            newNode = outbound.pollFirst();
            if (newNode != null) {
                nMgr.movePeerToActive(newNode.getIdHash(), "outbound");
            }
        }
    };
}

18 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testNotAtOutBoundList() {
    INode node = nMgr.allocNode(ip2, 1);
    addNodetoOutbound(node, UUID.fromString(nodeId1));
    replacedertFalse(nMgr.notAtOutboundList(node.getIdHash()));
    node = nMgr.allocNode(ip1, 1);
    replacedertTrue(nMgr.notAtOutboundList(node.getIdHash()));
}

18 Source : P2pMgr.java
with MIT License
from aionnetwork

/**
 * @implNote Compares the port and id to the given node to allow connections to the same id and
 *     different port. Does not compare IP values since the self IP is often recorded as 0.0.0.0
 *     in the configuration file and cannot be inferred reliably by the node itself.
 */
@Override
public boolean isSelf(INode node) {
    return selfNodeIdHash == node.getIdHash() && selfPort == node.getPort() && Arrays.equals(selfNodeId, node.getId());
}

18 Source : P2pMgr.java
with MIT License
from aionnetwork

/**
 * @param _node Node
 * @return boolean
 */
@Override
public boolean validateNode(final INode _node) {
    if (_node != null) {
        boolean notSelfId = !Arrays.equals(_node.getId(), this.selfNodeId);
        boolean notSameIpOrPort = !(Arrays.equals(selfIp, _node.getIp()) && selfPort == _node.getPort());
        boolean notActive = nodeMgr.notActiveNode(_node.getPeerId());
        boolean notOutbound = nodeMgr.notAtOutboundList(_node.getPeerId());
        return notSelfId && notSameIpOrPort && notActive && notOutbound;
    } else {
        return false;
    }
}

18 Source : NodeMgr.java
with MIT License
from aionnetwork

@Override
public INode allocNode(String ip, int p0) {
    INode n = new Node(ip, p0);
    if (seedIps.contains(ip)) {
        n.setFromBootList(true);
    }
    return n;
}

18 Source : NodeMgr.java
with MIT License
from aionnetwork

public void dropActive(int nodeIdHash, String _reason) {
    INode node = null;
    try {
        node = activeNodes.remove(nodeIdHash);
    } catch (Exception e) {
        p2pLOG.info("<dropActive exception>", e);
    }
    if (node == null) {
        return;
    }
    p2pMgr.closeSocket(node.getChannel(), _reason);
}

18 Source : SyncMgr.java
with MIT License
from aionnetwork

/**
 * Makes a status request to each active peer.
 */
private void requestStatus() {
    Thread.currentThread().setName("sync-gs");
    for (INode node : p2pMgr.getActiveNodes().values()) {
        p2pMgr.send(node.getIdHash(), node.getIdShort(), cachedReqStatus);
        stats.updateTotalRequestsToPeer(node.getIdShort(), RequestType.STATUS);
        stats.updateRequestTime(node.getIdShort(), System.nanoTime(), RequestType.STATUS);
    }
}

17 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testGetActiveNodesList() {
    INode node = nMgr.allocNode(ip2, 1);
    node.setChannel(channel);
    node.setId(nodeId2.getBytes(StandardCharsets.UTF_8));
    nMgr.addInboundNode(node);
    replacedertEquals(0, nMgr.activeNodesSize());
    nMgr.movePeerToActive(channel.hashCode(), "inbound");
    replacedertEquals(1, nMgr.activeNodesSize());
    List<INode> active = nMgr.getActiveNodesList();
    for (INode activeN : active) {
        replacedertEquals(ip2, activeN.getIpStr());
    }
}

17 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test
public void testMovePeerToActiveFromOutbound() {
    INode node = nMgr.allocNode(ip2, 1);
    node.setChannel(channel);
    addNodetoOutbound(node, UUID.fromString(nodeId1));
    // wrong type & key
    nMgr.movePeerToActive(node.getIdHash(), "inbound");
    replacedertTrue(nMgr.getActiveNodesMap().isEmpty());
    // move first node
    nMgr.movePeerToActive(node.getIdHash(), "outbound");
    replacedertEquals(1, nMgr.getActiveNodesMap().size());
    // move different node
    node = nMgr.allocNode(ip1, 1);
    addNodetoOutbound(node, UUID.fromString(nodeId2));
    nMgr.movePeerToActive(node.getIdHash(), "outbound");
    replacedertEquals(2, nMgr.getActiveNodesMap().size());
    // move same node again
    nMgr.movePeerToActive(node.getIdHash(), "outbound");
    replacedertEquals(2, nMgr.getActiveNodesMap().size());
}

17 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testGetActiveNodesMap() {
    INode node = nMgr.allocNode(ip2, 1);
    addNodetoInbound(node, UUID.fromString(nodeId1));
    nMgr.movePeerToActive(node.getChannel().hashCode(), "inbound");
    Map activeMap = nMgr.getActiveNodesMap();
    replacedertNotNull(activeMap);
    replacedertEquals(1, activeMap.size());
}

17 Source : NodeMgr.java
with MIT License
from aionnetwork

@Override
public void ban(int _nodeIdHash) {
    try {
        INode node = activeNodes.get(_nodeIdHash);
        if (node != null) {
            node.getPeerMetric().ban();
        }
    } catch (NullPointerException e) {
        p2pLOG.info("<p2p-ban null exception>", e);
    }
}

17 Source : NodeMgr.java
with MIT License
from aionnetwork

@Override
public INode tempNodesTake() {
    INode node = tempNodes.pollFirst();
    if (node != null) {
        tempNodesKeys.remove(node.getIdHash());
    }
    return node;
}

16 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testAddInOutBoundNode() {
    INode node = nMgr.allocNode(ip1, 1);
    node.setChannel(channel);
    node.setId(nodeId1.getBytes(StandardCharsets.UTF_8));
    nMgr.addInboundNode(node);
    INode iNode = nMgr.getInboundNode(channel.hashCode());
    replacedertEquals(ip1, iNode.getIpStr());
    nMgr.addOutboundNode(node);
    INode oNode = nMgr.getOutboundNode(node.getIdHash());
    replacedertEquals(ip1, oNode.getIpStr());
}

16 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testDumpNodeInfo2() {
    String dump = nMgr.dumpNodeInfo("testId", false);
    replacedertNotNull(dump);
    nMgr.seedIpAdd(ip1);
    INode node = nMgr.allocNode(ip1, 1);
    byte[] rHash = new byte[32];
    r.nextBytes(rHash);
    node.updateStatus(r.nextLong(), rHash, BigInteger.ONE, (byte) r.nextInt(), (short) r.nextInt(), r.nextInt(), r.nextInt());
    addNodetoOutbound(node, UUID.randomUUID());
    nMgr.movePeerToActive(node.getIdHash(), "outbound");
    String dump2 = nMgr.dumpNodeInfo("testId", false);
    replacedertTrue(dump2.length() > dump.length());
    String dump3 = nMgr.dumpNodeInfo("testId", true);
    replacedertEquals(dump3.length(), dump2.length());
}

16 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testDropActive() {
    INode node = nMgr.allocNode(ip2, 1);
    node.setChannel(channel);
    node.setId(nodeId2.getBytes(StandardCharsets.UTF_8));
    nMgr.addInboundNode(node);
    replacedertEquals(0, nMgr.activeNodesSize());
    nMgr.movePeerToActive(channel.hashCode(), "inbound");
    replacedertEquals(1, nMgr.activeNodesSize());
    // will not drop
    nMgr.dropActive(node.getIdHash() - 1, "close");
    replacedertEquals(1, nMgr.activeNodesSize());
    // will drop
    nMgr.dropActive(node.getIdHash(), "close");
    replacedertEquals(0, nMgr.activeNodesSize());
}

16 Source : NodeMgrTest.java
with MIT License
from aionnetwork

private void addActiveNode() {
    INode node = nMgr.allocNode(ip1, 1);
    byte[] rHash = new byte[32];
    r.nextBytes(rHash);
    node.updateStatus(r.nextLong(), rHash, BigInteger.valueOf(r.nextLong()), (byte) r.nextInt(), (short) r.nextInt(), r.nextInt(), r.nextInt());
    addNodetoOutbound(node, UUID.randomUUID());
    nMgr.movePeerToActive(node.getIdHash(), "outbound");
}

16 Source : P2pMgr.java
with MIT License
from aionnetwork

/**
 * Constructs node info after handshake request success.
 */
private void handleHandshakeRequest(final ChannelBuffer buffer, int channelHash, final byte[] nodeId, int netId, int port, final byte[] revision) {
    INode node = nodeMgr.getInboundNode(channelHash);
    if (node != null && node.getPeerMetric().notBan()) {
        p2pLOG.debug("netId={}, nodeId={} port={} rev={}", netId, new String(nodeId), port, revision);
        p2pLOG.trace("node {}", node.toString());
        if (isCorrectNetwork(netId)) {
            buffer.setNodeIdHash(Arrays.hashCode(nodeId));
            buffer.setDisplayId(new String(Arrays.copyOfRange(nodeId, 0, 6)));
            node.setId(nodeId);
            node.setPort(port);
            // handshake 1
            if (revision != null) {
                String binaryVersion;
                binaryVersion = new String(revision, StandardCharsets.UTF_8);
                node.setBinaryVersion(binaryVersion);
                nodeMgr.movePeerToActive(channelHash, "inbound");
                send(node.getIdHash(), node.getIdShort(), cachedResHandshake1);
            }
        } else {
            p2pLOG.debug("handshake-rule-fail");
        }
    }
}

16 Source : P2pMgr.java
with MIT License
from aionnetwork

private void handleHandshakeResponse(int nodeIdHash, String binaryVersion) {
    INode node = nodeMgr.getOutboundNode(nodeIdHash);
    if (node != null && node.getPeerMetric().notBan()) {
        node.refreshTimestamp();
        node.setBinaryVersion(binaryVersion);
        nodeMgr.movePeerToActive(node.getIdHash(), "outbound");
    }
}

16 Source : P2pMgr.java
with MIT License
from aionnetwork

private void handleKernelMessage(int nodeIdHash, int route, final byte[] msgBytes) {
    INode node = nodeMgr.getActiveNode(nodeIdHash);
    if (node != null) {
        String nodeDisplayId = node.getIdShort();
        node.refreshTimestamp();
        List<Handler> hs = handlers.get(route);
        if (hs != null) {
            scheduledWorkers.execute(() -> receiveMessage(nodeIdHash, nodeDisplayId, msgBytes, hs));
        }
    } else {
        p2pLOG.debug("handleKernelMsg can't find hash{}", nodeIdHash);
    }
}

16 Source : NodeMgr.java
with MIT License
from aionnetwork

public clreplaced NodeMgr implements INodeMgr {

    // node timeout constants
    static final int TIMEOUT_INBOUND_NODES = 10_000;

    static final int TIMEOUT_OUTBOUND_NODES = 20_000;

    static final int MIN_TIMEOUT_ACTIVE_NODES = 10_000;

    static final int MAX_TIMEOUT_ACTIVE_NODES = 60_000;

    private static final Random random = new SecureRandom();

    private static final char[] hexArray = "0123456789abcdef".toCharArray();

    private static Logger p2pLOG;

    private final int maxActiveNodes;

    private final int maxTempNodes;

    private final Set<String> seedIps = new HashSet<>();

    private final IP2pMgr p2pMgr;

    private final Deque<INode> tempNodes;

    private final Set<Integer> tempNodesKeys = new ConcurrentSkipListSet<>();

    private final Map<Integer, INode> outboundNodes = new ConcurrentHashMap<>();

    private final Map<Integer, INode> inboundNodes = new ConcurrentHashMap<>();

    private final Map<Integer, INode> activeNodes = new ConcurrentHashMap<>();

    private int avgLatency = 0;

    private final INode myNode;

    public NodeMgr(IP2pMgr _p2pMgr, int _maxActiveNodes, int _maxTempNodes, Logger _logger, INode myNode) {
        this.maxActiveNodes = _maxActiveNodes;
        this.maxTempNodes = _maxTempNodes;
        this.p2pMgr = _p2pMgr;
        p2pLOG = _logger;
        // this data structure is preferable to ConcurrentLinkedDeque because
        // 1. we only really need to access the data one thread at a time
        // 2. it allows bounding the collection size
        tempNodes = new LinkedBlockingDeque<>(maxTempNodes);
        this.myNode = myNode;
    }

    private static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    /**
     * @param selfShortId String
     */
    @Override
    public String dumpNodeInfo(String selfShortId, boolean completeInfo) {
        StringBuilder sb = new StringBuilder();
        sb.append("\n");
        sb.append(String.format("=========================================================================== p2p-status-%6s =============================================================================\n", selfShortId));
        sb.append(String.format(" temp[%3d] inbound[%3d] outbound[%3d] active[%3d]                           id - node short id, s - seed node, td - total difficulty, # - block number, bv - binary version\n", tempNodesSize(), inboundNodes.size(), outboundNodes.size(), activeNodes.size()));
        sb.append(appendColumnFormat());
        if (myNode != null) {
            sb.append(appendNodeInfo(myNode)).append("\n");
        }
        List<INode> sorted = new ArrayList<>(activeNodes.values());
        if (sorted.size() > 0) {
            sorted.sort((n1, n2) -> {
                int tdCompare = n2.getTotalDifficulty().compareTo(n1.getTotalDifficulty());
                if (tdCompare == 0) {
                    Long n2Bn = n2.getBestBlockNumber();
                    Long n1Bn = n1.getBestBlockNumber();
                    return n2Bn.compareTo(n1Bn);
                } else {
                    return tdCompare;
                }
            });
            for (INode n : sorted) {
                try {
                    if (!completeInfo && !n.getIfFromBootList()) {
                        continue;
                    }
                    sb.append(appendNodeInfo(n));
                } catch (Exception ex) {
                    p2pLOG.error("<NodeMgr dumpNodeInfo exception>", ex);
                }
            }
        }
        return sb.toString();
    }

    private static String appendColumnFormat() {
        return "\n" + String.format(" %6s", "id") + String.format(" %c", 's') + String.format(" %39s", "td") + String.format(" %8s", "#") + String.format(" %64s", "hash") + String.format(" %15s", "ip") + String.format(" %5s", "port") + String.format(" %8s", "conn") + String.format(" %16s", "bv") + "\n---------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n";
    }

    private String appendNodeInfo(INode n) {
        return String.format(" %6s %c %39s %8d %64s %15s %5d %8s %16s\n", n.getIdShort(), n.getIfFromBootList() ? 'y' : ' ', n.getTotalDifficulty().toString(10), n.getBestBlockNumber(), n.getBestBlockHash() == null ? "" : bytesToHex(n.getBestBlockHash()), n.getIpStr(), n.getPort(), n.getConnection(), n.getBinaryVersion());
    }

    /**
     * @param _ip String
     */
    @Override
    public void seedIpAdd(String _ip) {
        this.seedIps.add(_ip);
    }

    @Override
    public boolean isSeedIp(String _ip) {
        return this.seedIps.contains(_ip);
    }

    @Override
    public void addTempNode(final INode _n) {
        if (_n == null)
            return;
        int key = _n.getIdHash();
        // The bootlist node will be added back into the tempNodes incase all the connections dropped.
        if (!tempNodesKeys.contains(key) && (notActiveNode(key) || _n.getIfFromBootList())) {
            if (tempNodes.offerLast(_n)) {
                tempNodesKeys.add(key);
            }
        }
    }

    @Override
    public void addInboundNode(final INode _n) {
        if (p2pLOG.isTraceEnabled()) {
            p2pLOG.trace("<addInboundNode {}>", _n.toString());
        }
        INode node = inboundNodes.put(_n.getChannel().hashCode(), _n);
        if (node != null) {
            p2pLOG.error("The inbound node={} was overwritten by node={}.", node, _n);
        }
    }

    @Override
    public void addOutboundNode(final INode _n) {
        if (p2pLOG.isTraceEnabled()) {
            p2pLOG.trace("<addOutboundNode {}>", _n.toString());
        }
        outboundNodes.put(_n.getIdHash(), _n);
    }

    @Override
    public INode tempNodesTake() {
        INode node = tempNodes.pollFirst();
        if (node != null) {
            tempNodesKeys.remove(node.getIdHash());
        }
        return node;
    }

    @Override
    public int tempNodesSize() {
        return tempNodes.size();
    }

    @Override
    public int activeNodesSize() {
        return activeNodes.size();
    }

    @Override
    public boolean notActiveNode(int k) {
        return !activeNodes.containsKey(k);
    }

    @Override
    public INode getActiveNode(int k) {
        return activeNodes.get(k);
    }

    @Override
    public INode getInboundNode(int k) {
        return inboundNodes.get(k);
    }

    @Override
    public INode getOutboundNode(int k) {
        return outboundNodes.get(k);
    }

    @Override
    public INode allocNode(String ip, int p0) {
        INode n = new Node(ip, p0);
        if (seedIps.contains(ip)) {
            n.setFromBootList(true);
        }
        return n;
    }

    @Override
    public List<INode> getActiveNodesList() {
        return new ArrayList<>(activeNodes.values());
    }

    @Override
    public Map<Integer, INode> getActiveNodesMap() {
        return new HashMap<>(activeNodes);
    }

    @Override
    public int getAvgLatency() {
        return this.avgLatency;
    }

    @Override
    public void timeoutCheck(long currentTimeMillis) {
        timeoutInbound(currentTimeMillis);
        timeoutOutbound(currentTimeMillis);
        timeoutActive(currentTimeMillis);
    }

    @Override
    public boolean notAtOutboundList(int _nodeIdHash) {
        return !this.outboundNodes.containsKey(_nodeIdHash);
    }

    private void timeoutOutbound(long currentTimeMillis) {
        try {
            Iterator<Map.Entry<Integer, INode>> it = outboundNodes.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<Integer, INode> entry = it.next();
                if (currentTimeMillis - entry.getValue().getTimestamp() > TIMEOUT_OUTBOUND_NODES) {
                    p2pMgr.closeSocket(entry.getValue().getChannel(), "outbound-timeout ip=" + entry.getValue().getIpStr());
                    it.remove();
                }
            }
        } catch (IllegalStateException e) {
            p2pLOG.error("<timeoutOutbound IllegalStateException>", e);
        }
    }

    @Override
    public INode getRandom() {
        if (!activeNodes.isEmpty()) {
            Object[] keysArr = activeNodes.keySet().toArray();
            try {
                return this.getActiveNode((Integer) keysArr[random.nextInt(keysArr.length)]);
            } catch (IllegalArgumentException e) {
                p2pLOG.error("<getRandom-IllegalArgumentException>", e);
                return null;
            } catch (NullPointerException e) {
                p2pLOG.error("<getRandom-NullPointerException>", e);
                return null;
            } catch (ClreplacedCastException e) {
                p2pLOG.error("<getRandom-ClreplacedCastException>", e);
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * @param _ip String
     * @return boolean
     * @warning not thread safe helper function to check a specific ip a node replacedociated with is is
     *     allowed to add to active list
     */
    private boolean activeIpAllow(String _ip) {
        return true;
    // enable this in case
    // if(multiActiveAllowIps.contains(_ip))
    // return true;
    // else {
    // Set<String> ips = activeNodes.values().stream()
    // .map((n)-> n.getIpStr())
    // .collect(Collectors.toSet());
    // return !ips.contains(_ip);
    // }
    }

    public void movePeerToActive(int _hash, String _type) {
        Map<Integer, INode> nodes = (_type.contentEquals("inbound")) ? inboundNodes : outboundNodes;
        INode node = nodes.remove(_hash);
        if (node != null) {
            if (p2pLOG.isTraceEnabled()) {
                p2pLOG.trace("<movePeerToActive: {} {}>", _type, node.toString());
            }
            // noinspection SynchronizationOnLocalVariableOrMethodParameter
            synchronized (node) {
                if (activeNodes.size() >= maxActiveNodes) {
                    p2pMgr.closeSocket(node.getChannel(), _type + " -> active, active full");
                    return;
                }
                if (p2pMgr.isSelf(node)) {
                    p2pMgr.closeSocket(node.getChannel(), _type + " -> active, self-connected");
                    return;
                }
                node.setConnection(_type);
                node.setFromBootList(seedIps.contains(node.getIpStr()));
                INode previous = activeNodes.putIfAbsent(node.getIdHash(), node);
                if (previous != null) {
                    p2pMgr.closeSocket(node.getChannel(), _type + " -> active, node " + previous.getIdShort() + " exits");
                } else if (!activeIpAllow(node.getIpStr())) {
                    p2pMgr.closeSocket(node.getChannel(), _type + " -> active, ip " + node.getIpStr() + " exits");
                }
                if (p2pLOG.isDebugEnabled()) {
                    p2pLOG.debug("<{} -> active node-id={} ip={}>", _type, node.getIdShort(), node.getIpStr());
                }
            }
        } else {
            if (p2pLOG.isTraceEnabled()) {
                p2pLOG.trace("<movePeerToActive empty {} {}>", _type, _hash);
            }
        }
    }

    @Override
    public void updateChainInfo(long blockNumber, byte[] blockHash, BigInteger blockTD) {
        // We only need the block information
        myNode.updateStatus(blockNumber, blockHash, blockTD, (byte) 0, (short) 0, 0, 0);
    }

    private void timeoutInbound(long currentTimeMillis) {
        try {
            Iterator<Map.Entry<Integer, INode>> it = inboundNodes.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<Integer, INode> entry = it.next();
                if (currentTimeMillis - entry.getValue().getTimestamp() > TIMEOUT_INBOUND_NODES) {
                    p2pMgr.closeSocket(entry.getValue().getChannel(), "inbound-timeout ip=" + entry.getValue().getIpStr());
                    it.remove();
                }
            }
        } catch (IllegalStateException e) {
            p2pLOG.info("<timeoutInbound IllegalStateException>", e);
        }
    }

    private void timeoutActive(long now) {
        OptionalDouble average = activeNodes.values().stream().mapToLong(n -> now - n.getTimestamp()).average();
        this.avgLatency = (int) average.orElse(0);
        long timeout = ((long) average.orElse(4000)) * 5;
        timeout = Math.max(MIN_TIMEOUT_ACTIVE_NODES, Math.min(timeout, MAX_TIMEOUT_ACTIVE_NODES));
        if (p2pLOG.isDebugEnabled()) {
            p2pLOG.debug("<average-delay={}ms>", this.avgLatency);
        }
        try {
            Iterator<Map.Entry<Integer, INode>> it = activeNodes.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<Integer, INode> entry = it.next();
                INode node = entry.getValue();
                if (now - node.getTimestamp() > timeout) {
                    p2pMgr.closeSocket(node.getChannel(), "active-timeout ip=" + node.getIpStr());
                    it.remove();
                } else if (!node.getChannel().isConnected()) {
                    p2pMgr.closeSocket(node.getChannel(), "channel-already-closed node=" + node.getIdShort() + " ip=" + node.getIpStr());
                    it.remove();
                }
            }
        } catch (IllegalStateException e) {
            p2pLOG.info("<timeoutActive IllegalStateException>", e);
        }
    }

    public void dropActive(int nodeIdHash, String _reason) {
        INode node = null;
        try {
            node = activeNodes.remove(nodeIdHash);
        } catch (Exception e) {
            p2pLOG.info("<dropActive exception>", e);
        }
        if (node == null) {
            return;
        }
        p2pMgr.closeSocket(node.getChannel(), _reason);
    }

    @Override
    public void shutdown() {
        try {
            synchronized (outboundNodes) {
                outboundNodes.forEach((k, n) -> p2pMgr.closeSocket(n.getChannel(), "p2p-shutdown outbound node=" + n.getIdShort() + " ip=" + n.getIpStr()));
                outboundNodes.clear();
            }
            synchronized (inboundNodes) {
                inboundNodes.forEach((k, n) -> p2pMgr.closeSocket(n.getChannel(), "p2p-shutdown inbound ip=" + n.getIpStr()));
                inboundNodes.clear();
            }
            synchronized (activeNodes) {
                activeNodes.forEach((k, n) -> p2pMgr.closeSocket(n.getChannel(), "p2p-shutdown active node=" + n.getIdShort() + " ip=" + n.getIpStr()));
                activeNodes.clear();
            }
        } catch (Exception e) {
            p2pLOG.info("<p2p-shutdown exception>", e);
        }
    }

    @Override
    public void ban(int _nodeIdHash) {
        try {
            INode node = activeNodes.get(_nodeIdHash);
            if (node != null) {
                node.getPeerMetric().ban();
            }
        } catch (NullPointerException e) {
            p2pLOG.info("<p2p-ban null exception>", e);
        }
    }
}

16 Source : NodeMgr.java
with MIT License
from aionnetwork

private void timeoutActive(long now) {
    OptionalDouble average = activeNodes.values().stream().mapToLong(n -> now - n.getTimestamp()).average();
    this.avgLatency = (int) average.orElse(0);
    long timeout = ((long) average.orElse(4000)) * 5;
    timeout = Math.max(MIN_TIMEOUT_ACTIVE_NODES, Math.min(timeout, MAX_TIMEOUT_ACTIVE_NODES));
    if (p2pLOG.isDebugEnabled()) {
        p2pLOG.debug("<average-delay={}ms>", this.avgLatency);
    }
    try {
        Iterator<Map.Entry<Integer, INode>> it = activeNodes.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, INode> entry = it.next();
            INode node = entry.getValue();
            if (now - node.getTimestamp() > timeout) {
                p2pMgr.closeSocket(node.getChannel(), "active-timeout ip=" + node.getIpStr());
                it.remove();
            } else if (!node.getChannel().isConnected()) {
                p2pMgr.closeSocket(node.getChannel(), "channel-already-closed node=" + node.getIdShort() + " ip=" + node.getIpStr());
                it.remove();
            }
        }
    } catch (IllegalStateException e) {
        p2pLOG.info("<timeoutActive IllegalStateException>", e);
    }
}

16 Source : SyncHeaderRequestManagerTest.java
with MIT License
from aionnetwork

/**
 * Generates {@code count} mock peers with ids from {@code start} to {@code start + count - 1}
 * and best block number {@code id * 1_000L}.
 */
private Map<Integer, INode> generateMockPeers(int start, int count) {
    Map<Integer, INode> current = new HashMap<>();
    for (int i = start; i < count + start; i++) {
        INode mockPeer = mock(INode.clreplaced);
        when(mockPeer.getIdHash()).thenReturn(i);
        when(mockPeer.getIdShort()).thenReturn("peer" + i);
        when(mockPeer.getBestBlockNumber()).thenReturn(i * 1_000L);
        current.put(i, mockPeer);
    }
    return current;
}

16 Source : SyncHeaderRequestManager.java
with MIT License
from aionnetwork

/**
 * Updates the internally tracked states according to the given active peer list.
 *
 * <ol>
 *   <li>Ensures the inactive peers are dropped from all internal tracking and new peers are
 *       added according to the provided list of active connections.
 *   <li>Updates the best known block number for all active peers and the known network height.
 *   <li>Booked peers are checked for a change in their status based on the availability defined
 *       in {@link RequestState#tryMakeAvailable()} which takes into account the number of
 *       header requests allowed per second.
 * </ol>
 */
private void updateActiveNodes(Map<Integer, INode> current) {
    // find entries in the knownActiveNodes set that are not in the current map
    Set<Integer> dropped = knownActiveNodes.stream().filter(node -> !current.containsKey(node)).collect(Collectors.toSet());
    // remove dropped connections
    for (Integer id : dropped) {
        storedHeaders.remove(id);
        bookedPeerStates.remove(id);
        availablePeerStates.remove(id);
    }
    // add new peers and update best block for known peers
    for (INode node : current.values()) {
        Integer id = node.getIdHash();
        if (bookedPeerStates.containsKey(id)) {
            // update best
            bookedPeerStates.get(id).lastBestBlock = node.getBestBlockNumber();
        } else if (availablePeerStates.containsKey(id)) {
            // update best
            availablePeerStates.get(id).lastBestBlock = node.getBestBlockNumber();
        } else {
            // add peer
            availablePeerStates.put(id, new RequestState(id, node.getIdShort(), node.getBestBlockNumber()));
        }
        // update the known network height
        networkHeight = Math.max(networkHeight, node.getBestBlockNumber());
    }
    // update known active nodes
    knownActiveNodes.clear();
    knownActiveNodes.addAll(current.keySet());
    // reset booked states if now available
    if (!bookedPeerStates.isEmpty()) {
        // check if any of the booked states have become available
        Iterator<RequestState> states = bookedPeerStates.values().iterator();
        while (states.hasNext()) {
            RequestState currentState = states.next();
            if (currentState.tryMakeAvailable()) {
                availablePeerStates.put(currentState.id, currentState);
                states.remove();
            }
        }
    }
}

15 Source : NodeMgrTest.java
with MIT License
from aionnetwork

private void addNodetoInbound(INode node, UUID _uuid) {
    node.setChannel(channel);
    node.setId(_uuid.toString().getBytes(StandardCharsets.UTF_8));
    node.refreshTimestamp();
    nMgr.addInboundNode(node);
    replacedertNotNull(nMgr.getInboundNode(channel.hashCode()));
}

15 Source : NodeMgrTest.java
with MIT License
from aionnetwork

private Runnable generateTempNode() {
    return () -> {
        INode newNode = new Node(false, UUID.randomUUID().toString().getBytes(), randomIP(), r.nextInt(65535) + 1);
        SocketChannel ch = mock(SocketChannel.clreplaced);
        newNode.setChannel(ch);
        byte[] rHash = new byte[32];
        r.nextBytes(rHash);
        newNode.updateStatus(r.nextLong(), rHash, BigInteger.valueOf(r.nextLong()), (byte) r.nextInt(), (short) r.nextInt(), r.nextInt(), r.nextInt());
        nMgr.addTempNode(newNode);
    };
}

15 Source : NodeMgrTest.java
with MIT License
from aionnetwork

private void addNodetoOutbound(INode node, UUID _uuid) {
    node.setChannel(channel);
    node.setId(_uuid.toString().getBytes(StandardCharsets.UTF_8));
    node.refreshTimestamp();
    nMgr.addOutboundNode(node);
    replacedertNotNull(nMgr.getOutboundNode(node.getIdHash()));
}

15 Source : NodeMgrTest.java
with MIT License
from aionnetwork

@Test(timeout = 30_000)
public void testBan() {
    INode node = nMgr.allocNode(ip2, 1);
    node.setChannel(channel);
    node.setId(nodeId2.getBytes(StandardCharsets.UTF_8));
    nMgr.addInboundNode(node);
    replacedertEquals(0, nMgr.activeNodesSize());
    nMgr.movePeerToActive(channel.hashCode(), "inbound");
    replacedertEquals(1, nMgr.activeNodesSize());
    replacedertTrue(node.getPeerMetric().notBan());
    nMgr.ban(node.getIdHash());
    replacedertFalse(node.getPeerMetric().notBan());
}

See More Examples