src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
NewBlockFilter extends Filter { @Override public void newBlockReceived(Block b) { add(new NewBlockFilterEvent(b)); } @Override void newBlockReceived(Block b); } | @Test public void oneBlockAndEvent() { NewBlockFilter filter = new NewBlockFilter(); Block block = new BlockGenerator().getBlock(1); filter.newBlockReceived(block); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(1, result.length); Assert.assertEquals("0x" + block.getHash(), result[0]); }
@Test public void twoBlocksAndEvents() { NewBlockFilter filter = new NewBlockFilter(); Block block1 = new BlockGenerator().getBlock(1); Block block2 = new BlockGenerator().getBlock(2); filter.newBlockReceived(block1); filter.newBlockReceived(block2); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(2, result.length); Assert.assertEquals("0x" + block1.getHash(), result[0]); Assert.assertEquals("0x" + block2.getHash(), result[1]); } |
ConfigLoader { public Config getConfig() { Config cliConfig = getConfigFromCliArgs(); Config systemPropsConfig = ConfigFactory.systemProperties(); Config systemEnvConfig = ConfigFactory.systemEnvironment(); Config userCustomConfig = getUserCustomConfig(); Config installerConfig = getInstallerConfig(); Config userConfig = ConfigFactory.empty() .withFallback(cliConfig) .withFallback(systemPropsConfig) .withFallback(systemEnvConfig) .withFallback(userCustomConfig) .withFallback(installerConfig); Config networkBaseConfig = getNetworkDefaultConfig(userConfig); Config unifiedConfig = userConfig.withFallback(networkBaseConfig); Config expectedConfig = ConfigFactory.parseResourcesAnySyntax(EXPECTED_RESOURCE_PATH) .withFallback(systemPropsConfig) .withFallback(systemEnvConfig); boolean valid = isActualObjectValid("", expectedConfig.root(), unifiedConfig.root()); if (unifiedConfig.getBoolean(SystemProperties.PROPERTY_BC_VERIFY) && !valid) { throw new RskConfigurationException("Verification of node config settings has failed. See the previous error logs for details."); } return unifiedConfig; } ConfigLoader(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); Config getConfig(); static boolean isCollectionType(ConfigValueType valueType); } | @Test public void loadBaseMainnetConfigWithEmptyCliArgs() { Config config = loader.getConfig(); assertThat(config.getString(SystemProperties.PROPERTY_BC_CONFIG_NAME), is("main")); assertThat(config.getBoolean(SystemProperties.PROPERTY_DB_RESET), is(false)); assertThat(config.getString(SystemProperties.PROPERTY_RPC_CORS), is("localhost")); assertThat(config.getBoolean(SystemProperties.PROPERTY_RPC_HTTP_ENABLED), is(true)); }
@Test public void regtestCliFlagOverridesNetworkBaseConfig() { when(cliArgs.getFlags()) .thenReturn(Collections.singleton(NodeCliFlags.NETWORK_REGTEST)); Config config = loader.getConfig(); assertThat(config.getString(SystemProperties.PROPERTY_BC_CONFIG_NAME), is("regtest")); assertThat(config.getBoolean(SystemProperties.PROPERTY_RPC_HTTP_ENABLED), is(true)); }
@Test public void testnetCliFlagOverridesNetworkBaseConfig() { when(cliArgs.getFlags()) .thenReturn(Collections.singleton(NodeCliFlags.NETWORK_TESTNET)); Config config = loader.getConfig(); assertThat(config.getString(SystemProperties.PROPERTY_BC_CONFIG_NAME), is("testnet")); }
@Test public void dbResetCliFlagEnablesReset() { when(cliArgs.getFlags()) .thenReturn(Collections.singleton(NodeCliFlags.DB_RESET)); Config config = loader.getConfig(); assertThat(config.getString(SystemProperties.PROPERTY_BC_CONFIG_NAME), is("main")); assertThat(config.getBoolean(SystemProperties.PROPERTY_DB_RESET), is(true)); }
@Test public void rpcCorsCliOptionEnablesCorsAndChangesHostname() { when(cliArgs.getOptions()) .thenReturn(Collections.singletonMap(NodeCliOptions.RPC_CORS, "myhostname")); Config config = loader.getConfig(); assertThat(config.getString(SystemProperties.PROPERTY_RPC_CORS), is("myhostname")); assertThat(config.getBoolean(SystemProperties.PROPERTY_RPC_HTTP_ENABLED), is(true)); }
@Test public void verifyConfigSettingIsOffByDefault() { Config config = loader.getConfig(); assertThat(config.getBoolean(SystemProperties.PROPERTY_BC_VERIFY), is(false)); }
@Test public void setVerifyConfigSetting() { when(cliArgs.getFlags()).thenReturn(Collections.singleton(NodeCliFlags.VERIFY_CONFIG)); Config config = loader.getConfig(); assertThat(config.getBoolean(SystemProperties.PROPERTY_BC_VERIFY), is(true)); }
@Test(expected = RskConfigurationException.class) public void detectUnexpectedKeyProblem() { Config defaultConfig = EMPTY_CONFIG .withValue("blockchain.config.verify", TRUE_VALUE) .withValue("unexpectedKey", NULL_VALUE); Config expectedConfig = EMPTY_CONFIG .withValue("blockchain.config.verify", TRUE_VALUE) .withValue("expectedKey", NULL_VALUE); mockConfigFactory(defaultConfig, expectedConfig); loader.getConfig(); }
@Test(expected = RskConfigurationException.class) public void detectExpectedScalarValueProblemInObject() { Config defaultConfig = EMPTY_CONFIG .withValue("blockchain.config.verify", TRUE_VALUE) .withValue("expectedKey.nestedKey", EMPTY_OBJECT_VALUE); Config expectedConfig = EMPTY_CONFIG .withValue("blockchain.config.verify", TRUE_VALUE) .withValue("expectedKey", EMPTY_OBJECT_VALUE); mockConfigFactory(defaultConfig, expectedConfig); loader.getConfig(); }
@Parameterized.Parameters @Test(expected = RskConfigurationException.class) public void detectExpectedScalarValueProblemInList() { Config defaultConfig = EMPTY_CONFIG .withValue("blockchain.config.verify", TRUE_VALUE) .withValue("expectedKey", ConfigValueFactory.fromIterable(Collections.singletonList(EMPTY_LIST_VALUE))); Config expectedConfig = EMPTY_CONFIG .withValue("blockchain.config.verify", TRUE_VALUE) .withValue("expectedKey", EMPTY_LIST_VALUE); mockConfigFactory(defaultConfig, expectedConfig); loader.getConfig(); }
@Test public void detectTypeMismatchProblem() { ConfigValue[] values = { NULL_VALUE, TRUE_VALUE, ZERO_VALUE, STRING_VALUE, EMPTY_OBJECT_VALUE, EMPTY_LIST_VALUE }; Predicate<ConfigValueType> isCollectionType = ConfigLoader::isCollectionType; BiConsumer<ConfigValue, ConfigValue> checkTypeMismatchProblem = (ConfigValue expectedValue, ConfigValue actualValue) -> { Config defaultConfig = EMPTY_CONFIG .withValue("blockchain.config.verify", TRUE_VALUE) .withValue("expectedKey", actualValue); Config expectedConfig = EMPTY_CONFIG .withValue("blockchain.config.verify", TRUE_VALUE) .withValue("expectedKey", expectedValue); mockConfigFactory(defaultConfig, expectedConfig); try { loader.getConfig(); fail("Type mismatch problem is not detected"); } catch (RskConfigurationException e) { } }; Stream.of(values) .flatMap(expectedValue -> Stream.of(values) .filter(actualValue -> expectedValue.valueType() != actualValue.valueType() && (isCollectionType.test(expectedValue.valueType()) || isCollectionType.test(actualValue.valueType()))) .map(actualValue -> Pair.of(expectedValue, actualValue))) .forEach(pair -> checkTypeMismatchProblem.accept(pair.getLeft(), pair.getRight())); } |
NetBlockStore { public synchronized Block getBlockByHash(byte[] hash) { return this.blocks.get(new Keccak256(hash)); } synchronized void saveBlock(Block block); synchronized void removeBlock(Block block); synchronized Block getBlockByHash(byte[] hash); synchronized List<Block> getBlocksByNumber(long number); synchronized List<Block> getBlocksByParentHash(Keccak256 hash); List<Block> getChildrenOf(Set<Block> blocks); synchronized boolean hasBlock(Block block); synchronized boolean hasBlock(byte[] hash); synchronized int size(); synchronized long minimalHeight(); synchronized long maximumHeight(); synchronized void releaseRange(long from, long to); synchronized boolean hasHeader(Keccak256 hash); synchronized void saveHeader(@Nonnull final BlockHeader header); synchronized void removeHeader(@Nonnull final BlockHeader header); } | @Test public void getUnknownBlockAsNull() { NetBlockStore store = new NetBlockStore(); Assert.assertNull(store.getBlockByHash(TestUtils.randomBytes(32))); } |
NetBlockStore { public synchronized void releaseRange(long from, long to) { for (long k = from; k <= to; k++) { for (Block b : this.getBlocksByNumber(k)) { this.removeBlock(b); } } } synchronized void saveBlock(Block block); synchronized void removeBlock(Block block); synchronized Block getBlockByHash(byte[] hash); synchronized List<Block> getBlocksByNumber(long number); synchronized List<Block> getBlocksByParentHash(Keccak256 hash); List<Block> getChildrenOf(Set<Block> blocks); synchronized boolean hasBlock(Block block); synchronized boolean hasBlock(byte[] hash); synchronized int size(); synchronized long minimalHeight(); synchronized long maximumHeight(); synchronized void releaseRange(long from, long to); synchronized boolean hasHeader(Keccak256 hash); synchronized void saveHeader(@Nonnull final BlockHeader header); synchronized void removeHeader(@Nonnull final BlockHeader header); } | @Test public void releaseRange() { NetBlockStore store = new NetBlockStore(); final BlockGenerator generator = new BlockGenerator(); Block genesis = generator.getGenesisBlock(); List<Block> blocks1 = generator.getBlockChain(genesis, 1000); List<Block> blocks2 = generator.getBlockChain(genesis, 1000); for (Block b : blocks1) store.saveBlock(b); for (Block b : blocks2) store.saveBlock(b); Assert.assertEquals(2000, store.size()); store.releaseRange(1, 1000); Assert.assertEquals(0, store.size()); } |
NetBlockStore { public synchronized void saveHeader(@Nonnull final BlockHeader header) { this.headers.put(header.getHash(), header); } synchronized void saveBlock(Block block); synchronized void removeBlock(Block block); synchronized Block getBlockByHash(byte[] hash); synchronized List<Block> getBlocksByNumber(long number); synchronized List<Block> getBlocksByParentHash(Keccak256 hash); List<Block> getChildrenOf(Set<Block> blocks); synchronized boolean hasBlock(Block block); synchronized boolean hasBlock(byte[] hash); synchronized int size(); synchronized long minimalHeight(); synchronized long maximumHeight(); synchronized void releaseRange(long from, long to); synchronized boolean hasHeader(Keccak256 hash); synchronized void saveHeader(@Nonnull final BlockHeader header); synchronized void removeHeader(@Nonnull final BlockHeader header); } | @Test public void saveHeader() { NetBlockStore store = new NetBlockStore(); BlockHeader blockHeader = blockFactory.getBlockHeaderBuilder() .setParentHash(new byte[0]) .setCoinbase(TestUtils.randomAddress()) .setNumber(1) .setMinimumGasPrice(Coin.ZERO) .build(); store.saveHeader(blockHeader); Assert.assertTrue(store.hasHeader(blockHeader.getHash())); } |
NetBlockStore { public synchronized void removeHeader(@Nonnull final BlockHeader header) { if (!this.hasHeader(header.getHash())) { return; } this.headers.remove(header.getHash()); } synchronized void saveBlock(Block block); synchronized void removeBlock(Block block); synchronized Block getBlockByHash(byte[] hash); synchronized List<Block> getBlocksByNumber(long number); synchronized List<Block> getBlocksByParentHash(Keccak256 hash); List<Block> getChildrenOf(Set<Block> blocks); synchronized boolean hasBlock(Block block); synchronized boolean hasBlock(byte[] hash); synchronized int size(); synchronized long minimalHeight(); synchronized long maximumHeight(); synchronized void releaseRange(long from, long to); synchronized boolean hasHeader(Keccak256 hash); synchronized void saveHeader(@Nonnull final BlockHeader header); synchronized void removeHeader(@Nonnull final BlockHeader header); } | @Test public void removeHeader() { NetBlockStore store = new NetBlockStore(); BlockHeader blockHeader = blockFactory.getBlockHeaderBuilder() .setParentHash(new byte[0]) .setCoinbase(TestUtils.randomAddress()) .setNumber(1) .setMinimumGasPrice(Coin.ZERO) .build(); store.saveHeader(blockHeader); store.removeHeader(blockHeader); Assert.assertFalse(store.hasHeader(blockHeader.getHash())); } |
PacketDecoder extends MessageToMessageDecoder<DatagramPacket> { @Override public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception { ByteBuf buf = packet.content(); byte[] encoded = new byte[buf.readableBytes()]; buf.readBytes(encoded); out.add(this.decodeMessage(ctx, encoded, packet.sender())); } @Override void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out); DiscoveryEvent decodeMessage(ChannelHandlerContext ctx, byte[] encoded, InetSocketAddress sender); } | @Test public void decode() throws Exception { ECKey key1 = ECKey.fromPrivate(Hex.decode(KEY_1)).decompress(); String check = UUID.randomUUID().toString(); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); PacketDecoder decoder = new PacketDecoder(); PingPeerMessage nodeMessage = PingPeerMessage.create("localhost", 44035, check, key1, NETWORK_ID); InetSocketAddress sender = new InetSocketAddress("localhost", 44035); this.assertDecodedMessage(decoder.decodeMessage(ctx, nodeMessage.getPacket(), sender), sender, DiscoveryMessageType.PING); PongPeerMessage pongPeerMessage = PongPeerMessage.create("localhost", 44036, check, key1, NETWORK_ID); sender = new InetSocketAddress("localhost", 44036); this.assertDecodedMessage(decoder.decodeMessage(ctx, pongPeerMessage.getPacket(), sender), sender, DiscoveryMessageType.PONG); FindNodePeerMessage findNodePeerMessage = FindNodePeerMessage.create(key1.getNodeId(), check, key1, NETWORK_ID); sender = new InetSocketAddress("localhost", 44037); this.assertDecodedMessage(decoder.decodeMessage(ctx, findNodePeerMessage.getPacket(), sender), sender, DiscoveryMessageType.FIND_NODE); NeighborsPeerMessage neighborsPeerMessage = NeighborsPeerMessage.create(new ArrayList<>(), check, key1, NETWORK_ID); sender = new InetSocketAddress("localhost", 44038); this.assertDecodedMessage(decoder.decodeMessage(ctx, neighborsPeerMessage.getPacket(), sender), sender, DiscoveryMessageType.NEIGHBORS); } |
NodeDistanceTable { public synchronized List<Node> getClosestNodes(NodeID nodeId) { return getAllNodes().stream() .sorted(new NodeDistanceComparator(nodeId, this.distanceCalculator)) .collect(Collectors.toList()); } NodeDistanceTable(int numberOfBuckets, int entriesPerBucket, Node localNode); synchronized OperationResult addNode(Node node); synchronized OperationResult removeNode(Node node); synchronized List<Node> getClosestNodes(NodeID nodeId); Set<Node> getAllNodes(); void updateEntry(Node node); } | @Test public void creation() { Node localNode = new Node(Hex.decode(NODE_ID_1), HOST, PORT_1); NodeDistanceTable table = new NodeDistanceTable(KademliaOptions.BINS, KademliaOptions.BUCKET_SIZE, localNode); Assert.assertTrue(table != null); Assert.assertEquals(0, table.getClosestNodes(EMPTY_NODE_ID).size()); } |
SolidityType { public abstract Object decode(byte[] encoded, int offset); SolidityType(String name); String getName(); @JsonValue String getCanonicalName(); @JsonCreator static SolidityType getType(String typeName); abstract byte[] encode(Object value); abstract Object decode(byte[] encoded, int offset); Object decode(byte[] encoded); int getFixedSize(); boolean isDynamicType(); @Override String toString(); } | @Test public void TestDynamicArrayTypeWithInvalidDataSize() { SolidityType.DynamicArrayType dat = new SolidityType.DynamicArrayType("string[]"); byte[] input = new byte[32]; input[31] = 0x10; try { dat.decode(input, 0); Assert.fail(); } catch (IllegalArgumentException e) { } input = new byte[98]; input[31] = 0x01; input[63] = 0x20; input[95] = 0x10; input[96] = 0x68; input[97] = 0x69; try { dat.decode(input, 0); Assert.fail(); } catch (IllegalArgumentException e) { } input = new byte[164]; input[31] = 0x02; input[63] = 0x20; input[95] = 0x02; input[96] = 0x68; input[97] = 0x69; input[129] = 0x20; input[161] = 0x10; input[162] = 0x68; input[163] = 0x69; try { dat.decode(input, 0); Assert.fail(); } catch (IllegalArgumentException e) { } }
@Test public void TestStaticArrayTypeWithInvalidSize() { try { SolidityType.StaticArrayType dat = new SolidityType.StaticArrayType("string[2]"); byte[] input = new byte[34]; input[31] = 0x02; input[32] = 0x68; input[33] = 0x69; dat.decode(input, 0); Assert.fail("should have failed"); } catch (IllegalArgumentException e) { } try { SolidityType.StaticArrayType dat = new SolidityType.StaticArrayType("string[1]"); byte[] input = new byte[34]; input[31] = 0x03; input[32] = 0x68; input[33] = 0x69; dat.decode(input, 0); Assert.fail("should have failed"); } catch (IllegalArgumentException e) { } } |
NodeDistanceTable { public synchronized OperationResult addNode(Node node) { return getNodeBucket(node).addNode(node); } NodeDistanceTable(int numberOfBuckets, int entriesPerBucket, Node localNode); synchronized OperationResult addNode(Node node); synchronized OperationResult removeNode(Node node); synchronized List<Node> getClosestNodes(NodeID nodeId); Set<Node> getAllNodes(); void updateEntry(Node node); } | @Test public void addNode() { Node localNode = new Node(Hex.decode(NODE_ID_1), HOST, PORT_1); Node node2 = new Node(Hex.decode(NODE_ID_2), HOST, PORT_2); Node node3 = new Node(Hex.decode(NODE_ID_3), HOST, PORT_3); NodeDistanceTable table = new NodeDistanceTable(KademliaOptions.BINS, KademliaOptions.BUCKET_SIZE, localNode); OperationResult result = table.addNode(node3); Assert.assertTrue(result.isSuccess()); result = table.addNode(node2); Assert.assertTrue(result.isSuccess()); Assert.assertEquals(2, table.getClosestNodes(EMPTY_NODE_ID).size()); result = table.addNode(node2); Assert.assertTrue(result.isSuccess()); Assert.assertEquals(2, table.getClosestNodes(EMPTY_NODE_ID).size()); NodeDistanceTable smallerTable = new NodeDistanceTable(KademliaOptions.BINS, 1, localNode); result = smallerTable.addNode(node3); Assert.assertTrue(result.isSuccess()); Node sameDistanceNode = new Node(Hex.decode("00"), HOST, PORT_3); result = smallerTable.addNode(sameDistanceNode); Assert.assertFalse(result.isSuccess()); Assert.assertEquals(NODE_ID_3, result.getAffectedEntry().getNode().getHexId()); } |
DistanceCalculator { public int calculateDistance(NodeID node1, NodeID node2) { byte[] nodeId1 = HashUtil.keccak256(HashUtil.keccak256(node1.getID())); byte[] nodeId2 = HashUtil.keccak256(HashUtil.keccak256(node2.getID())); byte[] result = new byte[nodeId1.length]; for (int i = 0; i < result.length; i++) { result[i] = (byte) (((int) nodeId1[i]) ^ ((int) nodeId2[i])); } return msbPosition(result); } DistanceCalculator(int maxDistance); int calculateDistance(NodeID node1, NodeID node2); } | @Test public void distance() { DistanceCalculator calculator = new DistanceCalculator(256); Node node1 = new Node(Hex.decode(NODE_ID_1), "190.0.0.128", 8080); Node node2 = new Node(Hex.decode(NODE_ID_2), "192.0.0.127", 8080); Assert.assertEquals(0, calculator.calculateDistance(node1.getId(), node1.getId())); Assert.assertEquals(calculator.calculateDistance(node1.getId(), node2.getId()), calculator.calculateDistance(node2.getId(), node1.getId())); } |
UDPChannel extends SimpleChannelInboundHandler<DiscoveryEvent> { @Override public void channelRead0(ChannelHandlerContext ctx, DiscoveryEvent event) throws Exception { this.peerExplorer.handleMessage(event); } UDPChannel(Channel ch, PeerExplorer peerExplorer); @Override void channelRead0(ChannelHandlerContext ctx, DiscoveryEvent event); void write(DiscoveryEvent discoveryEvent); @Override void channelReadComplete(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); @Override void channelActive(ChannelHandlerContext ctx); } | @Test public void channelRead0() throws Exception { Channel channel = Mockito.mock(Channel.class); PeerExplorer peerExplorer = Mockito.mock(PeerExplorer.class); UDPChannel udpChannel = new UDPChannel(channel, peerExplorer); DiscoveryEvent event = Mockito.mock(DiscoveryEvent.class); udpChannel.channelRead0(Mockito.mock(ChannelHandlerContext.class), event); Mockito.verify(peerExplorer, Mockito.times(1)).handleMessage(event); } |
UDPChannel extends SimpleChannelInboundHandler<DiscoveryEvent> { public void write(DiscoveryEvent discoveryEvent) { InetSocketAddress address = discoveryEvent.getAddress(); sendPacket(discoveryEvent.getMessage().getPacket(), address); } UDPChannel(Channel ch, PeerExplorer peerExplorer); @Override void channelRead0(ChannelHandlerContext ctx, DiscoveryEvent event); void write(DiscoveryEvent discoveryEvent); @Override void channelReadComplete(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); @Override void channelActive(ChannelHandlerContext ctx); } | @Test public void write() { String check = UUID.randomUUID().toString(); ECKey key = new ECKey(); PingPeerMessage nodeMessage = PingPeerMessage.create("localhost", 80, check, key, NETWORK_ID); Channel channel = Mockito.mock(Channel.class); PeerExplorer peerExplorer = Mockito.mock(PeerExplorer.class); UDPChannel udpChannel = new UDPChannel(channel, peerExplorer); udpChannel.write(new DiscoveryEvent(nodeMessage, new InetSocketAddress("localhost", 8080))); Mockito.verify(channel, Mockito.times(1)).write(Mockito.any()); Mockito.verify(channel, Mockito.times(1)).flush(); } |
UDPChannel extends SimpleChannelInboundHandler<DiscoveryEvent> { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { peerExplorer.start(); } UDPChannel(Channel ch, PeerExplorer peerExplorer); @Override void channelRead0(ChannelHandlerContext ctx, DiscoveryEvent event); void write(DiscoveryEvent discoveryEvent); @Override void channelReadComplete(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); @Override void channelActive(ChannelHandlerContext ctx); } | @Test public void channelActive() throws Exception { Channel channel = Mockito.mock(Channel.class); PeerExplorer peerExplorer = Mockito.mock(PeerExplorer.class); UDPChannel udpChannel = new UDPChannel(channel, peerExplorer); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); udpChannel.channelActive(ctx); Mockito.verify(peerExplorer, Mockito.times(1)).start(); } |
NodeChallengeManager { public NodeChallenge startChallenge(Node challengedNode, Node challenger, PeerExplorer explorer) { PingPeerMessage pingMessage = explorer.sendPing(challengedNode.getAddress(), 1, challengedNode); String messageId = pingMessage.getMessageId(); NodeChallenge challenge = new NodeChallenge(challengedNode, challenger, messageId); activeChallenges.put(messageId, challenge); return challenge; } NodeChallenge startChallenge(Node challengedNode, Node challenger, PeerExplorer explorer); NodeChallenge removeChallenge(String challengeId); @VisibleForTesting int activeChallengesCount(); } | @Test public void startChallenge() { ECKey key1 = ECKey.fromPrivate(Hex.decode(KEY_1)).decompress(); ECKey key2 = ECKey.fromPrivate(Hex.decode(KEY_2)).decompress(); ECKey key3 = ECKey.fromPrivate(Hex.decode(KEY_3)).decompress(); Node node1 = new Node(key1.getNodeId(), HOST_1, PORT_1); Node node2 = new Node(key2.getNodeId(), HOST_2, PORT_2); Node node3 = new Node(key3.getNodeId(), HOST_3, PORT_3); NodeDistanceTable distanceTable = new NodeDistanceTable(KademliaOptions.BINS, KademliaOptions.BUCKET_SIZE, node1); PeerExplorer peerExplorer = new PeerExplorer(new ArrayList<>(), node1, distanceTable, new ECKey(), TIMEOUT, UPDATE, CLEAN, NETWORK_ID); peerExplorer.setUDPChannel(Mockito.mock(UDPChannel.class)); NodeChallengeManager manager = new NodeChallengeManager(); NodeChallenge challenge = manager.startChallenge(node2, node3, peerExplorer); Assert.assertNotNull(challenge); Assert.assertEquals(challenge.getChallengedNode(), node2); Assert.assertEquals(challenge.getChallenger(), node3); NodeChallenge anotherChallenge = manager.removeChallenge(UUID.randomUUID().toString()); Assert.assertNull(anotherChallenge); anotherChallenge = manager.removeChallenge(challenge.getChallengeId()); Assert.assertEquals(challenge, anotherChallenge); } |
UDPServer implements InternalService { @Override public void start() { if (port == 0) { logger.error("Discovery can't be started while listen port == 0"); } else { new Thread("UDPServer") { @Override public void run() { try { UDPServer.this.startUDPServer(); } catch (Exception e) { logger.error("Discovery can't be started. ", e); throw new PeerDiscoveryException("Discovery can't be started. ", e); } } }.start(); } } UDPServer(String address, int port, PeerExplorer peerExplorer); @Override void start(); void startUDPServer(); @Override void stop(); } | @Test public void port0DoesntCreateANewChannel() throws InterruptedException { UDPServer udpServer = new UDPServer(HOST, 0, null); Channel channel = Whitebox.getInternalState(udpServer, "channel"); udpServer.start(); TimeUnit.SECONDS.sleep(2); Assert.assertNull(channel); } |
PeerExplorer { public void handlePingMessage(InetSocketAddress address, PingPeerMessage message) { this.sendPong(address, message); Node connectedNode = this.establishedConnections.get(message.getNodeId()); if (connectedNode == null) { this.sendPing(address, 1); } else { updateEntry(connectedNode); } } PeerExplorer(List<String> initialBootNodes, Node localNode, NodeDistanceTable distanceTable, ECKey key, long reqTimeOut, long updatePeriod, long cleanPeriod, Integer networkId); void start(); Set<String> startConversationWithNewNodes(); void setUDPChannel(UDPChannel udpChannel); void handleMessage(DiscoveryEvent event); void handlePingMessage(InetSocketAddress address, PingPeerMessage message); void handlePong(InetSocketAddress pongAddress, PongPeerMessage message); void handleFindNode(FindNodePeerMessage message); void handleNeighborsMessage(InetSocketAddress neighborsResponseAddress, NeighborsPeerMessage message); List<Node> getNodes(); PingPeerMessage sendPing(InetSocketAddress nodeAddress, int attempt); PingPeerMessage sendPing(InetSocketAddress nodeAddress, int attempt, Node node); PongPeerMessage sendPong(InetSocketAddress nodeAddress, PingPeerMessage message); FindNodePeerMessage sendFindNode(Node node); NeighborsPeerMessage sendNeighbors(InetSocketAddress nodeAddress, List<Node> nodes, String id); void purgeRequests(); void clean(); void update(); @VisibleForTesting NodeChallengeManager getChallengeManager(); } | @Test public void handlePingMessage() throws Exception { List<String> nodes = new ArrayList<>(); ECKey key2 = ECKey.fromPrivate(Hex.decode(KEY_2)).decompress(); Node node = new Node(key2.getNodeId(), HOST_2, PORT_2); NodeDistanceTable distanceTable = new NodeDistanceTable(KademliaOptions.BINS, KademliaOptions.BUCKET_SIZE, node); PeerExplorer peerExplorer = new PeerExplorer(nodes, node, distanceTable, key2, TIMEOUT, UPDATE, CLEAN, NETWORK_ID1); Channel internalChannel = Mockito.mock(Channel.class); UDPTestChannel channel = new UDPTestChannel(internalChannel, peerExplorer); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); peerExplorer.setUDPChannel(channel); Assert.assertTrue(peerExplorer.getNodes().isEmpty()); ECKey key1 = ECKey.fromPrivate(Hex.decode(KEY_1)).decompress(); String check = UUID.randomUUID().toString(); PingPeerMessage nodeMessage = PingPeerMessage.create(HOST_1, PORT_1, check, key1, this.NETWORK_ID1); DiscoveryEvent incomingPingEvent = new DiscoveryEvent(nodeMessage, new InetSocketAddress(HOST_2, PORT_3)); channel.channelRead0(ctx, incomingPingEvent); List<DiscoveryEvent> sentEvents = channel.getEventsWritten(); Assert.assertEquals(2, sentEvents.size()); DiscoveryEvent pongEvent = sentEvents.get(0); PongPeerMessage toSenderPong = (PongPeerMessage) pongEvent.getMessage(); Assert.assertEquals(DiscoveryMessageType.PONG, toSenderPong.getMessageType()); Assert.assertEquals(new InetSocketAddress(HOST_2, PORT_3), pongEvent.getAddress()); DiscoveryEvent pingEvent = sentEvents.get(1); PingPeerMessage toSenderPing = (PingPeerMessage) pingEvent.getMessage(); Assert.assertEquals(DiscoveryMessageType.PING, toSenderPing.getMessageType()); Assert.assertEquals(new InetSocketAddress(HOST_2, PORT_3), pingEvent.getAddress()); PongPeerMessage pongResponseFromSender = PongPeerMessage.create(HOST_1, PORT_1, toSenderPing.getMessageId(), key1, NETWORK_ID1); DiscoveryEvent incomingPongEvent = new DiscoveryEvent(pongResponseFromSender, new InetSocketAddress(HOST_2, PORT_3)); channel.channelRead0(ctx, incomingPongEvent); channel.clearEvents(); channel.channelRead0(ctx, incomingPingEvent); sentEvents = channel.getEventsWritten(); Assert.assertEquals(1, sentEvents.size()); pongEvent = sentEvents.get(0); toSenderPong = (PongPeerMessage) pongEvent.getMessage(); Assert.assertEquals(DiscoveryMessageType.PONG, toSenderPong.getMessageType()); Assert.assertEquals(new InetSocketAddress(HOST_2, PORT_3), pongEvent.getAddress()); Assert.assertEquals(NODE_ID_2, ByteUtil.toHexString(toSenderPong.getKey().getNodeId())); } |
PeerDiscoveryRequest { public boolean validateMessageResponse(InetSocketAddress responseAddress, PeerDiscoveryMessage message) { return this.expectedResponse == message.getMessageType() && !this.hasExpired() && getAddress().equals(responseAddress); } PeerDiscoveryRequest(String messageId, PeerDiscoveryMessage message, InetSocketAddress address, DiscoveryMessageType expectedResponse, Long expirationPeriod, int attemptNumber, Node relatedNode); String getMessageId(); PeerDiscoveryMessage getMessage(); InetSocketAddress getAddress(); int getAttemptNumber(); Node getRelatedNode(); boolean validateMessageResponse(InetSocketAddress responseAddress, PeerDiscoveryMessage message); boolean hasExpired(); } | @Test public void create() { ECKey key = new ECKey(); String check = UUID.randomUUID().toString(); PingPeerMessage pingPeerMessage = PingPeerMessage.create("localhost", 80, check, key, NETWORK_ID); PongPeerMessage pongPeerMessage = PongPeerMessage.create("localhost", 80, check, key, NETWORK_ID); InetSocketAddress address = new InetSocketAddress("localhost", 8080); PeerDiscoveryRequest request = PeerDiscoveryRequestBuilder.builder().messageId(check) .message(pingPeerMessage).address(address).expectedResponse(DiscoveryMessageType.PONG) .expirationPeriod(1000).attemptNumber(1).build(); Assert.assertNotNull(request); Assert.assertTrue(request.validateMessageResponse(address, pongPeerMessage)); Assert.assertFalse(request.validateMessageResponse(address, pingPeerMessage)); } |
StatusMessage extends Message { @Override public void accept(MessageVisitor v) { v.apply(this); } StatusMessage(Status status); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); Status getStatus(); @Override void accept(MessageVisitor v); } | @Test public void accept() { StatusMessage message = new StatusMessage(mock(Status.class)); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
BlockResponseMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockResponseMessage(long id, Block block); long getId(); Block getBlock(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessageWithoutId(); @Override void accept(MessageVisitor v); } | @Test public void accept() { Block block = new BlockGenerator().getBlock(1); BlockResponseMessage message = new BlockResponseMessage(100, block); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
BlockRequestMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockRequestMessage(long id, byte[] hash); long getId(); byte[] getBlockHash(); @Override MessageType getMessageType(); @Override MessageType getResponseMessageType(); @Override byte[] getEncodedMessageWithoutId(); @Override void accept(MessageVisitor v); } | @Test public void accept() { byte[] hash = new BlockGenerator().getGenesisBlock().getHash().getBytes(); BlockRequestMessage message = new BlockRequestMessage(100, hash); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
BodyRequestMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BodyRequestMessage(long id, byte[] hash); long getId(); byte[] getBlockHash(); @Override MessageType getMessageType(); @Override MessageType getResponseMessageType(); @Override byte[] getEncodedMessageWithoutId(); @Override void accept(MessageVisitor v); } | @Test public void accept() { byte[] hash = new byte[]{0x0F}; BodyRequestMessage message = new BodyRequestMessage(100, hash); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
BlockHashRequestMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockHashRequestMessage(long id, long height); @Override MessageType getMessageType(); @Override MessageType getResponseMessageType(); @Override byte[] getEncodedMessageWithoutId(); long getId(); long getHeight(); @Override void accept(MessageVisitor v); } | @Test public void accept() { long someId = 42; long someHeight = 99; BlockHashRequestMessage message = new BlockHashRequestMessage(someId, someHeight); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
BlockHeadersResponseMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockHeadersResponseMessage(long id, List<BlockHeader> headers); @Override long getId(); List<BlockHeader> getBlockHeaders(); @Override MessageType getMessageType(); @Override void accept(MessageVisitor v); } | @Test public void accept() { BlockHeader blockHeader = mock(BlockHeader.class); List<BlockHeader> headers = new LinkedList<>(); headers.add(blockHeader); BlockHeadersResponseMessage message = new BlockHeadersResponseMessage(1, headers); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
BlockHeadersRequestMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockHeadersRequestMessage(long id, byte[] hash, int count); long getId(); byte[] getHash(); int getCount(); @Override byte[] getEncodedMessageWithoutId(); @Override MessageType getMessageType(); @Override MessageType getResponseMessageType(); @Override void accept(MessageVisitor v); } | @Test public void accept() { byte[] hash = HashUtil.randomHash(); BlockHeadersRequestMessage message = new BlockHeadersRequestMessage(1, hash, 100); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
MessageVisitor { public void apply(BlockMessage message) { final Block block = message.getBlock(); logger.trace("Process block {} {}", block.getNumber(), block.getPrintableHash()); if (block.isGenesis()) { logger.trace("Skip block processing {} {}", block.getNumber(), block.getPrintableHash()); return; } long blockNumber = block.getNumber(); if (this.blockProcessor.isAdvancedBlock(blockNumber)) { logger.trace("Too advanced block {} {}", blockNumber, block.getPrintableHash()); return; } if (blockProcessor.canBeIgnoredForUnclesRewards(block.getNumber())){ logger.trace("Block ignored: too far from best block {} {}", blockNumber, block.getPrintableHash()); return; } if (blockProcessor.hasBlockInSomeBlockchain(block.getHash().getBytes())){ logger.trace("Block ignored: it's included in blockchain {} {}", blockNumber, block.getPrintableHash()); return; } BlockProcessResult result = this.blockProcessor.processBlock(sender, block); if (result.isInvalidBlock()) { logger.trace("Invalid block {} {}", blockNumber, block.getPrintableHash()); recordEvent(sender, EventType.INVALID_BLOCK); return; } tryRelayBlock(block, result); if (result.isBest()) { sender.imported(true); } else { sender.imported(false); } recordEvent(sender, EventType.VALID_BLOCK); } MessageVisitor(RskSystemProperties config,
BlockProcessor blockProcessor,
SyncProcessor syncProcessor,
TransactionGateway transactionGateway,
PeerScoringManager peerScoringManager,
ChannelManager channelManager,
Peer sender); void apply(BlockMessage message); void apply(StatusMessage message); void apply(GetBlockMessage message); void apply(BlockRequestMessage message); void apply(BlockResponseMessage message); void apply(SkeletonRequestMessage message); void apply(BlockHeadersRequestMessage message); void apply(BlockHashRequestMessage message); void apply(BlockHashResponseMessage message); void apply(NewBlockHashMessage message); void apply(SkeletonResponseMessage message); void apply(BlockHeadersResponseMessage message); void apply(BodyRequestMessage message); void apply(BodyResponseMessage message); void apply(NewBlockHashesMessage message); void apply(TransactionsMessage message); } | @Test public void blockMessage_genesisBlock() { BlockMessage message = mock(BlockMessage.class); Block block = mock(Block.class); when(message.getBlock()).thenReturn(block); when(block.isGenesis()).thenReturn(true); target.apply(message); verify(blockProcessor, never()).processBlock(any(), any()); }
@Test public void blockMessage_advancedBlockNumber() { BlockMessage message = mock(BlockMessage.class); Block block = mock(Block.class); when(message.getBlock()).thenReturn(block); when(block.getNumber()).thenReturn(24L); when(blockProcessor.isAdvancedBlock(anyLong())).thenReturn(true); target.apply(message); verify(blockProcessor, never()).processBlock(any(), any()); }
@Test public void blockMessage_ignoredForUnclesReward() { BlockMessage message = mock(BlockMessage.class); Block block = mock(Block.class); when(message.getBlock()).thenReturn(block); when(block.getNumber()).thenReturn(24L); when(blockProcessor.canBeIgnoredForUnclesRewards(anyLong())).thenReturn(true); target.apply(message); verify(blockProcessor, never()).processBlock(any(), any()); }
@Test public void blockMessage_hasBlockInSomeBlockchain() { BlockMessage message = mock(BlockMessage.class); Block block = mock(Block.class); Keccak256 blockHash = mock(Keccak256.class); byte[] hashBytes = new byte[]{0x0F}; when(message.getBlock()).thenReturn(block); when(block.getNumber()).thenReturn(24L); when(block.getHash()).thenReturn(blockHash); when(blockHash.getBytes()).thenReturn(hashBytes); when(blockProcessor.hasBlockInSomeBlockchain(eq(hashBytes))).thenReturn(true); target.apply(message); verify(blockProcessor, never()).processBlock(any(), any()); }
@Test public void statusMessage() { StatusMessage message = mock(StatusMessage.class); Status status = mock(Status.class); when(message.getStatus()).thenReturn(status); target.apply(message); verify(syncProcessor, times(1)).processStatus(eq(sender),eq(status)); }
@Test public void getBlockMessage() { GetBlockMessage message = mock(GetBlockMessage.class); byte[] blockHash = new byte[]{0x0F}; when(message.getBlockHash()).thenReturn(blockHash); target.apply(message); verify(blockProcessor, times(1)).processGetBlock(eq(sender), eq(blockHash)); }
@Test public void blockRequestMessage() { BlockRequestMessage message = mock(BlockRequestMessage.class); byte[] blockHash = new byte[]{0x0F}; when(message.getBlockHash()).thenReturn(blockHash); when(message.getId()).thenReturn(24L); target.apply(message); verify(blockProcessor, times(1)) .processBlockRequest(eq(sender), eq(24L), eq(blockHash)); }
@Test public void blockResponseMessage() { BlockResponseMessage message = mock(BlockResponseMessage.class); target.apply(message); verify(syncProcessor, times(1)) .processBlockResponse(eq(sender), eq(message)); }
@Test public void skeletonRequestMessage() { SkeletonRequestMessage message = mock(SkeletonRequestMessage.class); when(message.getStartNumber()).thenReturn(24L); when(message.getId()).thenReturn(1L); target.apply(message); verify(blockProcessor, times(1)) .processSkeletonRequest(eq(sender), eq(1L), eq(24L)); }
@Test public void blockHeadersRequestMessage() { BlockHeadersRequestMessage message = mock(BlockHeadersRequestMessage.class); byte[] hash = new byte[]{0x0F}; when(message.getHash()).thenReturn(hash); when(message.getId()).thenReturn(1L); when(message.getCount()).thenReturn(10); target.apply(message); verify(blockProcessor, times(1)) .processBlockHeadersRequest(eq(sender), eq(1L), eq(hash), eq(10)); }
@Test public void blockHashRequestMessage() { BlockHashRequestMessage message = mock(BlockHashRequestMessage.class); when(message.getId()).thenReturn(1L); when(message.getHeight()).thenReturn(10L); target.apply(message); verify(blockProcessor, times(1)) .processBlockHashRequest(eq(sender), eq(1L), eq(10L)); }
@Test public void blockHashResponseMessage() { BlockHashResponseMessage message = mock(BlockHashResponseMessage.class); target.apply(message); verify(syncProcessor, times(1)) .processBlockHashResponse(eq(sender), eq(message)); }
@Test public void newBlockHashMessage() { NewBlockHashMessage message = mock(NewBlockHashMessage.class); target.apply(message); verify(syncProcessor, times(1)).processNewBlockHash(eq(sender), eq(message)); }
@Test public void skeletonResponseMessage() { SkeletonResponseMessage message = mock(SkeletonResponseMessage.class); target.apply(message); verify(syncProcessor, times(1)) .processSkeletonResponse(eq(sender), eq(message)); }
@Test public void blockHeadersResponseMessage() { BlockHeadersResponseMessage message = mock(BlockHeadersResponseMessage.class); target.apply(message); verify(syncProcessor, times(1)) .processBlockHeadersResponse(eq(sender), eq(message)); }
@Test public void bodyRequestMessage() { BodyRequestMessage message = mock(BodyRequestMessage.class); byte[] blockHash = new byte[]{0x0F}; when(message.getId()).thenReturn(1L); when(message.getBlockHash()).thenReturn(blockHash); target.apply(message); verify(blockProcessor, times(1)) .processBodyRequest(eq(sender), eq(1L), eq(blockHash)); }
@Test public void bodyResponseMessage() { BodyResponseMessage message = mock(BodyResponseMessage.class); target.apply(message); verify(syncProcessor, times(1)) .processBodyResponse(eq(sender), eq(message)); }
@Test public void newBlockHashesMessage() { NewBlockHashesMessage message = mock(NewBlockHashesMessage.class); target.apply(message); verify(blockProcessor, times(1)) .processNewBlockHashesMessage(eq(sender), eq(message)); }
@Test public void newBlockHashesMessage_betterBlockToSync() { NewBlockHashesMessage message = mock(NewBlockHashesMessage.class); when(blockProcessor.hasBetterBlockToSync()).thenReturn(true); target.apply(message); verify(blockProcessor, never()) .processNewBlockHashesMessage(eq(sender), eq(message)); }
@Test public void transactionsMessage_betterBlockToSync() { TransactionsMessage message = mock(TransactionsMessage.class); when(blockProcessor.hasBetterBlockToSync()).thenReturn(true); target.apply(message); verify(transactionGateway, never()).receiveTransactionsFrom(any(), any()); } |
ECIESCoder { public static byte[] decrypt(BigInteger privKey, byte[] cipher) throws IOException, InvalidCipherTextException { return decrypt(privKey, cipher, null); } static byte[] decrypt(BigInteger privKey, byte[] cipher); static byte[] decrypt(BigInteger privKey, byte[] cipher, byte[] macData); static byte[] decrypt(ECPoint ephem, BigInteger prv, byte[] iv, byte[] cipher, byte[] macData); static byte[] decryptSimple(BigInteger privKey, byte[] cipher); static byte[] encrypt(ECPoint toPub, byte[] plaintext); static byte[] encrypt(ECPoint toPub, byte[] plaintext, byte[] macData); static int getOverhead(); static final int KEY_SIZE; } | @Test public void test1(){ BigInteger privKey = new BigInteger("5e173f6ac3c669587538e7727cf19b782a4f2fda07c1eaa662c593e5e85e3051", 16); byte[] cipher = Hex.decode("049934a7b2d7f9af8fd9db941d9da281ac9381b5740e1f64f7092f3588d4f87f5ce55191a6653e5e80c1c5dd538169aa123e70dc6ffc5af1827e546c0e958e42dad355bcc1fcb9cdf2cf47ff524d2ad98cbf275e661bf4cf00960e74b5956b799771334f426df007350b46049adb21a6e78ab1408d5e6ccde6fb5e69f0f4c92bb9c725c02f99fa72b9cdc8dd53cff089e0e73317f61cc5abf6152513cb7d833f09d2851603919bf0fbe44d79a09245c6e8338eb502083dc84b846f2fee1cc310d2cc8b1b9334728f97220bb799376233e113"); byte[] payload = new byte[0]; try { payload = ECIESCoder.decrypt(privKey, cipher); } catch (Throwable e) {e.printStackTrace();} Assert.assertEquals("802b052f8b066640bba94a4fc39d63815c377fced6fcb84d27f791c9921ddf3e9bf0108e298f490812847109cbd778fae393e80323fd643209841a3b7f110397f37ec61d84cea03dcc5e8385db93248584e8af4b4d1c832d8c7453c0089687a700", ByteUtil.toHexString(payload)); } |
ECDSASignature { public boolean validateComponents() { return validateComponents(r, s, v); } ECDSASignature(BigInteger r, BigInteger s); ECDSASignature(BigInteger r, BigInteger s, byte v); static ECDSASignature fromComponentsWithRecoveryCalculation(byte[] r, byte[] s, byte[] hash, byte[] pub); static ECDSASignature fromSignature(ECKey.ECDSASignature sign); BigInteger getR(); BigInteger getS(); byte getV(); void setV(byte v); static ECDSASignature fromComponents(byte[] r, byte[] s); static ECDSASignature fromComponents(byte[] r, byte[] s, byte v); boolean validateComponents(); static boolean validateComponents(BigInteger r, BigInteger s, byte v); ECDSASignature toCanonicalised(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void testValidateComponents() { assertTrue(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 27).validateComponents()); assertTrue(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 28).validateComponents()); assertTrue(new ECDSASignature(SECP256K1N.subtract(BigInteger.ONE), BigInteger.ONE, (byte) 28).validateComponents()); assertTrue(new ECDSASignature(BigInteger.ONE, SECP256K1N.subtract(BigInteger.ONE), (byte) 28).validateComponents()); assertFalse(new ECDSASignature(BigInteger.ZERO, BigInteger.ONE, (byte) 27).validateComponents()); assertFalse(new ECDSASignature(SECP256K1N, BigInteger.ONE, (byte) 27).validateComponents()); assertFalse(new ECDSASignature(BigInteger.ONE, BigInteger.ZERO, (byte) 27).validateComponents()); assertFalse(new ECDSASignature(BigInteger.ONE, SECP256K1N, (byte) 27).validateComponents()); assertFalse(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 29).validateComponents()); assertFalse(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 26).validateComponents()); } |
SkeletonResponseMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } SkeletonResponseMessage(long id, List<BlockIdentifier> blockIdentifiers); @Override MessageType getMessageType(); @Override byte[] getEncodedMessageWithoutId(); long getId(); List<BlockIdentifier> getBlockIdentifiers(); @Override void accept(MessageVisitor v); } | @Test public void accept() { List<BlockIdentifier> blockIdentifiers = new LinkedList<>(); SkeletonResponseMessage message = new SkeletonResponseMessage(1, blockIdentifiers); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
BodyResponseMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BodyResponseMessage(long id, List<Transaction> transactions, List<BlockHeader> uncles); @Override long getId(); List<Transaction> getTransactions(); List<BlockHeader> getUncles(); @Override MessageType getMessageType(); @Override void accept(MessageVisitor v); } | @Test public void accept() { List<Transaction> transactions = new LinkedList<>(); List<BlockHeader> uncles = new LinkedList<>(); BodyResponseMessage message = new BodyResponseMessage(100, transactions, uncles); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
SkeletonRequestMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } SkeletonRequestMessage(long id, long startNumber); @Override MessageType getMessageType(); @Override MessageType getResponseMessageType(); @Override byte[] getEncodedMessageWithoutId(); long getId(); long getStartNumber(); @Override void accept(MessageVisitor v); } | @Test public void accept() { SkeletonRequestMessage message = new SkeletonRequestMessage(1, 10); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
BlockHashResponseMessage extends MessageWithId { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockHashResponseMessage(long id, byte[] hash); @Override MessageType getMessageType(); @Override byte[] getEncodedMessageWithoutId(); long getId(); byte[] getHash(); @Override void accept(MessageVisitor v); } | @Test public void accept() { long someId = 42; byte[] hash = new byte[32]; Random random = new Random(); random.nextBytes(hash); BlockHashResponseMessage message = new BlockHashResponseMessage(someId, hash); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
ECDSASignature { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ECDSASignature signature = (ECDSASignature) o; if (!r.equals(signature.r)) { return false; } return s.equals(signature.s); } ECDSASignature(BigInteger r, BigInteger s); ECDSASignature(BigInteger r, BigInteger s, byte v); static ECDSASignature fromComponentsWithRecoveryCalculation(byte[] r, byte[] s, byte[] hash, byte[] pub); static ECDSASignature fromSignature(ECKey.ECDSASignature sign); BigInteger getR(); BigInteger getS(); byte getV(); void setV(byte v); static ECDSASignature fromComponents(byte[] r, byte[] s); static ECDSASignature fromComponents(byte[] r, byte[] s, byte v); boolean validateComponents(); static boolean validateComponents(BigInteger r, BigInteger s, byte v); ECDSASignature toCanonicalised(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void testEquals() { ECDSASignature expected = new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 27); assertEquals(expected, expected); assertEquals(expected, new ECDSASignature(expected.getR(), expected.getS(), expected.getV())); assertEquals(expected, new ECDSASignature(expected.getR(), expected.getS(), (byte) 0)); assertNotEquals(expected, null); assertNotEquals(expected, BigInteger.ZERO); assertNotEquals(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 27), new ECDSASignature(BigInteger.TEN, BigInteger.ONE, (byte) 27)); assertNotEquals(new ECDSASignature(BigInteger.ONE, BigInteger.ONE, (byte) 27), new ECDSASignature(BigInteger.ONE, BigInteger.TEN, (byte) 27)); } |
TransactionsMessage extends Message { @Override public MessageType getMessageType() { return MessageType.TRANSACTIONS; } TransactionsMessage(List<Transaction> transactions); List<Transaction> getTransactions(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); String getMessageContentInfo(); @Override void accept(MessageVisitor v); } | @Test public void getMessageType() { TransactionsMessage message = new TransactionsMessage(null); Assert.assertEquals(MessageType.TRANSACTIONS, message.getMessageType()); } |
TransactionsMessage extends Message { public List<Transaction> getTransactions() { return this.transactions; } TransactionsMessage(List<Transaction> transactions); List<Transaction> getTransactions(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); String getMessageContentInfo(); @Override void accept(MessageVisitor v); } | @Test public void setAndGetTransactions() { List<Transaction> txs = TransactionUtils.getTransactions(10); TransactionsMessage message = new TransactionsMessage(txs); Assert.assertNotNull(message.getTransactions()); Assert.assertEquals(10, message.getTransactions().size()); Assert.assertSame(txs, message.getTransactions()); } |
TransactionsMessage extends Message { @Override public void accept(MessageVisitor v) { v.apply(this); } TransactionsMessage(List<Transaction> transactions); List<Transaction> getTransactions(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); String getMessageContentInfo(); @Override void accept(MessageVisitor v); } | @Test public void accept() { List<Transaction> txs = new LinkedList<>(); TransactionsMessage message = new TransactionsMessage(txs); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
GetBlockMessage extends Message { @Override public void accept(MessageVisitor v) { v.apply(this); } GetBlockMessage(byte[] hash); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); byte[] getBlockHash(); @Override void accept(MessageVisitor v); } | @Test public void accept() { byte[] hash = new byte[]{0x0F}; GetBlockMessage message = new GetBlockMessage(hash); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
BlockMessage extends Message { @Override public MessageType getMessageType() { return MessageType.BLOCK_MESSAGE; } BlockMessage(Block block); Block getBlock(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); @Override void accept(MessageVisitor v); } | @Test public void getMessageType() { BlockMessage message = new BlockMessage(null); Assert.assertEquals(MessageType.BLOCK_MESSAGE, message.getMessageType()); } |
BlockMessage extends Message { public Block getBlock() { return this.block; } BlockMessage(Block block); Block getBlock(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); @Override void accept(MessageVisitor v); } | @Test public void getBlock() { Block block = mock(Block.class); BlockMessage message = new BlockMessage(block); Assert.assertSame(block, message.getBlock()); } |
BlockMessage extends Message { @Override public void accept(MessageVisitor v) { v.apply(this); } BlockMessage(Block block); Block getBlock(); @Override MessageType getMessageType(); @Override byte[] getEncodedMessage(); @Override void accept(MessageVisitor v); } | @Test public void accept() { Block block = mock(Block.class); BlockMessage message = new BlockMessage(block); MessageVisitor visitor = mock(MessageVisitor.class); message.accept(visitor); verify(visitor, times(1)).apply(message); } |
BlockSyncService { public BlockProcessResult processBlock(@Nonnull Block block, Peer sender, boolean ignoreMissingHashes) { Instant start = Instant.now(); long bestBlockNumber = this.getBestBlockNumber(); long blockNumber = block.getNumber(); final Keccak256 blockHash = block.getHash(); int syncMaxDistance = syncConfiguration.getChunkSize() * syncConfiguration.getMaxSkeletonChunks(); tryReleaseStore(bestBlockNumber); store.removeHeader(block.getHeader()); if (blockNumber > bestBlockNumber + syncMaxDistance) { logger.trace("Block too advanced {} {} from {} ", blockNumber, block.getPrintableHash(), sender != null ? sender.getPeerNodeID().toString() : "N/A"); return new BlockProcessResult(false, null, block.getPrintableHash(), Duration.between(start, Instant.now())); } if (sender != null) { nodeInformation.addBlockToNode(blockHash, sender.getPeerNodeID()); } if (BlockUtils.blockInSomeBlockChain(block, blockchain)) { logger.trace("Block already in a chain {} {}", blockNumber, block.getPrintableHash()); return new BlockProcessResult(false, null, block.getPrintableHash(), Duration.between(start, Instant.now())); } trySaveStore(block); Set<Keccak256> unknownHashes = BlockUtils.unknownDirectAncestorsHashes(block, blockchain, store); if (!unknownHashes.isEmpty()) { if (!ignoreMissingHashes){ logger.trace("Missing hashes for block in process {} {}", blockNumber, block.getPrintableHash()); requestMissingHashes(sender, unknownHashes); } return new BlockProcessResult(false, null, block.getPrintableHash(), Duration.between(start, Instant.now())); } logger.trace("Trying to add to blockchain"); Map<Keccak256, ImportResult> connectResult = connectBlocksAndDescendants(sender, BlockUtils.sortBlocksByNumber(this.getParentsNotInBlockchain(block)), ignoreMissingHashes); return new BlockProcessResult(true, connectResult, block.getPrintableHash(), Duration.between(start, Instant.now())); } BlockSyncService(
@Nonnull final RskSystemProperties config,
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final SyncConfiguration syncConfiguration); BlockProcessResult processBlock(@Nonnull Block block, Peer sender, boolean ignoreMissingHashes); boolean hasBetterBlockToSync(); boolean canBeIgnoredForUnclesRewards(long blockNumber); long getLastKnownBlockNumber(); void setLastKnownBlockNumber(long lastKnownBlockNumber); @CheckForNull Block getBlockFromStoreOrBlockchain(@Nonnull final byte[] hash); static final int CHUNK_PART_LIMIT; static final int PROCESSED_BLOCKS_TO_CHECK_STORE; static final int RELEASED_RANGE; } | @Test public void sendBlockMessagesAndAddThemToBlockchain() { for (int i = 0; i < 50; i += 5) { Blockchain blockchain = new BlockChainBuilder().ofSize(10 * i); NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, SyncConfiguration.IMMEDIATE_FOR_TESTING); Assert.assertEquals(10 * i, blockchain.getBestBlock().getNumber()); List<Block> extendedChain = new BlockGenerator().getBlockChain(blockchain.getBestBlock(), i); for (Block block : extendedChain) { blockSyncService.processBlock(block, null, false); Assert.assertEquals(block.getNumber(), blockchain.getBestBlock().getNumber()); Assert.assertEquals(block.getHash(), blockchain.getBestBlock().getHash()); } } }
@Test public void sendBlockMessagesAndAddThemToBlockchainInReverseOrder() { for (int i = 1; i < 52; i += 5) { Blockchain blockchain = new BlockChainBuilder().ofSize(10 * i); NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, SyncConfiguration.IMMEDIATE_FOR_TESTING); Assert.assertEquals(10 * i, blockchain.getBestBlock().getNumber()); Block initialBestBlock = blockchain.getBestBlock(); List<Block> extendedChain = new BlockGenerator().getBlockChain(blockchain.getBestBlock(), i); Collections.reverse(extendedChain); for (int j = 0; j < extendedChain.size() - 1; j++) { Block block = extendedChain.get(j); blockSyncService.processBlock(block, null, false); Assert.assertEquals(initialBestBlock.getNumber(), blockchain.getBestBlock().getNumber()); Assert.assertEquals(initialBestBlock.getHash(), blockchain.getBestBlock().getHash()); } Block closingBlock = extendedChain.get(extendedChain.size() - 1); Block newBestBlock = extendedChain.get(0); blockSyncService.processBlock(closingBlock, null, false); Assert.assertEquals(newBestBlock.getNumber(), blockchain.getBestBlock().getNumber()); Assert.assertEquals(newBestBlock.getHash(), blockchain.getBestBlock().getHash()); } }
@Test public void sendBlockMessageAndAddItToBlockchainWithCommonAncestors() { Blockchain blockchain = new BlockChainBuilder().ofSize(10); NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, SyncConfiguration.IMMEDIATE_FOR_TESTING); Block initialBestBlock = blockchain.getBestBlock(); Assert.assertEquals(10, initialBestBlock.getNumber()); Block branchingPoint = blockchain.getBlockByNumber(7); BlockGenerator blockGenerator = new BlockGenerator(); List<Block> extendedChain = blockGenerator.getBlockChain(branchingPoint, 10, 1000000l); for (int i = 0; i < extendedChain.size(); i++) { Block newBestBlock = extendedChain.get(i); blockSyncService.processBlock(newBestBlock, null, false); Assert.assertEquals(newBestBlock.getNumber(), blockchain.getBestBlock().getNumber()); Assert.assertEquals(newBestBlock.getHash(), blockchain.getBestBlock().getHash()); } } |
ECDSASignature { public static ECDSASignature fromComponentsWithRecoveryCalculation(byte[] r, byte[] s, byte[] hash, byte[] pub) { byte v = calculateRecoveryByte(r, s, hash, pub); return fromComponents(r, s, v); } ECDSASignature(BigInteger r, BigInteger s); ECDSASignature(BigInteger r, BigInteger s, byte v); static ECDSASignature fromComponentsWithRecoveryCalculation(byte[] r, byte[] s, byte[] hash, byte[] pub); static ECDSASignature fromSignature(ECKey.ECDSASignature sign); BigInteger getR(); BigInteger getS(); byte getV(); void setV(byte v); static ECDSASignature fromComponents(byte[] r, byte[] s); static ECDSASignature fromComponents(byte[] r, byte[] s, byte v); boolean validateComponents(); static boolean validateComponents(BigInteger r, BigInteger s, byte v); ECDSASignature toCanonicalised(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void fromComponentsWithRecoveryCalculation() { ECKey key = new ECKey(); byte[] hash = HashUtil.randomHash(); ECDSASignature signature = ECDSASignature.fromSignature(key.sign(hash)); ECDSASignature signatureWithCalculatedV = ECDSASignature.fromComponentsWithRecoveryCalculation( signature.getR().toByteArray(), signature.getS().toByteArray(), hash, key.getPubKey(false) ); Assert.assertEquals(signature.getR(), signatureWithCalculatedV.getR()); Assert.assertEquals(signature.getS(), signatureWithCalculatedV.getS()); Assert.assertEquals(signature.getV(), signatureWithCalculatedV.getV()); signatureWithCalculatedV = ECDSASignature.fromComponentsWithRecoveryCalculation( signature.getR().toByteArray(), signature.getS().toByteArray(), hash, key.getPubKey(true) ); Assert.assertEquals(signature.getR(), signatureWithCalculatedV.getR()); Assert.assertEquals(signature.getS(), signatureWithCalculatedV.getS()); Assert.assertEquals(signature.getV(), signatureWithCalculatedV.getV()); } |
CallArgumentsToByteArray { public byte[] getData() { byte[] data = null; if (args.data != null && args.data.length() != 0) { data = stringHexToByteArray(args.data); } return data; } CallArgumentsToByteArray(Web3.CallArguments args); byte[] getGasPrice(); byte[] getGasLimit(); byte[] getToAddress(); byte[] getValue(); byte[] getData(); RskAddress getFromAddress(); } | @Test public void getDataWhenValueIsNull() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertNull(byteArrayArgs.getData()); }
@Test public void getDataWhenValueIsEmpty() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); args.data = ""; CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertNull(byteArrayArgs.getData()); } |
NodeBlockProcessor implements BlockProcessor { @Override public boolean isAdvancedBlock(long blockNumber) { int syncMaxDistance = syncConfiguration.getChunkSize() * syncConfiguration.getMaxSkeletonChunks(); long bestBlockNumber = this.getBestBlockNumber(); return blockNumber > bestBlockNumber + syncMaxDistance; } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test public void advancedBlock() throws UnknownHostException { final NetBlockStore store = new NetBlockStore(); final Peer sender = new SimplePeer(); final BlockNodeInformation nodeInformation = new BlockNodeInformation(); final SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; final Blockchain blockchain = new BlockChainBuilder().ofSize(0); final long advancedBlockNumber = syncConfiguration.getChunkSize() * syncConfiguration.getMaxSkeletonChunks() + blockchain.getBestBlock().getNumber() + 1; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); Assert.assertTrue(processor.isAdvancedBlock(advancedBlockNumber)); Assert.assertFalse(processor.isAdvancedBlock(advancedBlockNumber - 1)); } |
NodeBlockProcessor implements BlockProcessor { @Override public boolean canBeIgnoredForUnclesRewards(long blockNumber) { return blockSyncService.canBeIgnoredForUnclesRewards(blockNumber); } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test public void canBeIgnoredForUncles() throws UnknownHostException { final NetBlockStore store = new NetBlockStore(); final Peer sender = new SimplePeer(); final BlockNodeInformation nodeInformation = new BlockNodeInformation(); final SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; final Blockchain blockchain = new BlockChainBuilder().ofSize(15); final TestSystemProperties config = new TestSystemProperties(); int uncleGenerationLimit = config.getNetworkConstants().getUncleGenerationLimit(); final long blockNumberThatCanBeIgnored = blockchain.getBestBlock().getNumber() - 1 - uncleGenerationLimit; BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); Assert.assertTrue(processor.canBeIgnoredForUnclesRewards(blockNumberThatCanBeIgnored)); Assert.assertFalse(processor.canBeIgnoredForUnclesRewards(blockNumberThatCanBeIgnored + 1)); } |
NodeBlockProcessor implements BlockProcessor { @Override public BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block) { return blockSyncService.processBlock(block, sender, false); } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test public void processTenBlocksAddingToBlockchain() { Blockchain blockchain = new BlockChainBuilder().ofSize(0); NetBlockStore store = new NetBlockStore(); Block genesis = blockchain.getBestBlock(); List<Block> blocks = new BlockGenerator().getBlockChain(genesis, 10); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); processor.processBlock(null, genesis); Assert.assertEquals(0, store.size()); for (Block b : blocks) processor.processBlock(null, b); Assert.assertEquals(10, blockchain.getBestBlock().getNumber()); Assert.assertEquals(0, store.size()); }
@Test public void processTwoBlockListsAddingToBlockchain() { Blockchain blockchain = new BlockChainBuilder().ofSize(0); NetBlockStore store = new NetBlockStore(); Block genesis = blockchain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); List<Block> blocks = blockGenerator.getBlockChain(genesis, 10); List<Block> blocks2 = blockGenerator.getBlockChain(genesis, 20); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); processor.processBlock(null, genesis); Assert.assertEquals(0, store.size()); for (Block b : blocks) processor.processBlock(null, b); for (Block b : blocks2) processor.processBlock(null, b); Assert.assertEquals(20, blockchain.getBestBlock().getNumber()); Assert.assertEquals(0, store.size()); }
@Test public void processTwoBlockListsAddingToBlockchainWithFork() { NetBlockStore store = new NetBlockStore(); Blockchain blockchain = new BlockChainBuilder().ofSize(0); Block genesis = blockchain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); List<Block> blocks = blockGenerator.getBlockChain(genesis, 10); List<Block> blocks2 = blockGenerator.getBlockChain(blocks.get(4), 20); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); processor.processBlock(null, genesis); Assert.assertEquals(0, store.size()); for (Block b : blocks) processor.processBlock(null, b); for (Block b : blocks2) processor.processBlock(null, b); Assert.assertEquals(25, blockchain.getBestBlock().getNumber()); Assert.assertEquals(0, store.size()); }
@Test public void processTenBlocksGenesisAtLastAddingToBlockchain() { NetBlockStore store = new NetBlockStore(); Blockchain blockchain = new BlockChainBuilder().ofSize(0); Block genesis = blockchain.getBestBlock(); List<Block> blocks = new BlockGenerator().getBlockChain(genesis, 10); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); for (Block b : blocks) processor.processBlock(null, b); processor.processBlock(null, genesis); Assert.assertEquals(10, blockchain.getBestBlock().getNumber()); Assert.assertEquals(0, store.size()); }
@Test public void processTenBlocksInverseOrderAddingToBlockchain() { Blockchain blockchain = new BlockChainBuilder().ofSize(0); NetBlockStore store = new NetBlockStore(); Block genesis = blockchain.getBestBlock(); List<Block> blocks = new BlockGenerator().getBlockChain(genesis, 10); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); for (int k = 0; k < 10; k++) processor.processBlock(null, blocks.get(9 - k)); processor.processBlock(null, genesis); Assert.assertEquals(10, blockchain.getBestBlock().getNumber()); Assert.assertEquals(0, store.size()); }
@Test public void processTenBlocksWithHoleAddingToBlockchain() { Blockchain blockchain = new BlockChainBuilder().ofSize(0); NetBlockStore store = new NetBlockStore(); Block genesis = blockchain.getBestBlock(); List<Block> blocks = new BlockGenerator().getBlockChain(genesis, 10); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); for (int k = 0; k < 10; k++) if (k != 5) processor.processBlock(null, blocks.get(9 - k)); processor.processBlock(null, genesis); processor.processBlock(null, blocks.get(4)); Assert.assertEquals(10, blockchain.getBestBlock().getNumber()); Assert.assertEquals(0, store.size()); } |
NodeBlockProcessor implements BlockProcessor { @Override public boolean hasBetterBlockToSync() { return blockSyncService.hasBetterBlockToSync(); } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test public void noSyncingWithEmptyBlockchain() { NetBlockStore store = new NetBlockStore(); Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); Assert.assertFalse(processor.hasBetterBlockToSync()); }
@Test @Ignore("Ignored when Process status deleted on block processor") public void noSyncingWithEmptyBlockchainAndLowBestBlock() { NetBlockStore store = new NetBlockStore(); Block block = new BlockGenerator().createBlock(10, 0); Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); Assert.assertFalse(processor.hasBetterBlockToSync()); Status status = new Status(block.getNumber(), block.getHash().getBytes()); Assert.assertFalse(processor.hasBetterBlockToSync()); }
@Test @Ignore("Ignored when Process status deleted on block processor") public void syncingWithEmptyBlockchainAndHighBestBlock() { NetBlockStore store = new NetBlockStore(); Block block = new BlockGenerator().createBlock(30, 0); Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); Assert.assertFalse(processor.hasBetterBlockToSync()); Assert.assertTrue(processor.hasBetterBlockToSync()); }
@Test @Ignore("Ignored when Process status deleted on block processor") public void syncingThenNoSyncing() { NetBlockStore store = new NetBlockStore(); Block block = new BlockGenerator().createBlock(30, 0); Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); Assert.assertFalse(processor.hasBetterBlockToSync()); Assert.assertTrue(processor.hasBetterBlockToSync()); Assert.assertTrue(processor.hasBetterBlockToSync()); blockchain.setStatus(block, new BlockDifficulty(BigInteger.valueOf(30))); Assert.assertFalse(processor.hasBetterBlockToSync()); Assert.assertFalse(processor.hasBetterBlockToSync()); Block block2 = new BlockGenerator().createBlock(60, 0); Assert.assertTrue(processor.hasBetterBlockToSync()); Assert.assertFalse(processor.hasBetterBlockToSync()); } |
ECKey { @Override public int hashCode() { byte[] bits = getPubKey(true); return (bits[0] & 0xFF) | ((bits[1] & 0xFF) << 8) | ((bits[2] & 0xFF) << 16) | ((bits[3] & 0xFF) << 24); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; } | @Test public void testHashCode() { Assert.assertEquals(1866897155, ECKey.fromPrivate(privateKey).hashCode()); } |
NodeBlockProcessor implements BlockProcessor { @Override public BlockNodeInformation getNodeInformation() { return nodeInformation; } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test @Ignore("Ignored when Process status deleted on block processor") public void processStatusRetrievingBestBlockUsingSender() throws UnknownHostException { final NetBlockStore store = new NetBlockStore(); final Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); BlockGenerator blockGenerator = new BlockGenerator(); final Block genesis = blockGenerator.getGenesisBlock(); final Block block = blockGenerator.createChildBlock(genesis); Assert.assertTrue(processor.getNodeInformation().getNodesByBlock(block.getHash().getBytes()).size() == 1); Assert.assertEquals(1, sender.getGetBlockMessages().size()); final Message message = sender.getGetBlockMessages().get(0); Assert.assertNotNull(message); Assert.assertEquals(MessageType.GET_BLOCK_MESSAGE, message.getMessageType()); final GetBlockMessage gbMessage = (GetBlockMessage) message; Assert.assertArrayEquals(block.getHash().getBytes(), gbMessage.getBlockHash()); Assert.assertEquals(0, store.size()); }
@Test @Ignore("Ignored when Process status deleted on block processor") public void processStatusHavingBestBlockInStore() throws UnknownHostException { final NetBlockStore store = new NetBlockStore(); final Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); BlockGenerator blockGenerator = new BlockGenerator(); final Block genesis = blockGenerator.getGenesisBlock(); final Block block = blockGenerator.createChildBlock(genesis); store.saveBlock(block); Assert.assertTrue(processor.getNodeInformation().getNodesByBlock(block.getHash().getBytes()).size() == 1); Assert.assertEquals(1, store.size()); }
@Test @Ignore("Ignored when Process status deleted on block processor") public void processStatusHavingBestBlockAsBestBlockInBlockchain() throws UnknownHostException { final NetBlockStore store = new NetBlockStore(); final Blockchain blockchain = new BlockChainBuilder().ofSize(2); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); final Block block = blockchain.getBestBlock(); final Keccak256 blockHash = block.getHash(); Assert.assertTrue(processor.getNodeInformation().getNodesByBlock(block.getHash().getBytes()).size() == 1); Assert.assertTrue(processor.getNodeInformation().getNodesByBlock(block.getHash().getBytes()).contains(sender.getPeerNodeID())); Assert.assertEquals(0, sender.getGetBlockMessages().size()); Assert.assertEquals(0, store.size()); } |
NodeBlockProcessor implements BlockProcessor { @Override public void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count) { logger.trace("Processing headers request {} {} from {}", requestId, ByteUtil.toHexString(hash), sender.getPeerNodeID()); if (count > syncConfiguration.getChunkSize()) { logger.trace("Headers request from {} failed because size {}", sender.getPeerNodeID(), count); return; } Block block = blockSyncService.getBlockFromStoreOrBlockchain(hash); if (block == null) { return; } List<BlockHeader> headers = new ArrayList<>(); headers.add(block.getHeader()); for (int k = 1; k < count; k++) { block = blockSyncService.getBlockFromStoreOrBlockchain(block.getParentHash().getBytes()); if (block == null) { break; } headers.add(block.getHeader()); } BlockHeadersResponseMessage response = new BlockHeadersResponseMessage(requestId, headers); sender.sendMessage(response); } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test public void processGetBlockHeaderMessageUsingBlockInStore() throws UnknownHostException { final Block block = new BlockGenerator().getBlock(3); final NetBlockStore store = new NetBlockStore(); store.saveBlock(block); final Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processBlockHeadersRequest(sender, 1, block.getHash().getBytes(), 1); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_HEADERS_RESPONSE_MESSAGE, message.getMessageType()); final BlockHeadersResponseMessage bMessage = (BlockHeadersResponseMessage) message; Assert.assertEquals(block.getHeader().getHash(), bMessage.getBlockHeaders().get(0).getHash()); }
@Test public void processGetBlockHeaderMessageUsingEmptyStore() throws UnknownHostException { final Block block = new BlockGenerator().getBlock(3); final NetBlockStore store = new NetBlockStore(); final Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).isEmpty()); processor.processBlockHeadersRequest(sender, 1, block.getHash().getBytes(), 1); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).isEmpty()); Assert.assertTrue(sender.getMessages().isEmpty()); }
@Test public void processGetBlockHeaderMessageUsingBlockInBlockchain() throws UnknownHostException { final Blockchain blockchain = new BlockChainBuilder().ofSize(10); final Block block = blockchain.getBlockByNumber(5); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processBlockHeadersRequest(sender, 1, block.getHash().getBytes(), 1); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_HEADERS_RESPONSE_MESSAGE, message.getMessageType()); final BlockHeadersResponseMessage bMessage = (BlockHeadersResponseMessage) message; Assert.assertEquals(block.getHeader().getHash(), bMessage.getBlockHeaders().get(0).getHash()); }
@Test public void processBlockHeadersRequestMessageUsingBlockInBlockchain() throws UnknownHostException { final Blockchain blockchain = new BlockChainBuilder().ofSize(100); final Block block = blockchain.getBlockByNumber(60); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processBlockHeadersRequest(sender, 100, block.getHash().getBytes(), 20); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_HEADERS_RESPONSE_MESSAGE, message.getMessageType()); final BlockHeadersResponseMessage response = (BlockHeadersResponseMessage) message; Assert.assertEquals(100, response.getId()); Assert.assertNotNull(response.getBlockHeaders()); Assert.assertEquals(20, response.getBlockHeaders().size()); for (int k = 0; k < 20; k++) Assert.assertEquals(blockchain.getBlockByNumber(60 - k).getHash(), response.getBlockHeaders().get(k).getHash()); }
@Test public void processBlockHeadersRequestMessageUsingUnknownHash() throws UnknownHostException { final Blockchain blockchain = new BlockChainBuilder().ofSize(100); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processBlockHeadersRequest(sender, 100, HashUtil.randomHash(), 20); Assert.assertTrue(sender.getMessages().isEmpty()); }
@Test public void failIfProcessBlockHeadersRequestCountHigher() { final Peer sender = mock(Peer.class); final Block block = new BlockGenerator().getBlock(3); final NetBlockStore store = new NetBlockStore(); store.saveBlock(block); final Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final Integer size = syncConfiguration.getChunkSize() + 1; processor.processBlockHeadersRequest(sender, 1, block.getHash().getBytes(), size); verify(sender, never()).sendMessage(any()); } |
NodeBlockProcessor implements BlockProcessor { @Override public void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash) { logger.trace("Processing get block {} from {}", ByteUtil.toHexString(hash), sender.getPeerNodeID()); final Block block = blockSyncService.getBlockFromStoreOrBlockchain(hash); if (block == null) { return; } nodeInformation.addBlockToNode(new Keccak256(hash), sender.getPeerNodeID()); sender.sendMessage(new BlockMessage(block)); } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test public void processGetBlockMessageUsingBlockInStore() throws UnknownHostException { final Block block = new BlockGenerator().getBlock(3); final Keccak256 blockHash = block.getHash(); final NetBlockStore store = new NetBlockStore(); store.saveBlock(block); final Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).isEmpty()); processor.processGetBlock(sender, block.getHash().getBytes()); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).contains(sender.getPeerNodeID())); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_MESSAGE, message.getMessageType()); final BlockMessage bMessage = (BlockMessage) message; Assert.assertEquals(block.getHash(), bMessage.getBlock().getHash()); }
@Test public void processGetBlockMessageUsingEmptyStore() throws UnknownHostException { final Block block = new BlockGenerator().getBlock(3); final NetBlockStore store = new NetBlockStore(); final Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).isEmpty()); processor.processGetBlock(sender, block.getHash().getBytes()); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).isEmpty()); Assert.assertTrue(sender.getMessages().isEmpty()); }
@Test public void processGetBlockMessageUsingBlockInBlockchain() throws UnknownHostException { final Blockchain blockchain = new BlockChainBuilder().ofSize(10); final Block block = blockchain.getBlockByNumber(5); final Keccak256 blockHash = block.getHash(); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).isEmpty()); processor.processGetBlock(sender, block.getHash().getBytes()); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).contains(sender.getPeerNodeID())); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_MESSAGE, message.getMessageType()); final BlockMessage bMessage = (BlockMessage) message; Assert.assertEquals(block.getHash(), bMessage.getBlock().getHash()); } |
ECKey { public ECKey() { this(secureRandom); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; } | @Test public void testECKey() { ECKey key = new ECKey(); assertTrue(key.isPubKeyCanonical()); assertNotNull(key.getPubKey()); assertNotNull(key.getPrivKeyBytes()); log.debug(ByteUtil.toHexString(key.getPrivKeyBytes()) + " :Generated privkey"); log.debug(ByteUtil.toHexString(key.getPubKey()) + " :Generated pubkey"); } |
NodeBlockProcessor implements BlockProcessor { @Override public void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash) { logger.trace("Processing get block by hash {} {} from {}", requestId, ByteUtil.toHexString(hash), sender.getPeerNodeID()); final Block block = blockSyncService.getBlockFromStoreOrBlockchain(hash); if (block == null) { return; } nodeInformation.addBlockToNode(new Keccak256(hash), sender.getPeerNodeID()); sender.sendMessage(new BlockResponseMessage(requestId, block)); } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test public void processBlockRequestMessageUsingBlockInStore() throws UnknownHostException { final Block block = new BlockGenerator().getBlock(3); final Keccak256 blockHash = block.getHash(); final NetBlockStore store = new NetBlockStore(); store.saveBlock(block); final Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).isEmpty()); processor.processBlockRequest(sender, 100, block.getHash().getBytes()); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).contains(sender.getPeerNodeID())); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_RESPONSE_MESSAGE, message.getMessageType()); final BlockResponseMessage bMessage = (BlockResponseMessage) message; Assert.assertEquals(100, bMessage.getId()); Assert.assertEquals(block.getHash(), bMessage.getBlock().getHash()); }
@Test public void processBlockHashRequestMessageUsingEmptyStore() throws UnknownHostException { final Block block = new BlockGenerator().getBlock(3); final Keccak256 blockHash = block.getHash(); final NetBlockStore store = new NetBlockStore(); final Blockchain blockchain = new BlockChainBuilder().ofSize(0); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).isEmpty()); processor.processBlockRequest(sender, 100, block.getHash().getBytes()); Assert.assertFalse(nodeInformation.getNodesByBlock(block.getHash()).contains(sender.getPeerNodeID())); Assert.assertTrue(sender.getMessages().isEmpty()); }
@Test public void processBlockHashRequestMessageUsingBlockInBlockchain() throws UnknownHostException { final Blockchain blockchain = new BlockChainBuilder().ofSize(10); final Block block = blockchain.getBlockByNumber(5); final Keccak256 blockHash = block.getHash(); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).isEmpty()); processor.processBlockRequest(sender, 100, block.getHash().getBytes()); Assert.assertTrue(nodeInformation.getNodesByBlock(block.getHash()).contains(sender.getPeerNodeID())); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_RESPONSE_MESSAGE, message.getMessageType()); final BlockResponseMessage bMessage = (BlockResponseMessage) message; Assert.assertEquals(100, bMessage.getId()); Assert.assertEquals(block.getHash(), bMessage.getBlock().getHash()); } |
NodeBlockProcessor implements BlockProcessor { @Override public void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash) { logger.trace("Processing body request {} {} from {}", requestId, ByteUtil.toHexString(hash), sender.getPeerNodeID()); final Block block = blockSyncService.getBlockFromStoreOrBlockchain(hash); if (block == null) { return; } Message responseMessage = new BodyResponseMessage(requestId, block.getTransactionsList(), block.getUncleList()); sender.sendMessage(responseMessage); } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test public void processBodyRequestMessageUsingBlockInBlockchain() throws UnknownHostException { final Blockchain blockchain = new BlockChainBuilder().ofSize(10); final Block block = blockchain.getBlockByNumber(3); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processBodyRequest(sender, 100, block.getHash().getBytes()); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BODY_RESPONSE_MESSAGE, message.getMessageType()); final BodyResponseMessage bMessage = (BodyResponseMessage) message; Assert.assertEquals(100, bMessage.getId()); Assert.assertEquals(block.getTransactionsList(), bMessage.getTransactions()); Assert.assertEquals(block.getUncleList(), bMessage.getUncles()); } |
NodeBlockProcessor implements BlockProcessor { @Override public void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height) { logger.trace("Processing block hash request {} {} from {}", requestId, height, sender.getPeerNodeID()); if (height == 0){ return; } final Block block = this.getBlockFromBlockchainStore(height); if (block == null) { return; } BlockHashResponseMessage responseMessage = new BlockHashResponseMessage(requestId, block.getHash().getBytes()); sender.sendMessage(responseMessage); } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test public void processBlockHashRequestMessageUsingOutOfBoundsHeight() throws UnknownHostException { final Blockchain blockchain = new BlockChainBuilder().ofSize(10); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processBlockHashRequest(sender, 100, 99999); Assert.assertTrue(sender.getMessages().isEmpty()); } |
NodeBlockProcessor implements BlockProcessor { @Override public void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber) { logger.trace("Processing skeleton request {} {} from {}", requestId, startNumber, sender.getPeerNodeID()); int skeletonStep = syncConfiguration.getChunkSize(); Block blockStart = this.getBlockFromBlockchainStore(startNumber); if (blockStart == null) { return; } long skeletonStartHeight = (blockStart.getNumber() / skeletonStep) * skeletonStep; List<BlockIdentifier> blockIdentifiers = new ArrayList<>(); long skeletonNumber = skeletonStartHeight; int maxSkeletonChunks = syncConfiguration.getMaxSkeletonChunks(); long maxSkeletonNumber = Math.min(this.getBestBlockNumber(), skeletonStartHeight + skeletonStep * maxSkeletonChunks); for (; skeletonNumber < maxSkeletonNumber; skeletonNumber += skeletonStep) { byte[] skeletonHash = getSkeletonHash(skeletonNumber); blockIdentifiers.add(new BlockIdentifier(skeletonHash, skeletonNumber)); } skeletonNumber = Math.min(this.getBestBlockNumber(), skeletonNumber); byte[] skeletonHash = getSkeletonHash(skeletonNumber); blockIdentifiers.add(new BlockIdentifier(skeletonHash, skeletonNumber)); SkeletonResponseMessage responseMessage = new SkeletonResponseMessage(requestId, blockIdentifiers); sender.sendMessage(responseMessage); } NodeBlockProcessor(
@Nonnull final NetBlockStore store,
@Nonnull final Blockchain blockchain,
@Nonnull final BlockNodeInformation nodeInformation,
@Nonnull final BlockSyncService blockSyncService,
@Nonnull final SyncConfiguration syncConfiguration); @Override boolean isAdvancedBlock(long blockNumber); @Override void processNewBlockHashesMessage(final Peer sender, final NewBlockHashesMessage message); @Override void processBlockHeaders(@Nonnull final Peer sender, @Nonnull final List<BlockHeader> blockHeaders); @Override void processGetBlock(@Nonnull final Peer sender, @Nonnull final byte[] hash); @Override void processBlockRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHeadersRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash, int count); @Override void processBodyRequest(@Nonnull final Peer sender, long requestId, @Nonnull final byte[] hash); @Override void processBlockHashRequest(@Nonnull final Peer sender, long requestId, long height); @Override void processSkeletonRequest(@Nonnull final Peer sender, long requestId, long startNumber); @Override boolean canBeIgnoredForUnclesRewards(long blockNumber); @Override BlockNodeInformation getNodeInformation(); long getBestBlockNumber(); @Override boolean hasBlock(@Nonnull final byte[] hash); @Override boolean hasBlockInProcessorStore(@Nonnull final byte[] hash); @Override BlockProcessResult processBlock(@Nullable final Peer sender, @Nonnull final Block block); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override boolean hasBetterBlockToSync(); @Override long getLastKnownBlockNumber(); } | @Test public void processSkeletonRequestWithGenesisPlusBestBlockInSkeleton() throws UnknownHostException { int skeletonStep = 192; final Blockchain blockchain = new BlockChainBuilder().ofSize(skeletonStep / 2); final Block blockStart = blockchain.getBlockByNumber(5); final Block blockEnd = blockchain.getBlockByNumber(skeletonStep / 2); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processSkeletonRequest(sender, 100, 5); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.SKELETON_RESPONSE_MESSAGE, message.getMessageType()); final SkeletonResponseMessage bMessage = (SkeletonResponseMessage) message; Assert.assertEquals(100, bMessage.getId()); Block genesis = blockchain.getBlockByNumber(0); Block bestBlock = blockchain.getBestBlock(); BlockIdentifier[] expected = { new BlockIdentifier(genesis.getHash().getBytes(), genesis.getNumber()), new BlockIdentifier(bestBlock.getHash().getBytes(), bestBlock.getNumber()), }; assertBlockIdentifiers(expected, bMessage.getBlockIdentifiers()); }
@Test public void processSkeletonRequestWithThreeResults() throws UnknownHostException { int skeletonStep = 192; final Blockchain blockchain = new BlockChainBuilder().ofSize(300); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processSkeletonRequest(sender, 100, 5); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.SKELETON_RESPONSE_MESSAGE, message.getMessageType()); final SkeletonResponseMessage bMessage = (SkeletonResponseMessage) message; Assert.assertEquals(100, bMessage.getId()); Block b1 = blockchain.getBlockByNumber(0); Block b2 = blockchain.getBlockByNumber(skeletonStep); Block b3 = blockchain.getBestBlock(); BlockIdentifier[] expected = { new BlockIdentifier(b1.getHash().getBytes(), b1.getNumber()), new BlockIdentifier(b2.getHash().getBytes(), b2.getNumber()), new BlockIdentifier(b3.getHash().getBytes(), b3.getNumber()), }; assertBlockIdentifiers(expected, bMessage.getBlockIdentifiers()); }
@Test public void processSkeletonRequestNotIncludingGenesis() throws UnknownHostException { int skeletonStep = 192; final Blockchain blockchain = new BlockChainBuilder().ofSize(400); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; TestSystemProperties config = new TestSystemProperties(); BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor processor = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); processor.processSkeletonRequest(sender, 100, skeletonStep + 5); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.SKELETON_RESPONSE_MESSAGE, message.getMessageType()); final SkeletonResponseMessage bMessage = (SkeletonResponseMessage) message; Assert.assertEquals(100, bMessage.getId()); Block b1 = blockchain.getBlockByNumber(skeletonStep); Block b2 = blockchain.getBlockByNumber(2 * skeletonStep); Block b3 = blockchain.getBestBlock(); BlockIdentifier[] expected = { new BlockIdentifier(b1.getHash().getBytes(), b1.getNumber()), new BlockIdentifier(b2.getHash().getBytes(), b2.getNumber()), new BlockIdentifier(b3.getHash().getBytes(), b3.getNumber()), }; assertBlockIdentifiers(expected, bMessage.getBlockIdentifiers()); } |
ECKey { public boolean isPubKeyOnly() { return priv == null; } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; } | @Test public void testIsPubKeyOnly() { ECKey key = ECKey.fromPublicOnly(pubKey); assertTrue(key.isPubKeyCanonical()); assertTrue(key.isPubKeyOnly()); assertArrayEquals(key.getPubKey(), pubKey); } |
BlockCache { public Block getBlockByHash(byte[] hash) { return blockMap.get(new Keccak256(hash)); } BlockCache(int cacheSize); void removeBlock(Block block); void addBlock(Block block); Block getBlockByHash(byte[] hash); } | @Test public void getUnknownBlockAsNull() { BlockCache store = getSubject(); assertThat(store.getBlockByHash(HASH_1), nullValue()); } |
RskWireProtocol extends SimpleChannelInboundHandler<EthMessage> implements Eth { @Override public void channelRead0(final ChannelHandlerContext ctx, EthMessage msg) throws InterruptedException { loggerNet.debug("Read message: {}", msg); if (EthMessageCodes.inRange(msg.getCommand().asByte(), version)) { loggerNet.trace("EthHandler invoke: [{}]", msg.getCommand()); } ethereumListener.trace(String.format("EthHandler invoke: [%s]", msg.getCommand())); channel.getNodeStatistics().getEthInbound().add(); msgQueue.receivedMessage(msg); if (this.messageRecorder != null) { this.messageRecorder.recordMessage(channel.getPeerNodeID(), msg); } if (!hasGoodReputation(ctx)) { ctx.disconnect(); return; } switch (msg.getCommand()) { case STATUS: processStatus((org.ethereum.net.eth.message.StatusMessage) msg, ctx); break; case RSK_MESSAGE: RskMessage rskmessage = (RskMessage)msg; Message message = rskmessage.getMessage(); switch (message.getMessageType()) { case BLOCK_MESSAGE: loggerNet.trace("RSK Block Message: Block {} {} from {}", ((BlockMessage)message).getBlock().getNumber(), ((BlockMessage)message).getBlock().getPrintableHash(), channel.getPeerNodeID()); syncStats.addBlocks(1); break; case GET_BLOCK_MESSAGE: loggerNet.trace("RSK Get Block Message: Block {} from {}", ByteUtil.toHexString(((GetBlockMessage)message).getBlockHash()), channel.getPeerNodeID()); syncStats.getBlock(); break; case STATUS_MESSAGE: loggerNet.trace("RSK Status Message: Block {} {} from {}", ((StatusMessage)message).getStatus().getBestBlockNumber(), ByteUtil.toHexString(((StatusMessage)message).getStatus().getBestBlockHash()), channel.getPeerNodeID()); syncStats.addStatus(); break; } if (this.messageHandler != null) { this.messageHandler.postMessage(channel, rskmessage.getMessage()); } break; default: break; } } RskWireProtocol(RskSystemProperties config,
PeerScoringManager peerScoringManager,
MessageHandler messageHandler,
CompositeEthereumListener ethereumListener,
Genesis genesis,
MessageRecorder messageRecorder,
StatusResolver statusResolver,
MessageQueue msgQueue,
Channel channel); @Override void channelRead0(final ChannelHandlerContext ctx, EthMessage msg); @Override void sendStatus(); @Override boolean hasStatusPassed(); @Override boolean hasStatusSucceeded(); @Override SyncStatistics getStats(); @Override EthVersion getVersion(); @Override void dropConnection(); @Override boolean isUsingNewProtocol(); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); @Override void handlerRemoved(ChannelHandlerContext ctx); void activate(); @Override void sendMessage(EthMessage message); } | @Test public void channelRead0_get_block_message() throws Exception { NodeStatistics.StatHandler statHandler = mock(NodeStatistics.StatHandler.class); NodeStatistics nodeStatistics = mock(NodeStatistics.class); when(channel.getNodeStatistics()).thenReturn(nodeStatistics); when(nodeStatistics.getEthInbound()).thenReturn(statHandler); Message message = new GetBlockMessage(new byte[32]); EthMessage rskMessage = new RskMessage(message); target.channelRead0(ctx, rskMessage); verify(messageHandler).postMessage(eq(channel), eq(message)); }
@Test public void channelRead0_block_message() throws Exception { NodeStatistics.StatHandler statHandler = mock(NodeStatistics.StatHandler.class); NodeStatistics nodeStatistics = mock(NodeStatistics.class); when(channel.getNodeStatistics()).thenReturn(nodeStatistics); when(nodeStatistics.getEthInbound()).thenReturn(statHandler); Block block = mock(Block.class); when(block.getHash()).thenReturn(new Keccak256(new byte[32])); Message message = new BlockMessage(block); EthMessage rskMessage = new RskMessage(message); target.channelRead0(ctx, rskMessage); verify(messageHandler).postMessage(eq(channel), eq(message)); }
@Test public void channelRead0_status_message() throws Exception { NodeStatistics.StatHandler statHandler = mock(NodeStatistics.StatHandler.class); NodeStatistics nodeStatistics = mock(NodeStatistics.class); when(channel.getNodeStatistics()).thenReturn(nodeStatistics); when(nodeStatistics.getEthInbound()).thenReturn(statHandler); Status status = mock(Status.class); when(status.getBestBlockHash()).thenReturn(new byte[32]); Message message = new co.rsk.net.messages.StatusMessage(status); EthMessage rskMessage = new RskMessage(message); target.channelRead0(ctx, rskMessage); verify(messageHandler).postMessage(eq(channel), eq(message)); } |
TxValidatorNotRemascTxValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { if (!(tx instanceof RemascTransaction)) { return TransactionValidationResult.ok(); } return TransactionValidationResult.withError("transaction is a remasc transaction"); } @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); } | @Test public void remascTx() { TxValidatorNotRemascTxValidator validator = new TxValidatorNotRemascTxValidator(); Transaction tx1 = Mockito.mock(RemascTransaction.class); Mockito.when(tx1.getHash()).thenReturn(Keccak256.ZERO_HASH); Assert.assertFalse(validator.validate(tx1, null, null, null, 0, false).transactionIsValid()); }
@Test public void commonTx() { TxValidatorNotRemascTxValidator validator = new TxValidatorNotRemascTxValidator(); Assert.assertTrue(validator.validate(Mockito.mock(Transaction.class), null, null, null, 0, false).transactionIsValid()); } |
TxValidatorIntrinsicGasLimitValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { if (BigInteger.valueOf(tx.transactionCost(constants, activationConfig.forBlock(bestBlockNumber))).compareTo(tx.getGasLimitAsInteger()) <= 0) { return TransactionValidationResult.ok(); } return TransactionValidationResult.withError("transaction's basic cost is above the gas limit"); } TxValidatorIntrinsicGasLimitValidator(Constants constants, ActivationConfig activationConfig); @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); } | @Test public void validIntrinsicGasPrice() { Transaction tx1 = new Transaction(BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), BigInteger.valueOf(21000).toByteArray(), new ECKey().getAddress(), BigInteger.ZERO.toByteArray(), null, Constants.REGTEST_CHAIN_ID); tx1.sign(new ECKey().getPrivKeyBytes()); Transaction tx2 = new Transaction(BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), BigInteger.valueOf(30000).toByteArray(), new ECKey().getAddress(), BigInteger.ZERO.toByteArray(), Hex.decode("0001"), Constants.REGTEST_CHAIN_ID); tx2.sign(new ECKey().getPrivKeyBytes()); Transaction tx3 = new Transaction(BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), BigInteger.valueOf(21072).toByteArray(), new ECKey().getAddress(), BigInteger.ZERO.toByteArray(), Hex.decode("0001"), Constants.REGTEST_CHAIN_ID); tx3.sign(new ECKey().getPrivKeyBytes()); Transaction tx4 = new Transaction(BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), PrecompiledContracts.BRIDGE_ADDR.getBytes(), BigInteger.ZERO.toByteArray(), null, Constants.REGTEST_CHAIN_ID); BridgeRegTestConstants bridgeRegTestConstants = BridgeRegTestConstants.getInstance(); tx4.sign(BridgeRegTestConstants.REGTEST_FEDERATION_PRIVATE_KEYS.get(0).getPrivKeyBytes()); TxValidatorIntrinsicGasLimitValidator tvigpv = new TxValidatorIntrinsicGasLimitValidator(constants, activationConfig); Assert.assertTrue(tvigpv.validate(tx1, new AccountState(), null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvigpv.validate(tx2, new AccountState(), null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvigpv.validate(tx3, new AccountState(), null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvigpv.validate(tx4, new AccountState(), null, null, Long.MAX_VALUE, false).transactionIsValid()); }
@Test public void invalidIntrinsicGasPrice() { Transaction tx1 = new Transaction(BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), BigInteger.valueOf(21071).toByteArray(), new ECKey().getAddress(), BigInteger.ZERO.toByteArray(), Hex.decode("0001"), Constants.REGTEST_CHAIN_ID); tx1.sign(new ECKey().getPrivKeyBytes()); Transaction tx2 = new Transaction(BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), BigInteger.valueOf(20999).toByteArray(), new ECKey().getAddress(), BigInteger.ZERO.toByteArray(), null, Constants.REGTEST_CHAIN_ID); tx2.sign(new ECKey().getPrivKeyBytes()); Transaction tx3 = new Transaction(BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), new ECKey().getAddress(), BigInteger.ZERO.toByteArray(), Hex.decode("0001"), Constants.REGTEST_CHAIN_ID); tx3.sign(new ECKey().getPrivKeyBytes()); Transaction tx4 = new Transaction(BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), BigInteger.ZERO.toByteArray(), new ECKey().getAddress(), BigInteger.ZERO.toByteArray(), null, Constants.REGTEST_CHAIN_ID); tx4.sign(new ECKey().getPrivKeyBytes()); TxValidatorIntrinsicGasLimitValidator tvigpv = new TxValidatorIntrinsicGasLimitValidator(constants, activationConfig); Assert.assertFalse(tvigpv.validate(tx1, new AccountState(), null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertFalse(tvigpv.validate(tx2, new AccountState(), null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertFalse(tvigpv.validate(tx3, new AccountState(), null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertFalse(tvigpv.validate(tx4, new AccountState(), null, null, Long.MAX_VALUE, false).transactionIsValid()); } |
ECKey { public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed) { ECPoint point = CURVE.getG().multiply(privKey); return point.getEncoded(compressed); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; } | @Test public void testPublicKeyFromPrivate() { byte[] pubFromPriv = ECKey.publicKeyFromPrivate(privateKey, false); assertArrayEquals(pubKey, pubFromPriv); }
@Test public void testPublicKeyFromPrivateCompressed() { byte[] pubFromPriv = ECKey.publicKeyFromPrivate(privateKey, true); assertArrayEquals(compressedPubKey, pubFromPriv); } |
TxValidatorGasLimitValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { BigInteger txGasLimit = tx.getGasLimitAsInteger(); if (txGasLimit.compareTo(gasLimit) <= 0 && txGasLimit.compareTo(Constants.getTransactionGasCap()) <= 0) { return TransactionValidationResult.ok(); } return TransactionValidationResult.withError(String.format( "transaction's gas limit of %s is higher than the block's gas limit of %s", txGasLimit, gasLimit )); } @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); } | @Test public void validGasLimit() { Transaction tx1 = Mockito.mock(Transaction.class); Transaction tx2 = Mockito.mock(Transaction.class); Mockito.when(tx1.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(1)); Mockito.when(tx2.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(6)); BigInteger gl = BigInteger.valueOf(6); TxValidatorGasLimitValidator tvglv = new TxValidatorGasLimitValidator(); Assert.assertTrue(tvglv.validate(tx1, null, gl, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvglv.validate(tx2, null, gl, null, Long.MAX_VALUE, false).transactionIsValid()); }
@Test public void invalidGasLimit() { Transaction tx1 = Mockito.mock(Transaction.class); Mockito.when(tx1.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(6)); Mockito.when(tx1.getHash()).thenReturn(Keccak256.ZERO_HASH); BigInteger gl = BigInteger.valueOf(3); TxValidatorGasLimitValidator tvglv = new TxValidatorGasLimitValidator(); Assert.assertFalse(tvglv.validate(tx1, null, gl, null, Long.MAX_VALUE, false).transactionIsValid()); } |
TxValidatorAccountStateValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { if (isFreeTx) { return TransactionValidationResult.ok(); } if (state == null) { return TransactionValidationResult.withError("the sender account doesn't exist"); } if (state.isDeleted()) { return TransactionValidationResult.withError("the sender account is deleted"); } return TransactionValidationResult.ok(); } @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); } | @Test public void validAccountState() { AccountState state = Mockito.mock(AccountState.class); Mockito.when(state.isDeleted()).thenReturn(false); TxValidatorAccountStateValidator tvasv = new TxValidatorAccountStateValidator(); Assert.assertTrue(tvasv.validate(null, state, null, null, Long.MAX_VALUE, false).transactionIsValid()); }
@Test public void invalidAccountState() { AccountState state = Mockito.mock(AccountState.class); Mockito.when(state.isDeleted()).thenReturn(true); TxValidatorAccountStateValidator tvasv = new TxValidatorAccountStateValidator(); Assert.assertFalse(tvasv.validate(null, state, null, null, Long.MAX_VALUE, false).transactionIsValid()); } |
TxValidatorNonceRangeValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { BigInteger nonce = tx.getNonceAsInteger(); BigInteger stateNonce = state == null ? BigInteger.ZERO : state.getNonce(); if (stateNonce.compareTo(nonce) > 0) { return TransactionValidationResult.withError("transaction nonce too low"); } if (stateNonce.add(accountSlots).compareTo(nonce) <= 0) { return TransactionValidationResult.withError("transaction nonce too high"); } return TransactionValidationResult.ok(); } TxValidatorNonceRangeValidator(int accountSlots); @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); } | @Test public void oneSlotRange() { Transaction tx1 = Mockito.mock(Transaction.class); Transaction tx2 = Mockito.mock(Transaction.class); Transaction tx3 = Mockito.mock(Transaction.class); AccountState as = Mockito.mock(AccountState.class); Mockito.when(tx1.getNonceAsInteger()).thenReturn(BigInteger.valueOf(0)); Mockito.when(tx2.getNonceAsInteger()).thenReturn(BigInteger.valueOf(1)); Mockito.when(tx3.getNonceAsInteger()).thenReturn(BigInteger.valueOf(2)); Mockito.when(as.getNonce()).thenReturn(BigInteger.valueOf(1)); TxValidatorNonceRangeValidator tvnrv = new TxValidatorNonceRangeValidator(1); Assert.assertFalse(tvnrv.validate(tx1, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvnrv.validate(tx2, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertFalse(tvnrv.validate(tx3, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); }
@Test public void fiveSlotsRange() { Transaction[] txs = new Transaction[7]; for (int i = 0; i < 7; i++) { txs[i] = Mockito.mock(Transaction.class); Mockito.when(txs[i].getNonceAsInteger()).thenReturn(BigInteger.valueOf(i)); } AccountState as = Mockito.mock(AccountState.class); Mockito.when(as.getNonce()).thenReturn(BigInteger.valueOf(1)); TxValidatorNonceRangeValidator tvnrv = new TxValidatorNonceRangeValidator(5); for (int i = 0; i < 7; i++) { Transaction tx = txs[i]; long txNonce = tx.getNonceAsInteger().longValue(); boolean isValid = tvnrv.validate(tx, as, null, null, Long.MAX_VALUE, false).transactionIsValid(); Assert.assertEquals(isValid, txNonce >= 1 && txNonce <= 5); } } |
TxValidatorAccountBalanceValidator implements TxValidatorStep { @Override public TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx) { if (isFreeTx) { return TransactionValidationResult.ok(); } if (state == null) { return TransactionValidationResult.withError("the sender account doesn't exist"); } BigInteger txGasLimit = tx.getGasLimitAsInteger(); Coin maximumPrice = tx.getGasPrice().multiply(txGasLimit); if (state.getBalance().compareTo(maximumPrice) >= 0) { return TransactionValidationResult.ok(); } return TransactionValidationResult.withError("insufficient funds"); } @Override TransactionValidationResult validate(Transaction tx, @Nullable AccountState state, BigInteger gasLimit, Coin minimumGasPrice, long bestBlockNumber, boolean isFreeTx); } | @Test public void validAccountBalance() { Transaction tx1 = Mockito.mock(Transaction.class); Transaction tx2 = Mockito.mock(Transaction.class); Transaction tx3 = Mockito.mock(Transaction.class); AccountState as = Mockito.mock(AccountState.class); Mockito.when(tx1.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(1)); Mockito.when(tx2.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(1)); Mockito.when(tx3.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(2)); Mockito.when(tx1.getGasPrice()).thenReturn(Coin.valueOf(1)); Mockito.when(tx2.getGasPrice()).thenReturn(Coin.valueOf(10000)); Mockito.when(tx3.getGasPrice()).thenReturn(Coin.valueOf(5000)); Mockito.when(as.getBalance()).thenReturn(Coin.valueOf(10000)); TxValidatorAccountBalanceValidator tvabv = new TxValidatorAccountBalanceValidator(); Assert.assertTrue(tvabv.validate(tx1, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvabv.validate(tx2, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertTrue(tvabv.validate(tx3, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); }
@Test public void invalidAccountBalance() { Transaction tx1 = Mockito.mock(Transaction.class); Transaction tx2 = Mockito.mock(Transaction.class); AccountState as = Mockito.mock(AccountState.class); Mockito.when(tx1.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(1)); Mockito.when(tx2.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(2)); Mockito.when(tx1.getGasPrice()).thenReturn(Coin.valueOf(20)); Mockito.when(tx2.getGasPrice()).thenReturn(Coin.valueOf(10)); Mockito.when(as.getBalance()).thenReturn(Coin.valueOf(19)); TxValidatorAccountBalanceValidator tvabv = new TxValidatorAccountBalanceValidator(); Assert.assertFalse(tvabv.validate(tx1, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); Assert.assertFalse(tvabv.validate(tx2, as, null, null, Long.MAX_VALUE, false).transactionIsValid()); }
@Test public void balanceIsNotValidatedIfFreeTx() { Transaction tx = new Transaction(BigInteger.ZERO.toByteArray(), BigInteger.ONE.toByteArray(), BigInteger.valueOf(21071).toByteArray(), new ECKey().getAddress(), BigInteger.ZERO.toByteArray(), Hex.decode("0001"), Constants.REGTEST_CHAIN_ID); tx.sign(new ECKey().getPrivKeyBytes()); TxValidatorAccountBalanceValidator tv = new TxValidatorAccountBalanceValidator(); Assert.assertTrue(tv.validate(tx, new AccountState(), BigInteger.ONE, Coin.valueOf(1L), Long.MAX_VALUE, true).transactionIsValid()); } |
TxsPerAccount { public List<Transaction> getTransactions(){ return txs; } List<Transaction> getTransactions(); void setTransactions(List<Transaction> txs); @VisibleForTesting BigInteger getNextNonce(); } | @Test public void containsNoTransactions() { TxsPerAccount txspa = new TxsPerAccount(); Assert.assertNotNull(txspa.getTransactions()); Assert.assertTrue(txspa.getTransactions().isEmpty()); } |
TxsPerAccount { @VisibleForTesting public BigInteger getNextNonce() { return this.nextNonce; } List<Transaction> getTransactions(); void setTransactions(List<Transaction> txs); @VisibleForTesting BigInteger getNextNonce(); } | @Test public void nextNonceIsNull() { TxsPerAccount txspa = new TxsPerAccount(); Assert.assertNull(txspa.getNextNonce()); } |
TxsPerAccount { boolean containsNonce(BigInteger nonce) { for (Transaction tx : txs) { if (new BigInteger(1, tx.getNonce()).equals(nonce)) { return true; } } return false; } List<Transaction> getTransactions(); void setTransactions(List<Transaction> txs); @VisibleForTesting BigInteger getNextNonce(); } | @Test public void doesNotCointainNonce() { TxsPerAccount txspa = new TxsPerAccount(); Assert.assertFalse(txspa.containsNonce(BigInteger.ONE)); }
@Test public void containsNonce() { TxsPerAccount txspa = new TxsPerAccount(); Transaction tx = buildTransaction(1); txspa.getTransactions().add(tx); Assert.assertTrue(txspa.containsNonce(BigInteger.ONE)); } |
StatusResolver { public Status currentStatus() { Status status; if (blockStore.getMinNumber() != 0) { status = new Status( genesis.getNumber(), genesis.getHash().getBytes(), genesis.getParentHash().getBytes(), genesis.getCumulativeDifficulty()); } else { Block block = blockStore.getBestBlock(); BlockDifficulty totalDifficulty = blockStore.getTotalDifficultyForHash(block.getHash().getBytes()); status = new Status(block.getNumber(), block.getHash().getBytes(), block.getParentHash().getBytes(), totalDifficulty); } return status; } StatusResolver(BlockStore blockStore, Genesis genesis); Status currentStatus(); } | @Test public void status() { Block bestBlock = mock(Block.class); Keccak256 blockHash = mock(Keccak256.class); byte[] hashBytes = new byte[]{0x00}; long blockNumber = 52; BlockDifficulty totalDifficulty = mock(BlockDifficulty.class); when(blockStore.getBestBlock()).thenReturn(bestBlock); when(bestBlock.getHash()).thenReturn(blockHash); when(bestBlock.getParentHash()).thenReturn(blockHash); when(blockHash.getBytes()).thenReturn(hashBytes); when(bestBlock.getNumber()).thenReturn(blockNumber); when(blockStore.getTotalDifficultyForHash(eq(hashBytes))).thenReturn(totalDifficulty); Status status = target.currentStatus(); Assert.assertEquals(blockNumber, status.getBestBlockNumber()); Assert.assertEquals(hashBytes, status.getBestBlockHash()); Assert.assertEquals(hashBytes, status.getBestBlockParentHash()); Assert.assertEquals(totalDifficulty, status.getTotalDifficulty()); }
@Test public void status_incompleteBlockchain() { when(blockStore.getMinNumber()).thenReturn(1L); Keccak256 genesisHash = new Keccak256("ee5c851e70650111887bb6c04e18ef4353391abe37846234c17895a9ca2b33d5"); Keccak256 parentHash = new Keccak256("133e83bb305ef21ea7fc86fcced355db2300887274961a136ca5e8c8763687d9"); when(genesis.getHash()).thenReturn(genesisHash); when(genesis.getParentHash()).thenReturn(parentHash); when(genesis.getNumber()).thenReturn(0L); BlockDifficulty genesisDifficulty = new BlockDifficulty(BigInteger.valueOf(10L)); when(genesis.getCumulativeDifficulty()).thenReturn(genesisDifficulty); Status status = target.currentStatus(); Assert.assertEquals(0L, status.getBestBlockNumber()); Assert.assertEquals(genesisHash.getBytes(), status.getBestBlockHash()); Assert.assertEquals(parentHash.getBytes(), status.getBestBlockParentHash()); Assert.assertEquals(genesisDifficulty, status.getTotalDifficulty()); } |
BlockProcessResult { @VisibleForTesting public static String buildLogMessage(String blockHash, Duration processingTime, Map<Keccak256, ImportResult> result) { StringBuilder sb = new StringBuilder("[MESSAGE PROCESS] Block[") .append(blockHash) .append("] After[") .append(FormatUtils.formatNanosecondsToSeconds(processingTime.toNanos())) .append("] seconds, process result."); if (result == null || result.isEmpty()) { sb.append(" No block connections were made"); } else { sb.append(" Connections attempts: ") .append(result.size()) .append(" | "); for (Map.Entry<Keccak256, ImportResult> entry : result.entrySet()) { sb.append(entry.getKey().toString()) .append(" - ") .append(entry.getValue()) .append(" | "); } } return sb.toString(); } BlockProcessResult(boolean additionalValidations, Map<Keccak256, ImportResult> result, String blockHash, Duration processingTime); boolean wasBlockAdded(Block block); static boolean importOk(ImportResult blockResult); boolean isBest(); boolean isInvalidBlock(); @VisibleForTesting static String buildLogMessage(String blockHash, Duration processingTime, Map<Keccak256, ImportResult> result); static final Duration LOG_TIME_LIMIT; } | @Test public void buildSimpleLogMessage() { String blockHash = "0x01020304"; Duration processingTime = Duration.ofNanos(123_000_000L); String result = BlockProcessResult.buildLogMessage(blockHash, processingTime, null); Assert.assertNotNull(result); Assert.assertEquals("[MESSAGE PROCESS] Block[0x01020304] After[0.123000] seconds, process result. No block connections were made", result); }
@Test public void buildLogMessageWithConnections() { String blockHash = "0x01020304"; Duration processingTime = Duration.ofNanos(123_000_000L); Map<Keccak256, ImportResult> connections = new HashMap<>(); Random random = new Random(); byte[] bytes = new byte[32]; random.nextBytes(bytes); Keccak256 hash = new Keccak256(bytes); connections.put(hash, ImportResult.IMPORTED_BEST); String result = BlockProcessResult.buildLogMessage(blockHash, processingTime, connections); Assert.assertNotNull(result); Assert.assertEquals("[MESSAGE PROCESS] Block[0x01020304] After[0.123000] seconds, process result. Connections attempts: 1 | " + hash.toHexString() + " - IMPORTED_BEST | ", result); } |
NodeMessageHandler implements MessageHandler, InternalService, Runnable { public synchronized void processMessage(final Peer sender, @Nonnull final Message message) { long start = System.nanoTime(); MessageType messageType = message.getMessageType(); logger.trace("Process message type: {}", messageType); MessageVisitor mv = new MessageVisitor(config, blockProcessor, syncProcessor, transactionGateway, peerScoringManager, channelManager, sender); message.accept(mv); long processTime = System.nanoTime() - start; String timeInSeconds = FormatUtils.formatNanosecondsToSeconds(processTime); if ((messageType == MessageType.BLOCK_MESSAGE || messageType == MessageType.BODY_RESPONSE_MESSAGE) && BlockUtils.tooMuchProcessTime(processTime)) { loggerMessageProcess.warn("Message[{}] processed after [{}] seconds.", message.getMessageType(), timeInSeconds); } else { loggerMessageProcess.debug("Message[{}] processed after [{}] seconds.", message.getMessageType(), timeInSeconds); } } NodeMessageHandler(RskSystemProperties config,
final BlockProcessor blockProcessor,
final SyncProcessor syncProcessor,
@Nullable final ChannelManager channelManager,
@Nullable final TransactionGateway transactionGateway,
@Nullable final PeerScoringManager peerScoringManager,
StatusResolver statusResolver); synchronized void processMessage(final Peer sender, @Nonnull final Message message); @Override void postMessage(Peer sender, Message message); @Override void start(); @Override void stop(); @Override long getMessageQueueSize(); @Override void run(); static final int MAX_NUMBER_OF_MESSAGES_CACHED; static final long RECEIVED_MESSAGES_CACHE_DURATION; } | @Test public void processBlockMessageUsingProcessor() { SimplePeer sender = new SimplePeer(); PeerScoringManager scoring = createPeerScoringManager(); SimpleBlockProcessor sbp = new SimpleBlockProcessor(); NodeMessageHandler processor = new NodeMessageHandler(config, sbp, null, null, null, scoring, mock(StatusResolver.class)); Block block = new BlockChainBuilder().ofSize(1, true).getBestBlock(); Message message = new BlockMessage(block); processor.processMessage(sender, message); Assert.assertNotNull(sbp.getBlocks()); Assert.assertEquals(1, sbp.getBlocks().size()); Assert.assertSame(block, sbp.getBlocks().get(0)); Assert.assertFalse(scoring.isEmpty()); PeerScoring pscoring = scoring.getPeerScoring(sender.getPeerNodeID()); Assert.assertNotNull(pscoring); Assert.assertFalse(pscoring.isEmpty()); Assert.assertEquals(1, pscoring.getTotalEventCounter()); Assert.assertEquals(1, pscoring.getEventCounter(EventType.VALID_BLOCK)); pscoring = scoring.getPeerScoring(sender.getAddress()); Assert.assertNotNull(pscoring); Assert.assertFalse(pscoring.isEmpty()); Assert.assertEquals(1, pscoring.getTotalEventCounter()); Assert.assertEquals(1, pscoring.getEventCounter(EventType.VALID_BLOCK)); }
@Test public void skipProcessGenesisBlock() throws UnknownHostException { SimplePeer sender = new SimplePeer(); PeerScoringManager scoring = createPeerScoringManager(); SimpleBlockProcessor sbp = new SimpleBlockProcessor(); NodeMessageHandler processor = new NodeMessageHandler(config, sbp, null, null, null, scoring, mock(StatusResolver.class)); Block block = new BlockGenerator().getGenesisBlock(); Message message = new BlockMessage(block); processor.processMessage(sender, message); Assert.assertNotNull(sbp.getBlocks()); Assert.assertEquals(0, sbp.getBlocks().size()); Assert.assertTrue(scoring.isEmpty()); PeerScoring pscoring = scoring.getPeerScoring(sender.getPeerNodeID()); Assert.assertNotNull(pscoring); Assert.assertTrue(pscoring.isEmpty()); }
@Test public void skipAdvancedBlock() throws UnknownHostException { SimplePeer sender = new SimplePeer(); PeerScoringManager scoring = createPeerScoringManager(); SimpleBlockProcessor sbp = new SimpleBlockProcessor(); sbp.setBlockGap(100000); NodeMessageHandler processor = new NodeMessageHandler(config, sbp, null, null, null, scoring, mock(StatusResolver.class)); Block block = new BlockGenerator().createBlock(200000, 0); Message message = new BlockMessage(block); processor.processMessage(sender, message); Assert.assertNotNull(sbp.getBlocks()); Assert.assertEquals(0, sbp.getBlocks().size()); Assert.assertTrue(scoring.isEmpty()); PeerScoring pscoring = scoring.getPeerScoring(sender.getPeerNodeID()); Assert.assertNotNull(pscoring); Assert.assertTrue(pscoring.isEmpty()); }
@Test public void processMissingPoWBlockMessageUsingProcessor() throws UnknownHostException { SimplePeer sender = new SimplePeer(); PeerScoringManager scoring = createPeerScoringManager(); SimpleBlockProcessor sbp = new SimpleBlockProcessor(); NodeMessageHandler processor = new NodeMessageHandler(config, sbp, null, null, null, scoring, mock(StatusResolver.class)); BlockGenerator blockGenerator = new BlockGenerator(); Block block = blockGenerator.getGenesisBlock(); for (int i = 0; i < 50; i++) { block = blockGenerator.createChildBlock(block); } Message message = new BlockMessage(block); processor.processMessage(sender, message); Assert.assertNotNull(sbp.getBlocks()); Assert.assertEquals(1, sbp.getBlocks().size()); Assert.assertFalse(scoring.isEmpty()); PeerScoring pscoring = scoring.getPeerScoring(sender.getPeerNodeID()); Assert.assertNotNull(pscoring); Assert.assertFalse(pscoring.isEmpty()); Assert.assertEquals(1, pscoring.getTotalEventCounter()); Assert.assertEquals(1, pscoring.getEventCounter(EventType.VALID_BLOCK)); Assert.assertEquals(0, pscoring.getEventCounter(EventType.INVALID_BLOCK)); }
@Test public void processFutureBlockMessageUsingProcessor() throws UnknownHostException { SimpleBlockProcessor sbp = new SimpleBlockProcessor(); NodeMessageHandler processor = new NodeMessageHandler(config, sbp, null, null, null, null, mock(StatusResolver.class)); Block block = new BlockGenerator().getGenesisBlock(); Message message = new BlockMessage(block); SimplePeer sender = new SimplePeer(); processor.processMessage(sender, message); Assert.assertNotNull(sbp.getBlocks()); Assert.assertEquals(0, sbp.getBlocks().size()); }
@Test @Ignore("This should be reviewed with sync processor or deleted") public void processStatusMessageUsingNodeBlockProcessor() throws UnknownHostException { final World world = new World(); final Blockchain blockchain = world.getBlockChain(); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor bp = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); final NodeMessageHandler handler = new NodeMessageHandler(config, bp, null, null, null, null, mock(StatusResolver.class)); BlockGenerator blockGenerator = new BlockGenerator(); final Block block = blockGenerator.createChildBlock(blockGenerator.getGenesisBlock()); final Status status = new Status(block.getNumber(), block.getHash().getBytes()); final Message message = new StatusMessage(status); handler.processMessage(sender, message); Assert.assertNotNull(sender.getGetBlockMessages()); Assert.assertEquals(1, sender.getGetBlockMessages().size()); final Message msg = sender.getGetBlockMessages().get(0); Assert.assertEquals(MessageType.GET_BLOCK_MESSAGE, msg.getMessageType()); final GetBlockMessage gbMessage = (GetBlockMessage) msg; Assert.assertArrayEquals(block.getHash().getBytes(), gbMessage.getBlockHash()); }
@Test() public void processStatusMessageUsingSyncProcessor() { final SimplePeer sender = new SimplePeer(); final ChannelManager channelManager = mock(ChannelManager.class); when(channelManager.getActivePeers()).thenReturn(Collections.singletonList(sender)); final NodeMessageHandler handler = NodeMessageHandlerUtil.createHandlerWithSyncProcessor(SyncConfiguration.IMMEDIATE_FOR_TESTING, channelManager); BlockGenerator blockGenerator = new BlockGenerator(); final Block block = blockGenerator.createChildBlock(blockGenerator.getGenesisBlock()); final Status status = new Status(block.getNumber(), block.getHash().getBytes(), block.getParentHash().getBytes(), new BlockDifficulty(BigInteger.TEN)); final Message message = new StatusMessage(status); handler.processMessage(sender, message); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(MessageType.BLOCK_HEADERS_REQUEST_MESSAGE, sender.getMessages().get(0).getMessageType()); }
@Test public void processStatusMessageWithKnownBestBlock() { final World world = new World(); final Blockchain blockchain = world.getBlockChain(); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor bp = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final SimplePeer sender = new SimplePeer(); final SyncProcessor syncProcessor = new SyncProcessor( blockchain, mock(BlockStore.class), mock(ConsensusValidationMainchainView.class), blockSyncService, syncConfiguration, blockFactory, new DummyBlockValidationRule(), new SyncBlockValidatorRule(new BlockUnclesHashValidationRule(), new BlockRootValidationRule(config.getActivationConfig())), null, new PeersInformation(RskMockFactory.getChannelManager(), syncConfiguration, blockchain, RskMockFactory.getPeerScoringManager()), mock(Genesis.class)); final NodeMessageHandler handler = new NodeMessageHandler(config, bp, syncProcessor, null, null, null, mock(StatusResolver.class)); BlockGenerator blockGenerator = new BlockGenerator(); final Block block = blockGenerator.createChildBlock(blockGenerator.getGenesisBlock()); final Status status = new Status(block.getNumber(), block.getHash().getBytes(), block.getParentHash().getBytes(), blockchain.getTotalDifficulty()); final Message message = new StatusMessage(status); store.saveBlock(block); handler.processMessage(sender, message); Assert.assertNotNull(sender.getMessages()); }
@Test public void processGetBlockMessageUsingBlockInStore() throws UnknownHostException { final Block block = new BlockGenerator().getBlock(3); final World world = new World(); final Blockchain blockchain = world.getBlockChain(); final NetBlockStore store = new NetBlockStore(); store.saveBlock(block); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor bp = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final NodeMessageHandler handler = new NodeMessageHandler(config, bp, null, null, null, null, mock(StatusResolver.class)); final SimplePeer sender = new SimplePeer(); handler.processMessage(sender, new GetBlockMessage(block.getHash().getBytes())); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_MESSAGE, message.getMessageType()); final BlockMessage bMessage = (BlockMessage) message; Assert.assertEquals(block.getHash(), bMessage.getBlock().getHash()); }
@Test public void processGetBlockMessageUsingBlockInBlockchain() throws UnknownHostException { final World world = new World(); final Blockchain blockchain = world.getBlockChain(); final NetBlockStore store = new NetBlockStore(); List<Block> blocks = new BlockGenerator().getBlockChain(blockchain.getBestBlock(), 10); for (Block b: blocks) blockchain.tryToConnect(b); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); NodeBlockProcessor bp = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); NodeMessageHandler handler = new NodeMessageHandler(config, bp, null, null, null, null, mock(StatusResolver.class)); SimplePeer sender = new SimplePeer(); handler.processMessage(sender, new GetBlockMessage(blocks.get(4).getHash().getBytes())); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_MESSAGE, message.getMessageType()); BlockMessage bmessage = (BlockMessage) message; Assert.assertEquals(blocks.get(4).getHash(), bmessage.getBlock().getHash()); }
@Test public void processGetBlockMessageUsingEmptyStore() throws UnknownHostException { final Block block = new BlockGenerator().getBlock(3); final World world = new World(); final Blockchain blockchain = world.getBlockChain(); final NetBlockStore store = new NetBlockStore(); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor bp = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final NodeMessageHandler handler = new NodeMessageHandler(config, bp, null, null, null, null, mock(StatusResolver.class)); final SimplePeer sender = new SimplePeer(); handler.processMessage(sender, new GetBlockMessage(block.getHash().getBytes())); Assert.assertTrue(sender.getMessages().isEmpty()); }
@Test public void processBlockHeaderRequestMessageUsingBlockInStore() throws UnknownHostException { final Block block = new BlockGenerator().getBlock(3); final World world = new World(); final Blockchain blockchain = world.getBlockChain(); final NetBlockStore store = new NetBlockStore(); store.saveBlock(block); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor bp = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final NodeMessageHandler handler = new NodeMessageHandler(config, bp, null, null, null, null, mock(StatusResolver.class)); final SimplePeer sender = new SimplePeer(); handler.processMessage(sender, new BlockHeadersRequestMessage(1,block.getHash().getBytes(), 1)); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); final Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_HEADERS_RESPONSE_MESSAGE, message.getMessageType()); final BlockHeadersResponseMessage bMessage = (BlockHeadersResponseMessage) message; Assert.assertEquals(block.getHash(), bMessage.getBlockHeaders().get(0).getHash()); }
@Test public void processBlockHeaderRequestMessageUsingBlockInBlockchain() throws UnknownHostException { final World world = new World(); final Blockchain blockchain = world.getBlockChain(); final NetBlockStore store = new NetBlockStore(); List<Block> blocks = new BlockGenerator().getBlockChain(blockchain.getBestBlock(), 10); for (Block b: blocks) blockchain.tryToConnect(b); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); NodeBlockProcessor bp = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); NodeMessageHandler handler = new NodeMessageHandler(config, bp, null, null, null, null, mock(StatusResolver.class)); SimplePeer sender = new SimplePeer(); handler.processMessage(sender, new BlockHeadersRequestMessage(1, blocks.get(4).getHash().getBytes(), 1)); Assert.assertFalse(sender.getMessages().isEmpty()); Assert.assertEquals(1, sender.getMessages().size()); Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_HEADERS_RESPONSE_MESSAGE, message.getMessageType()); BlockHeadersResponseMessage bMessage = (BlockHeadersResponseMessage) message; Assert.assertEquals(blocks.get(4).getHash(), bMessage.getBlockHeaders().get(0).getHash()); }
@Test public void processNewBlockHashesMessage() throws UnknownHostException { final World world = new World(); final Blockchain blockchain = world.getBlockChain(); final NetBlockStore store = new NetBlockStore(); final List<Block> blocks = new BlockGenerator().getBlockChain(blockchain.getBestBlock(), 15); final List<Block> bcBlocks = blocks.subList(0, 10); for (Block b: bcBlocks) blockchain.tryToConnect(b); BlockNodeInformation nodeInformation = new BlockNodeInformation(); SyncConfiguration syncConfiguration = SyncConfiguration.IMMEDIATE_FOR_TESTING; BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, syncConfiguration); final NodeBlockProcessor bp = new NodeBlockProcessor(store, blockchain, nodeInformation, blockSyncService, syncConfiguration); final NodeMessageHandler handler = new NodeMessageHandler(config, bp, null, null, null, null, mock(StatusResolver.class)); class TestCase { protected final NewBlockHashesMessage message; protected final List<Block> expected; public TestCase(@Nonnull final NewBlockHashesMessage message, final List<Block> expected) { this.message = message; this.expected = expected; } } TestCase[] testCases = { new TestCase( new NewBlockHashesMessage(new LinkedList<>()), null ), new TestCase( new NewBlockHashesMessage( Arrays.asList( new BlockIdentifier(blocks.get(5).getHash().getBytes(), blocks.get(5).getNumber()) ) ), null ), new TestCase( new NewBlockHashesMessage( Arrays.asList( new BlockIdentifier(blocks.get(11).getHash().getBytes(), blocks.get(5).getNumber()) ) ), Arrays.asList(blocks.get(11)) ), new TestCase( new NewBlockHashesMessage( Arrays.asList( new BlockIdentifier(blocks.get(11).getHash().getBytes(), blocks.get(5).getNumber()), new BlockIdentifier(blocks.get(5).getHash().getBytes(), blocks.get(5).getNumber()) ) ), Arrays.asList(blocks.get(11)) ), new TestCase( new NewBlockHashesMessage( Arrays.asList( new BlockIdentifier(blocks.get(11).getHash().getBytes(), blocks.get(5).getNumber()), new BlockIdentifier(blocks.get(12).getHash().getBytes(), blocks.get(5).getNumber()) ) ), Arrays.asList(blocks.get(11), blocks.get(12)) ), new TestCase( new NewBlockHashesMessage( Arrays.asList( new BlockIdentifier(blocks.get(11).getHash().getBytes(), blocks.get(5).getNumber()), new BlockIdentifier(blocks.get(11).getHash().getBytes(), blocks.get(5).getNumber()) ) ), Arrays.asList(blocks.get(11)) ) }; for (int i = 0; i < testCases.length; i += 1) { final TestCase testCase = testCases[i]; final SimplePeer sender = new SimplePeer(); handler.processMessage(sender, testCase.message); if (testCase.expected == null) { Assert.assertTrue(sender.getMessages().isEmpty()); continue; } Assert.assertEquals(testCase.expected.size(), sender.getMessages().size()); Assert.assertTrue(sender.getMessages().stream().allMatch(m -> m.getMessageType() == MessageType.GET_BLOCK_MESSAGE)); List<Keccak256> msgs = sender.getMessages().stream() .map(m -> (GetBlockMessage) m) .map(m -> m.getBlockHash()) .map(h -> new Keccak256(h)) .collect(Collectors.toList()); Set<Keccak256> expected = testCase.expected.stream() .map(b -> b.getHash().getBytes()) .map(h -> new Keccak256(h)) .collect(Collectors.toSet()); for (Keccak256 h : msgs) { Assert.assertTrue(expected.contains(h)); } for (Keccak256 h : expected) { Assert.assertTrue( msgs.stream() .filter(h1 -> h.equals(h1)) .count() == 1 ); } } }
@Test public void processNewBlockHashesMessageDoesNothingBecauseNodeIsSyncing() { BlockProcessor blockProcessor = mock(BlockProcessor.class); Mockito.when(blockProcessor.hasBetterBlockToSync()).thenReturn(true); final NodeMessageHandler handler = new NodeMessageHandler(config, blockProcessor, null, null, null, null, mock(StatusResolver.class)); Message message = mock(Message.class); Mockito.when(message.getMessageType()).thenReturn(MessageType.NEW_BLOCK_HASHES); handler.processMessage(null, message); verify(blockProcessor, never()).processNewBlockHashesMessage(any(), any()); }
@Test public void processTransactionsMessage() throws UnknownHostException { PeerScoringManager scoring = createPeerScoringManager(); TransactionGateway transactionGateway = mock(TransactionGateway.class); BlockProcessor blockProcessor = mock(BlockProcessor.class); Mockito.when(blockProcessor.hasBetterBlockToSync()).thenReturn(false); final NodeMessageHandler handler = new NodeMessageHandler(config, blockProcessor, null, null, transactionGateway, scoring, mock(StatusResolver.class)); final SimplePeer sender = new SimplePeer(new NodeID(new byte[] {1})); final SimplePeer sender2 = new SimplePeer(new NodeID(new byte[] {2})); final List<Transaction> txs = TransactionUtils.getTransactions(10); final TransactionsMessage message = new TransactionsMessage(txs); handler.processMessage(sender, message); Mockito.verify(transactionGateway, times(1)).receiveTransactionsFrom(txs, Collections.singleton(sender.getPeerNodeID())); handler.processMessage(sender2, message); Mockito.verify(transactionGateway, times(1)).receiveTransactionsFrom(txs, Collections.singleton(sender2.getPeerNodeID())); Assert.assertFalse(scoring.isEmpty()); PeerScoring pscoring = scoring.getPeerScoring(sender.getPeerNodeID()); Assert.assertNotNull(pscoring); Assert.assertFalse(pscoring.isEmpty()); Assert.assertEquals(10, pscoring.getTotalEventCounter()); Assert.assertEquals(10, pscoring.getEventCounter(EventType.VALID_TRANSACTION)); pscoring = scoring.getPeerScoring(sender2.getPeerNodeID()); Assert.assertNotNull(pscoring); Assert.assertFalse(pscoring.isEmpty()); Assert.assertEquals(10, pscoring.getTotalEventCounter()); Assert.assertEquals(10, pscoring.getEventCounter(EventType.VALID_TRANSACTION)); }
@Test public void processRejectedTransactionsMessage() throws UnknownHostException { PeerScoringManager scoring = createPeerScoringManager(); final SimpleChannelManager channelManager = new SimpleChannelManager(); TransactionGateway transactionGateway = mock(TransactionGateway.class); BlockProcessor blockProcessor = mock(BlockProcessor.class); Mockito.when(blockProcessor.hasBetterBlockToSync()).thenReturn(false); final NodeMessageHandler handler = new NodeMessageHandler(config, blockProcessor, null, channelManager, transactionGateway, scoring, mock(StatusResolver.class)); final SimplePeer sender = new SimplePeer(); final List<Transaction> txs = TransactionUtils.getTransactions(0); final TransactionsMessage message = new TransactionsMessage(txs); handler.processMessage(sender, message); Assert.assertNotNull(channelManager.getTransactions()); Assert.assertEquals(0, channelManager.getTransactions().size()); Assert.assertTrue(scoring.isEmpty()); PeerScoring pscoring = scoring.getPeerScoring(sender.getPeerNodeID()); Assert.assertNotNull(pscoring); Assert.assertTrue(pscoring.isEmpty()); Assert.assertEquals(0, pscoring.getTotalEventCounter()); Assert.assertEquals(0, pscoring.getEventCounter(EventType.INVALID_TRANSACTION)); }
@Test public void processTooMuchGasTransactionMessage() throws UnknownHostException { PeerScoringManager scoring = createPeerScoringManager(); final SimpleChannelManager channelManager = new SimpleChannelManager(); TransactionGateway transactionGateway = mock(TransactionGateway.class); BlockProcessor blockProcessor = mock(BlockProcessor.class); Mockito.when(blockProcessor.hasBetterBlockToSync()).thenReturn(false); final NodeMessageHandler handler = new NodeMessageHandler(config, blockProcessor, null, channelManager, transactionGateway, scoring, mock(StatusResolver.class)); final SimplePeer sender = new SimplePeer(); final List<Transaction> txs = new ArrayList<>(); BigInteger value = BigInteger.ONE; BigInteger nonce = BigInteger.ZERO; BigInteger gasPrice = BigInteger.ONE; BigInteger gasLimit = BigDecimal.valueOf(Math.pow(2, 60)).add(BigDecimal.ONE).toBigInteger(); txs.add(TransactionUtils.createTransaction(TransactionUtils.getPrivateKeyBytes(), TransactionUtils.getAddress(), value, nonce, gasPrice, gasLimit)); final TransactionsMessage message = new TransactionsMessage(txs); handler.processMessage(sender, message); Assert.assertNotNull(channelManager.getTransactions()); Assert.assertEquals(0, channelManager.getTransactions().size()); Assert.assertFalse(scoring.isEmpty()); PeerScoring pscoring = scoring.getPeerScoring(sender.getPeerNodeID()); Assert.assertNotNull(pscoring); Assert.assertFalse(pscoring.isEmpty()); Assert.assertEquals(1, pscoring.getTotalEventCounter()); Assert.assertEquals(1, pscoring.getEventCounter(EventType.VALID_TRANSACTION)); }
@Test public void processTransactionsMessageUsingTransactionPool() throws UnknownHostException { TransactionGateway transactionGateway = mock(TransactionGateway.class); BlockProcessor blockProcessor = mock(BlockProcessor.class); Mockito.when(blockProcessor.hasBetterBlockToSync()).thenReturn(false); final NodeMessageHandler handler = new NodeMessageHandler(config, blockProcessor, null, null, transactionGateway, RskMockFactory.getPeerScoringManager(), mock(StatusResolver.class)); final SimplePeer sender = new SimplePeer(new NodeID(new byte[] {1})); final SimplePeer sender2 = new SimplePeer(new NodeID(new byte[] {2})); final List<Transaction> txs = TransactionUtils.getTransactions(10); final TransactionsMessage message = new TransactionsMessage(txs); handler.processMessage(sender, message); Mockito.verify(transactionGateway, times(1)).receiveTransactionsFrom(txs, Collections.singleton(sender.getPeerNodeID())); handler.processMessage(sender2, message); Mockito.verify(transactionGateway, times(1)).receiveTransactionsFrom(txs, Collections.singleton(sender2.getPeerNodeID())); }
@Test public void processBlockByHashRequestMessageUsingProcessor() throws UnknownHostException { SimpleBlockProcessor sbp = new SimpleBlockProcessor(); NodeMessageHandler processor = new NodeMessageHandler(config, sbp, null, null, null, null, mock(StatusResolver.class)); Block block = new BlockChainBuilder().ofSize(1, true).getBestBlock(); Message message = new BlockRequestMessage(100, block.getHash().getBytes()); processor.processMessage(new SimplePeer(), message); Assert.assertEquals(100, sbp.getRequestId()); Assert.assertArrayEquals(block.getHash().getBytes(), sbp.getHash()); }
@Test public void processBlockHeadersRequestMessageUsingProcessor() throws UnknownHostException { byte[] hash = HashUtil.randomHash(); SimpleBlockProcessor sbp = new SimpleBlockProcessor(); NodeMessageHandler processor = new NodeMessageHandler(config, sbp, null, null, null, null, mock(StatusResolver.class)); Message message = new BlockHeadersRequestMessage(100, hash, 50); processor.processMessage(new SimplePeer(), message); Assert.assertEquals(100, sbp.getRequestId()); Assert.assertArrayEquals(hash, sbp.getHash()); } |
ECKey { public byte[] getAddress() { if (pubKeyHash == null) { byte[] pubBytes = this.pub.getEncoded(false); pubKeyHash = HashUtil.keccak256Omit12(Arrays.copyOfRange(pubBytes, 1, pubBytes.length)); } return pubKeyHash; } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; } | @Test public void testGetAddress() { ECKey key = ECKey.fromPublicOnly(pubKey); assertArrayEquals(Hex.decode(address), key.getAddress()); } |
NodeMessageHandler implements MessageHandler, InternalService, Runnable { @Override public void postMessage(Peer sender, Message message) { logger.trace("Start post message (queue size {}) (message type {})", this.queue.size(), message.getMessageType()); cleanExpiredMessages(); tryAddMessage(sender, message); logger.trace("End post message (queue size {})", this.queue.size()); } NodeMessageHandler(RskSystemProperties config,
final BlockProcessor blockProcessor,
final SyncProcessor syncProcessor,
@Nullable final ChannelManager channelManager,
@Nullable final TransactionGateway transactionGateway,
@Nullable final PeerScoringManager peerScoringManager,
StatusResolver statusResolver); synchronized void processMessage(final Peer sender, @Nonnull final Message message); @Override void postMessage(Peer sender, Message message); @Override void start(); @Override void stop(); @Override long getMessageQueueSize(); @Override void run(); static final int MAX_NUMBER_OF_MESSAGES_CACHED; static final long RECEIVED_MESSAGES_CACHE_DURATION; } | @Test public void postBlockMessageTwice() throws InterruptedException, UnknownHostException { Peer sender = new SimplePeer(); PeerScoringManager scoring = createPeerScoringManager(); SimpleBlockProcessor sbp = new SimpleBlockProcessor(); NodeMessageHandler processor = new NodeMessageHandler(config, sbp, null, null, null, scoring, mock(StatusResolver.class)); Block block = new BlockChainBuilder().ofSize(1, true).getBestBlock(); Message message = new BlockMessage(block); processor.postMessage(sender, message); processor.postMessage(sender, message); PeerScoring pscoring = scoring.getPeerScoring(sender.getPeerNodeID()); Assert.assertNotNull(pscoring); Assert.assertFalse(pscoring.isEmpty()); Assert.assertEquals(1, pscoring.getTotalEventCounter()); Assert.assertEquals(1, pscoring.getEventCounter(EventType.REPEATED_MESSAGE)); } |
ECKey { public String toString() { StringBuilder b = new StringBuilder(); b.append("pub:").append(ByteUtil.toHexString(pub.getEncoded(false))); return b.toString(); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; } | @Test public void testToString() { ECKey key = ECKey.fromPrivate(BigInteger.TEN); assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7", key.toString()); } |
DecidingSyncState extends BaseSyncState { @Override public void newPeerStatus() { if (peersInformation.count() >= syncConfiguration.getExpectedPeers()) { tryStartSyncing(); } } DecidingSyncState(SyncConfiguration syncConfiguration,
SyncEventsHandler syncEventsHandler,
PeersInformation peersInformation,
BlockStore blockStore); @Override void newPeerStatus(); @Override void tick(Duration duration); } | @Test public void startsSyncingWith5Peers() { SyncConfiguration syncConfiguration = SyncConfiguration.DEFAULT; SimpleSyncEventsHandler syncEventsHandler = new SimpleSyncEventsHandler(); PeersInformation peersInformation = mock(PeersInformation.class); when(peersInformation.count()).thenReturn(1,2,3,4,5); BlockStore blockStore = mock(BlockStore.class); Block bestBlock = mock(Block.class); when(blockStore.getBestBlock()).thenReturn(bestBlock); when(bestBlock.getNumber()).thenReturn(100L); SyncState syncState = new DecidingSyncState(syncConfiguration, syncEventsHandler, peersInformation, blockStore); when(peersInformation.getBestPeer()).thenReturn(Optional.of(mock(Peer.class))); Status status = mock(Status.class); SyncPeerStatus bpStatus = mock(SyncPeerStatus.class); when(bpStatus.getStatus()).thenReturn(status); when(peersInformation.getPeer(any())).thenReturn(bpStatus); for (int i = 0; i < 5; i++) { Assert.assertFalse(syncEventsHandler.startSyncingWasCalled()); syncState.newPeerStatus(); } Assert.assertTrue(syncEventsHandler.startSyncingWasCalled()); }
@Test public void backwardsSynchronization() { SyncConfiguration syncConfiguration = SyncConfiguration.DEFAULT; PeersInformation peersInformation = mock(PeersInformation.class); SyncEventsHandler syncEventsHandler = mock(SyncEventsHandler.class); BlockStore blockStore = mock(BlockStore.class); SyncState syncState = new DecidingSyncState(syncConfiguration, syncEventsHandler, peersInformation, blockStore); when(peersInformation.count()).thenReturn(syncConfiguration.getExpectedPeers() + 1); Peer peer = mock(Peer.class); when(peersInformation.getBestPeer()).thenReturn(Optional.of(peer)); SyncPeerStatus syncPeerStatus = mock(SyncPeerStatus.class); Status status = mock(Status.class); when(syncPeerStatus.getStatus()).thenReturn(status); when(peersInformation.getPeer(peer)).thenReturn(syncPeerStatus); when(blockStore.getMinNumber()).thenReturn(1L); Block block = mock(Block.class); long myBestBlockNumber = 90L; when(block.getNumber()).thenReturn(myBestBlockNumber); when(blockStore.getBestBlock()).thenReturn(block); when(status.getBestBlockNumber()).thenReturn(myBestBlockNumber + syncConfiguration.getLongSyncLimit()); syncState.newPeerStatus(); verify(syncEventsHandler).backwardSyncing(peer); }
@Test public void forwardsSynchronization_genesisIsConnected() { SyncConfiguration syncConfiguration = SyncConfiguration.DEFAULT; PeersInformation peersInformation = mock(PeersInformation.class); SyncEventsHandler syncEventsHandler = mock(SyncEventsHandler.class); BlockStore blockStore = mock(BlockStore.class); SyncState syncState = new DecidingSyncState(syncConfiguration, syncEventsHandler, peersInformation, blockStore); when(peersInformation.count()).thenReturn(syncConfiguration.getExpectedPeers() + 1); Peer peer = mock(Peer.class); when(peersInformation.getBestPeer()).thenReturn(Optional.of(peer)); SyncPeerStatus syncPeerStatus = mock(SyncPeerStatus.class); Status status = mock(Status.class); when(syncPeerStatus.getStatus()).thenReturn(status); when(peersInformation.getPeer(peer)).thenReturn(syncPeerStatus); when(blockStore.getMinNumber()).thenReturn(0L); Block block = mock(Block.class); long myBestBlockNumber = 90L; when(block.getNumber()).thenReturn(myBestBlockNumber); when(blockStore.getBestBlock()).thenReturn(block); when(status.getBestBlockNumber()).thenReturn(myBestBlockNumber + 1); syncState.newPeerStatus(); verify(syncEventsHandler).startSyncing(peer); }
@Test public void forwardsSynchronization() { SyncConfiguration syncConfiguration = SyncConfiguration.DEFAULT; PeersInformation peersInformation = mock(PeersInformation.class); SyncEventsHandler syncEventsHandler = mock(SyncEventsHandler.class); BlockStore blockStore = mock(BlockStore.class); SyncState syncState = new DecidingSyncState(syncConfiguration, syncEventsHandler, peersInformation, blockStore); when(peersInformation.count()).thenReturn(syncConfiguration.getExpectedPeers() + 1); Peer peer = mock(Peer.class); when(peersInformation.getBestPeer()).thenReturn(Optional.of(peer)); SyncPeerStatus syncPeerStatus = mock(SyncPeerStatus.class); Status status = mock(Status.class); when(syncPeerStatus.getStatus()).thenReturn(status); when(peersInformation.getPeer(peer)).thenReturn(syncPeerStatus); Block block = mock(Block.class); long myBestBlockNumber = 90L; when(block.getNumber()).thenReturn(myBestBlockNumber); when(blockStore.getBestBlock()).thenReturn(block); when(blockStore.getMinNumber()).thenReturn(1L); when(status.getBestBlockNumber()) .thenReturn(myBestBlockNumber + 1 + syncConfiguration.getLongSyncLimit()); syncState.newPeerStatus(); verify(syncEventsHandler).startSyncing(peer); } |
ECKey { public boolean isPubKeyCanonical() { return isPubKeyCanonical(pub.getEncoded(false)); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; } | @Test public void testIsPubKeyCanonicalCorect() { byte[] canonicalPubkey1 = new byte[65]; canonicalPubkey1[0] = 0x04; assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey1)); byte[] canonicalPubkey2 = new byte[33]; canonicalPubkey2[0] = 0x02; assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey2)); byte[] canonicalPubkey3 = new byte[33]; canonicalPubkey3[0] = 0x03; assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey3)); }
@Test public void testIsPubKeyCanonicalWrongLength() { byte[] nonCanonicalPubkey1 = new byte[64]; nonCanonicalPubkey1[0] = 0x04; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey1)); byte[] nonCanonicalPubkey2 = new byte[32]; nonCanonicalPubkey2[0] = 0x02; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey2)); byte[] nonCanonicalPubkey3 = new byte[32]; nonCanonicalPubkey3[0] = 0x03; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey3)); }
@Test public void testIsPubKeyCanonicalWrongPrefix() { byte[] nonCanonicalPubkey4 = new byte[65]; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey4)); byte[] nonCanonicalPubkey5 = new byte[33]; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey5)); byte[] nonCanonicalPubkey6 = new byte[33]; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey6)); } |
DecidingSyncState extends BaseSyncState { @Override public void tick(Duration duration) { peersInformation.cleanExpired(); timeElapsed = timeElapsed.plus(duration); if (peersInformation.count() > 0 && timeElapsed.compareTo(syncConfiguration.getTimeoutWaitingPeers()) >= 0) { tryStartSyncing(); } } DecidingSyncState(SyncConfiguration syncConfiguration,
SyncEventsHandler syncEventsHandler,
PeersInformation peersInformation,
BlockStore blockStore); @Override void newPeerStatus(); @Override void tick(Duration duration); } | @Test public void doesntStartSyncingWithNoPeersAfter2Minutes() { SyncConfiguration syncConfiguration = SyncConfiguration.DEFAULT; SimpleSyncEventsHandler syncEventsHandler = new SimpleSyncEventsHandler(); PeersInformation knownPeers = mock(PeersInformation.class); when(knownPeers.count()).thenReturn(0); when(knownPeers.getBestPeer()).thenReturn(Optional.empty()); SyncState syncState = new DecidingSyncState(syncConfiguration, syncEventsHandler, knownPeers, mock(BlockStore.class)); syncState.tick(Duration.ofMinutes(2)); Assert.assertFalse(syncEventsHandler.startSyncingWasCalled()); }
@Test public void startsSyncingWith1PeerAfter2Minutes() { SyncConfiguration syncConfiguration = SyncConfiguration.DEFAULT; SyncEventsHandler syncEventsHandler = mock(SyncEventsHandler.class); PeersInformation peersInformation = mock(PeersInformation.class); when(peersInformation.count()).thenReturn(1); when(peersInformation.getBestPeer()).thenReturn(Optional.of(mock(Peer.class))); Status status = mock(Status.class); SyncPeerStatus bpStatus = mock(SyncPeerStatus.class); when(bpStatus.getStatus()).thenReturn(status); when(peersInformation.getPeer(any())).thenReturn(bpStatus); BlockStore blockStore = mock(BlockStore.class); Block bestBlock = mock(Block.class); when(blockStore.getBestBlock()).thenReturn(bestBlock); when(bestBlock.getNumber()).thenReturn(100L); SyncState syncState = new DecidingSyncState( syncConfiguration, syncEventsHandler, peersInformation, blockStore); verify(syncEventsHandler, never()).startSyncing(any()); syncState.tick(Duration.ofMinutes(2)); verify(syncEventsHandler).startSyncing(any()); } |
DownloadingBackwardsBodiesSyncState extends BaseSyncState { @Override public void onEnter() { if (child.getNumber() == 1L) { connectGenesis(child); blockStore.flush(); syncEventsHandler.stopSyncing(); return; } if (toRequest.isEmpty()) { syncEventsHandler.stopSyncing(); return; } while (!toRequest.isEmpty() && inTransit.size() < syncConfiguration.getMaxRequestedBodies()) { BlockHeader headerToRequest = toRequest.remove(); requestBodies(headerToRequest); } } DownloadingBackwardsBodiesSyncState(
SyncConfiguration syncConfiguration,
SyncEventsHandler syncEventsHandler,
PeersInformation peersInformation,
Genesis genesis,
BlockFactory blockFactory,
BlockStore blockStore,
Block child,
List<BlockHeader> toRequest,
Peer peer); @Override void newBody(BodyResponseMessage body, Peer peer); @Override void onEnter(); } | @Test(expected = IllegalStateException.class) public void onEnter_connectGenesis_genesisIsNotChildsParent() { List<BlockHeader> toRequest = new LinkedList<>(); DownloadingBackwardsBodiesSyncState target = new DownloadingBackwardsBodiesSyncState( syncConfiguration, syncEventsHandler, peersInformation, genesis, blockFactory, blockStore, child, toRequest, peer); when(child.getNumber()).thenReturn(1L); when(genesis.isParentOf(child)).thenReturn(false); target.onEnter(); }
@Test(expected = IllegalStateException.class) public void onEnter_connectGenesis_difficultyDoesNotMatch() { List<BlockHeader> toRequest = new LinkedList<>(); DownloadingBackwardsBodiesSyncState target = new DownloadingBackwardsBodiesSyncState( syncConfiguration, syncEventsHandler, peersInformation, genesis, blockFactory, blockStore, child, toRequest, peer); Keccak256 childHash = new Keccak256(new byte[32]); when(child.getHash()).thenReturn(childHash); when(child.getNumber()).thenReturn(1L); when(genesis.isParentOf(child)).thenReturn(true); when(child.getCumulativeDifficulty()).thenReturn(new BlockDifficulty(BigInteger.valueOf(50))); when(genesis.getCumulativeDifficulty()).thenReturn(new BlockDifficulty(BigInteger.valueOf(50))); when(blockStore.getTotalDifficultyForHash(eq(childHash.getBytes()))) .thenReturn(new BlockDifficulty(BigInteger.valueOf(101))); target.onEnter(); }
@Test public void onEnter_connectGenesis() { List<BlockHeader> toRequest = new LinkedList<>(); DownloadingBackwardsBodiesSyncState target = new DownloadingBackwardsBodiesSyncState( syncConfiguration, syncEventsHandler, peersInformation, genesis, blockFactory, blockStore, child, toRequest, peer); Keccak256 childHash = new Keccak256(new byte[32]); when(child.getHash()).thenReturn(childHash); when(child.getNumber()).thenReturn(1L); when(genesis.isParentOf(child)).thenReturn(true); when(child.getCumulativeDifficulty()).thenReturn(new BlockDifficulty(BigInteger.valueOf(50))); BlockDifficulty cumulativeDifficulty = new BlockDifficulty(BigInteger.valueOf(50)); when(genesis.getCumulativeDifficulty()).thenReturn(cumulativeDifficulty); when(blockStore.getTotalDifficultyForHash(eq(childHash.getBytes()))) .thenReturn(new BlockDifficulty(BigInteger.valueOf(100))); target.onEnter(); verify(blockStore).saveBlock(eq(genesis), eq(cumulativeDifficulty), eq(true)); verify(blockStore).flush(); verify(syncEventsHandler).stopSyncing(); } |
DownloadingBackwardsHeadersSyncState extends BaseSyncState { @Override public void onEnter() { Keccak256 hashToRequest = child.getHash(); ChunkDescriptor chunkDescriptor = new ChunkDescriptor( hashToRequest.getBytes(), syncConfiguration.getChunkSize()); syncEventsHandler.sendBlockHeadersRequest(selectedPeer, chunkDescriptor); } DownloadingBackwardsHeadersSyncState(
SyncConfiguration syncConfiguration,
SyncEventsHandler syncEventsHandler,
BlockStore blockStore,
Peer peer); @Override void newBlockHeaders(List<BlockHeader> toRequest); @Override void onEnter(); } | @Test public void onEnter() { when(blockStore.getMinNumber()).thenReturn(50L); Block child = mock(Block.class); Keccak256 hash = new Keccak256(new byte[32]); when(child.getHash()).thenReturn(hash); when(blockStore.getChainBlockByNumber(50L)).thenReturn(child); DownloadingBackwardsHeadersSyncState target = new DownloadingBackwardsHeadersSyncState( syncConfiguration, syncEventsHandler, blockStore, selectedPeer); ArgumentCaptor<ChunkDescriptor> descriptorCaptor = ArgumentCaptor.forClass(ChunkDescriptor.class); target.onEnter(); verify(syncEventsHandler).sendBlockHeadersRequest(eq(selectedPeer), descriptorCaptor.capture()); verify(syncEventsHandler, never()).onSyncIssue(any(), any()); assertEquals(descriptorCaptor.getValue().getHash(), hash.getBytes()); assertEquals(descriptorCaptor.getValue().getCount(), syncConfiguration.getChunkSize()); } |
DownloadingBackwardsHeadersSyncState extends BaseSyncState { @Override public void newBlockHeaders(List<BlockHeader> toRequest) { syncEventsHandler.backwardDownloadBodies( child, toRequest.stream().skip(1).collect(Collectors.toList()), selectedPeer ); } DownloadingBackwardsHeadersSyncState(
SyncConfiguration syncConfiguration,
SyncEventsHandler syncEventsHandler,
BlockStore blockStore,
Peer peer); @Override void newBlockHeaders(List<BlockHeader> toRequest); @Override void onEnter(); } | @Test public void newHeaders() { when(blockStore.getMinNumber()).thenReturn(50L); Block child = mock(Block.class); Keccak256 hash = new Keccak256(new byte[32]); when(child.getHash()).thenReturn(hash); when(blockStore.getChainBlockByNumber(50L)).thenReturn(child); DownloadingBackwardsHeadersSyncState target = new DownloadingBackwardsHeadersSyncState( syncConfiguration, syncEventsHandler, blockStore, selectedPeer); List<BlockHeader> receivedHeaders = new LinkedList<>(); target.newBlockHeaders(receivedHeaders); verify(syncEventsHandler).backwardDownloadBodies(eq(child), eq(receivedHeaders), eq(selectedPeer)); } |
BlockNodeInformation { @Nonnull public synchronized Set<NodeID> getNodesByBlock(@Nonnull final Keccak256 blockHash) { Set<NodeID> result = nodesByBlock.get(blockHash); if (result == null) { result = new HashSet<>(); } return new HashSet<>(result); } BlockNodeInformation(final int maxBlocks); BlockNodeInformation(); synchronized void addBlockToNode(@Nonnull final Keccak256 blockHash, @Nonnull final NodeID nodeID); @Nonnull synchronized Set<NodeID> getNodesByBlock(@Nonnull final Keccak256 blockHash); @Nonnull Set<NodeID> getNodesByBlock(@Nonnull final byte[] blockHash); } | @Test public void getIsEmptyIfNotPresent() { final BlockNodeInformation nodeInformation = new BlockNodeInformation(); Assert.assertTrue(nodeInformation.getNodesByBlock(createBlockHash(0)).size() == 0); Assert.assertTrue(nodeInformation.getNodesByBlock(createBlockHash(0)).size() == 0); } |
SyncProcessor implements SyncEventsHandler { @Override public void sendSkeletonRequest(Peer peer, long height) { logger.debug("Send skeleton request to node {} height {}", peer.getPeerNodeID(), height); MessageWithId message = new SkeletonRequestMessage(++lastRequestId, height); sendMessage(peer, message); } SyncProcessor(Blockchain blockchain,
BlockStore blockStore,
ConsensusValidationMainchainView consensusValidationMainchainView,
BlockSyncService blockSyncService,
SyncConfiguration syncConfiguration,
BlockFactory blockFactory,
BlockHeaderValidationRule blockHeaderValidationRule,
SyncBlockValidatorRule syncBlockValidatorRule,
DifficultyCalculator difficultyCalculator,
PeersInformation peersInformation,
Genesis genesis); void processStatus(Peer sender, Status status); void processSkeletonResponse(Peer peer, SkeletonResponseMessage message); void processBlockHashResponse(Peer peer, BlockHashResponseMessage message); void processBlockHeadersResponse(Peer peer, BlockHeadersResponseMessage message); void processBodyResponse(Peer peer, BodyResponseMessage message); void processNewBlockHash(Peer peer, NewBlockHashMessage message); void processBlockResponse(Peer peer, BlockResponseMessage message); @Override void sendSkeletonRequest(Peer peer, long height); @Override void sendBlockHashRequest(Peer peer, long height); @Override void sendBlockHeadersRequest(Peer peer, ChunkDescriptor chunk); @Override long sendBodyRequest(Peer peer, @Nonnull BlockHeader header); Set<NodeID> getKnownPeersNodeIDs(); void onTimePassed(Duration timePassed); @Override void startSyncing(Peer peer); @Override void startDownloadingBodies(
List<Deque<BlockHeader>> pendingHeaders, Map<Peer, List<BlockIdentifier>> skeletons, Peer peer); @Override void startDownloadingHeaders(Map<Peer, List<BlockIdentifier>> skeletons, long connectionPoint, Peer peer); @Override void startDownloadingSkeleton(long connectionPoint, Peer peer); @Override void startFindingConnectionPoint(Peer peer); @Override void backwardSyncing(Peer peer); @Override void backwardDownloadBodies(Block child, List<BlockHeader> toRequest, Peer peer); @Override void stopSyncing(); @Override void onErrorSyncing(NodeID peerId, String message, EventType eventType, Object... arguments); @Override void onSyncIssue(String message, Object... arguments); @VisibleForTesting void registerExpectedMessage(MessageWithId message); @VisibleForTesting SyncState getSyncState(); @VisibleForTesting Map<Long, MessageType> getExpectedResponses(); } | @Test public void sendSkeletonRequest() { Blockchain blockchain = new BlockChainBuilder().ofSize(100); SimplePeer sender = new SimplePeer(new byte[] { 0x01 }); final ChannelManager channelManager = mock(ChannelManager.class); Peer channel = mock(Peer.class); when(channel.getPeerNodeID()).thenReturn(sender.getPeerNodeID()); when(channelManager.getActivePeers()).thenReturn(Collections.singletonList(channel)); SyncProcessor processor = new SyncProcessor( blockchain, mock(org.ethereum.db.BlockStore.class), mock(ConsensusValidationMainchainView.class), null, SyncConfiguration.IMMEDIATE_FOR_TESTING, blockFactory, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), new SyncBlockValidatorRule( new BlockUnclesHashValidationRule(), new BlockRootValidationRule(config.getActivationConfig()) ), DIFFICULTY_CALCULATOR, new PeersInformation(channelManager, SyncConfiguration.IMMEDIATE_FOR_TESTING, blockchain, RskMockFactory.getPeerScoringManager()), mock(Genesis.class)); processor.sendSkeletonRequest(sender, 0); Assert.assertFalse(sender.getMessages().isEmpty()); Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.SKELETON_REQUEST_MESSAGE, message.getMessageType()); SkeletonRequestMessage request = (SkeletonRequestMessage) message; Assert.assertNotEquals(0, request.getId()); Assert.assertEquals(0, request.getStartNumber()); Assert.assertEquals(1, processor.getExpectedResponses().size()); } |
SyncProcessor implements SyncEventsHandler { @Override public void sendBlockHashRequest(Peer peer, long height) { logger.debug("Send hash request to node {} height {}", peer.getPeerNodeID(), height); BlockHashRequestMessage message = new BlockHashRequestMessage(++lastRequestId, height); sendMessage(peer, message); } SyncProcessor(Blockchain blockchain,
BlockStore blockStore,
ConsensusValidationMainchainView consensusValidationMainchainView,
BlockSyncService blockSyncService,
SyncConfiguration syncConfiguration,
BlockFactory blockFactory,
BlockHeaderValidationRule blockHeaderValidationRule,
SyncBlockValidatorRule syncBlockValidatorRule,
DifficultyCalculator difficultyCalculator,
PeersInformation peersInformation,
Genesis genesis); void processStatus(Peer sender, Status status); void processSkeletonResponse(Peer peer, SkeletonResponseMessage message); void processBlockHashResponse(Peer peer, BlockHashResponseMessage message); void processBlockHeadersResponse(Peer peer, BlockHeadersResponseMessage message); void processBodyResponse(Peer peer, BodyResponseMessage message); void processNewBlockHash(Peer peer, NewBlockHashMessage message); void processBlockResponse(Peer peer, BlockResponseMessage message); @Override void sendSkeletonRequest(Peer peer, long height); @Override void sendBlockHashRequest(Peer peer, long height); @Override void sendBlockHeadersRequest(Peer peer, ChunkDescriptor chunk); @Override long sendBodyRequest(Peer peer, @Nonnull BlockHeader header); Set<NodeID> getKnownPeersNodeIDs(); void onTimePassed(Duration timePassed); @Override void startSyncing(Peer peer); @Override void startDownloadingBodies(
List<Deque<BlockHeader>> pendingHeaders, Map<Peer, List<BlockIdentifier>> skeletons, Peer peer); @Override void startDownloadingHeaders(Map<Peer, List<BlockIdentifier>> skeletons, long connectionPoint, Peer peer); @Override void startDownloadingSkeleton(long connectionPoint, Peer peer); @Override void startFindingConnectionPoint(Peer peer); @Override void backwardSyncing(Peer peer); @Override void backwardDownloadBodies(Block child, List<BlockHeader> toRequest, Peer peer); @Override void stopSyncing(); @Override void onErrorSyncing(NodeID peerId, String message, EventType eventType, Object... arguments); @Override void onSyncIssue(String message, Object... arguments); @VisibleForTesting void registerExpectedMessage(MessageWithId message); @VisibleForTesting SyncState getSyncState(); @VisibleForTesting Map<Long, MessageType> getExpectedResponses(); } | @Test public void sendBlockHashRequest() { Blockchain blockchain = new BlockChainBuilder().ofSize(0); SimplePeer sender = new SimplePeer(new byte[] { 0x01 }); final ChannelManager channelManager = mock(ChannelManager.class); Peer channel = mock(Peer.class); when(channel.getPeerNodeID()).thenReturn(sender.getPeerNodeID()); when(channelManager.getActivePeers()).thenReturn(Collections.singletonList(channel)); SyncProcessor processor = new SyncProcessor( blockchain, mock(org.ethereum.db.BlockStore.class), mock(ConsensusValidationMainchainView.class), null, SyncConfiguration.IMMEDIATE_FOR_TESTING, blockFactory, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), new SyncBlockValidatorRule( new BlockUnclesHashValidationRule(), new BlockRootValidationRule(config.getActivationConfig()) ), DIFFICULTY_CALCULATOR, new PeersInformation(channelManager, SyncConfiguration.IMMEDIATE_FOR_TESTING, blockchain, RskMockFactory.getPeerScoringManager()), mock(Genesis.class)); processor.sendBlockHashRequest(sender, 100); Assert.assertFalse(sender.getMessages().isEmpty()); Message message = sender.getMessages().get(0); Assert.assertEquals(MessageType.BLOCK_HASH_REQUEST_MESSAGE, message.getMessageType()); BlockHashRequestMessage request = (BlockHashRequestMessage) message; Assert.assertNotEquals(0, request.getId()); Assert.assertEquals(100, request.getHeight()); Assert.assertEquals(1, processor.getExpectedResponses().size()); } |
SyncProcessor implements SyncEventsHandler { public void processStatus(Peer sender, Status status) { logger.debug("Receiving syncState from node {} block {} {}", sender.getPeerNodeID(), status.getBestBlockNumber(), HashUtil.toPrintableHash(status.getBestBlockHash())); peersInformation.registerPeer(sender).setStatus(status); syncState.newPeerStatus(); } SyncProcessor(Blockchain blockchain,
BlockStore blockStore,
ConsensusValidationMainchainView consensusValidationMainchainView,
BlockSyncService blockSyncService,
SyncConfiguration syncConfiguration,
BlockFactory blockFactory,
BlockHeaderValidationRule blockHeaderValidationRule,
SyncBlockValidatorRule syncBlockValidatorRule,
DifficultyCalculator difficultyCalculator,
PeersInformation peersInformation,
Genesis genesis); void processStatus(Peer sender, Status status); void processSkeletonResponse(Peer peer, SkeletonResponseMessage message); void processBlockHashResponse(Peer peer, BlockHashResponseMessage message); void processBlockHeadersResponse(Peer peer, BlockHeadersResponseMessage message); void processBodyResponse(Peer peer, BodyResponseMessage message); void processNewBlockHash(Peer peer, NewBlockHashMessage message); void processBlockResponse(Peer peer, BlockResponseMessage message); @Override void sendSkeletonRequest(Peer peer, long height); @Override void sendBlockHashRequest(Peer peer, long height); @Override void sendBlockHeadersRequest(Peer peer, ChunkDescriptor chunk); @Override long sendBodyRequest(Peer peer, @Nonnull BlockHeader header); Set<NodeID> getKnownPeersNodeIDs(); void onTimePassed(Duration timePassed); @Override void startSyncing(Peer peer); @Override void startDownloadingBodies(
List<Deque<BlockHeader>> pendingHeaders, Map<Peer, List<BlockIdentifier>> skeletons, Peer peer); @Override void startDownloadingHeaders(Map<Peer, List<BlockIdentifier>> skeletons, long connectionPoint, Peer peer); @Override void startDownloadingSkeleton(long connectionPoint, Peer peer); @Override void startFindingConnectionPoint(Peer peer); @Override void backwardSyncing(Peer peer); @Override void backwardDownloadBodies(Block child, List<BlockHeader> toRequest, Peer peer); @Override void stopSyncing(); @Override void onErrorSyncing(NodeID peerId, String message, EventType eventType, Object... arguments); @Override void onSyncIssue(String message, Object... arguments); @VisibleForTesting void registerExpectedMessage(MessageWithId message); @VisibleForTesting SyncState getSyncState(); @VisibleForTesting Map<Long, MessageType> getExpectedResponses(); } | @Test(expected = Exception.class) public void processBlockHashResponseWithUnknownHash() { Blockchain blockchain = new BlockChainBuilder().ofSize(0); SimplePeer sender = new SimplePeer(new byte[] { 0x01 }); SyncProcessor processor = new SyncProcessor( blockchain, mock(org.ethereum.db.BlockStore.class), mock(ConsensusValidationMainchainView.class), null, SyncConfiguration.IMMEDIATE_FOR_TESTING, blockFactory, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), new SyncBlockValidatorRule( new BlockUnclesHashValidationRule(), new BlockRootValidationRule(config.getActivationConfig()) ), DIFFICULTY_CALCULATOR, new PeersInformation(getChannelManager(), SyncConfiguration.IMMEDIATE_FOR_TESTING, blockchain, RskMockFactory.getPeerScoringManager()), mock(Genesis.class)); processor.processStatus(sender, new Status(100, null)); } |
ABICallElection { public Map<ABICallSpec, List<RskAddress>> getVotes() { return votes; } ABICallElection(AddressBasedAuthorizer authorizer, Map<ABICallSpec, List<RskAddress>> votes); ABICallElection(AddressBasedAuthorizer authorizer); Map<ABICallSpec, List<RskAddress>> getVotes(); void clear(); boolean vote(ABICallSpec callSpec, RskAddress voter); ABICallSpec getWinner(); void clearWinners(); } | @Test public void emptyVotesConstructor() { ABICallElection electionBis = new ABICallElection(authorizer); Assert.assertEquals(0, electionBis.getVotes().size()); }
@Test public void getVotes() { Assert.assertSame(votes, election.getVotes()); } |
ABICallElection { public void clear() { this.votes = new HashMap<>(); } ABICallElection(AddressBasedAuthorizer authorizer, Map<ABICallSpec, List<RskAddress>> votes); ABICallElection(AddressBasedAuthorizer authorizer); Map<ABICallSpec, List<RskAddress>> getVotes(); void clear(); boolean vote(ABICallSpec callSpec, RskAddress voter); ABICallSpec getWinner(); void clearWinners(); } | @Test public void clear() { election.clear(); Assert.assertEquals(0, election.getVotes().size()); } |
ABICallSpec { public String getFunction() { return function; } ABICallSpec(String function, byte[][] arguments); String getFunction(); byte[][] getArguments(); byte[] getEncoded(); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); static final Comparator<ABICallSpec> byBytesComparator; } | @Test public void getFunction() { ABICallSpec spec = new ABICallSpec("a-function", new byte[][]{}); Assert.assertEquals("a-function", spec.getFunction()); } |
ABICallSpec { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } ABICallSpec otherSpec = ((ABICallSpec) other); return otherSpec.getFunction().equals(getFunction()) && areEqual(arguments, otherSpec.arguments); } ABICallSpec(String function, byte[][] arguments); String getFunction(); byte[][] getArguments(); byte[] getEncoded(); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); static final Comparator<ABICallSpec> byBytesComparator; } | @Test public void testEquals() { ABICallSpec specA = new ABICallSpec("function-a", new byte[][]{ Hex.decode("aabb"), Hex.decode("ccddee") }); ABICallSpec specB = new ABICallSpec("function-b", new byte[][]{ Hex.decode("aabb"), Hex.decode("ccddee") }); ABICallSpec specC = new ABICallSpec("function-a", new byte[][]{ Hex.decode("ccddee"), Hex.decode("aabb") }); ABICallSpec specD = new ABICallSpec("function-a", new byte[][]{ Hex.decode("aabb"), Hex.decode("ccdd") }); ABICallSpec specE = new ABICallSpec("function-a", new byte[][]{ Hex.decode("aabb") }); ABICallSpec specF = new ABICallSpec("function-a", new byte[][]{ Hex.decode("aabb"), Hex.decode("ccddee") }); Assert.assertEquals(specA, specF); Assert.assertNotEquals(specA, specB); Assert.assertNotEquals(specA, specC); Assert.assertNotEquals(specA, specD); Assert.assertNotEquals(specA, specE); } |
PendingFederation { public List<FederationMember> getMembers() { return members; } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); } | @Test public void membersImmutable() { boolean exception = false; try { pendingFederation.getMembers().add(new FederationMember(new BtcECKey(), new ECKey(), new ECKey())); } catch (Exception e) { exception = true; } Assert.assertTrue(exception); exception = false; try { pendingFederation.getMembers().remove(0); } catch (Exception e) { exception = true; } Assert.assertTrue(exception); } |
PendingFederation { public boolean isComplete() { return this.members.size() >= MIN_MEMBERS_REQUIRED; } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); } | @Test public void isComplete() { Assert.assertTrue(pendingFederation.isComplete()); }
@Test public void isComplete_not() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(200)); Assert.assertFalse(otherPendingFederation.isComplete()); } |
PendingFederation { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } return this.members.equals(((PendingFederation) other).members); } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); } | @Test public void testEquals_basic() { Assert.assertTrue(pendingFederation.equals(pendingFederation)); Assert.assertFalse(pendingFederation.equals(null)); Assert.assertFalse(pendingFederation.equals(new Object())); Assert.assertFalse(pendingFederation.equals("something else")); }
@Test public void testEquals_differentNumberOfMembers() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500, 600, 700)); Assert.assertFalse(pendingFederation.equals(otherPendingFederation)); }
@Test public void testEquals_differentMembers() { List<FederationMember> members = FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500); members.add(new FederationMember(BtcECKey.fromPrivate(BigInteger.valueOf(610)), ECKey.fromPrivate(BigInteger.valueOf(600)), ECKey.fromPrivate(BigInteger.valueOf(620)))); PendingFederation otherPendingFederation = new PendingFederation(members); members.remove(members.size()-1); members.add(new FederationMember(BtcECKey.fromPrivate(BigInteger.valueOf(600)), ECKey.fromPrivate(BigInteger.valueOf(610)), ECKey.fromPrivate(BigInteger.valueOf(630)))); PendingFederation yetOtherPendingFederation = new PendingFederation(members); Assert.assertFalse(otherPendingFederation.equals(yetOtherPendingFederation)); Assert.assertFalse(pendingFederation.equals(otherPendingFederation)); Assert.assertFalse(pendingFederation.equals(yetOtherPendingFederation)); }
@Test public void testEquals_same() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500, 600)); Assert.assertTrue(pendingFederation.equals(otherPendingFederation)); } |
PendingFederation { @Override public String toString() { return String.format("%d signatures pending federation (%s)", members.size(), isComplete() ? "complete" : "incomplete"); } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); } | @Test public void testToString() { Assert.assertEquals("6 signatures pending federation (complete)", pendingFederation.toString()); PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(100)); Assert.assertEquals("1 signatures pending federation (incomplete)", otherPendingFederation.toString()); } |
PendingFederation { public Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams) { if (!this.isComplete()) { throw new IllegalStateException("PendingFederation is incomplete"); } return new Federation( members, creationTime, blockNumber, btcParams ); } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); } | @Test public void buildFederation_ok_a() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500, 600)); Federation expectedFederation = new Federation( FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500, 600), Instant.ofEpochMilli(1234L), 0L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST) ); Assert.assertEquals( expectedFederation, otherPendingFederation.buildFederation( Instant.ofEpochMilli(1234L), 0L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST) ) ); }
@Test public void buildFederation_ok_b() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks( 100, 200, 300, 400, 500, 600, 700, 800, 900 )); Federation expectedFederation = new Federation( FederationTestUtils.getFederationMembersFromPks(100, 200, 300, 400, 500, 600, 700, 800, 900), Instant.ofEpochMilli(1234L), 0L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST) ); Assert.assertEquals( expectedFederation, otherPendingFederation.buildFederation( Instant.ofEpochMilli(1234L), 0L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST) ) ); }
@Test public void buildFederation_incomplete() { PendingFederation otherPendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersFromPks(100)); try { otherPendingFederation.buildFederation(Instant.ofEpochMilli(12L), 0L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); } catch (Exception e) { Assert.assertEquals("PendingFederation is incomplete", e.getMessage()); return; } Assert.fail(); } |
ECKey { @Nullable public byte[] getPrivKeyBytes() { return bigIntegerToBytes(priv, 32); } ECKey(); ECKey(SecureRandom secureRandom); ECKey(@Nullable BigInteger priv, ECPoint pub); static ECPoint compressPoint(ECPoint uncompressed); static ECPoint decompressPoint(ECPoint compressed); static ECKey fromPrivate(BigInteger privKey); static ECKey fromPrivate(byte[] privKeyBytes); static ECKey fromPublicOnly(ECPoint pub); static ECKey fromPublicOnly(byte[] pub); ECKey decompress(); boolean isPubKeyOnly(); boolean hasPrivKey(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getAddress(); byte[] getNodeId(); byte[] getPubKey(); byte[] getPubKey(boolean compressed); ECPoint getPubKeyPoint(); boolean equalsPub(ECKey other); BigInteger getPrivKey(); String toString(); ECDSASignature doSign(byte[] input); ECDSASignature sign(byte[] messageHash); @Deprecated static ECKey signatureToKey(byte[] messageHash, ECDSASignature signature); byte[] decryptAES(byte[] cipher); @Deprecated static boolean verify(byte[] data, ECDSASignature signature, byte[] pub); @Deprecated boolean verify(byte[] sigHash, ECDSASignature signature); boolean verify(byte[] sigHash, org.ethereum.crypto.signature.ECDSASignature signature); boolean isPubKeyCanonical(); static boolean isPubKeyCanonical(byte[] pubkey); @Deprecated @Nullable static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed); @Nullable byte[] getPrivKeyBytes(); @Override boolean equals(Object o); @Override int hashCode(); static final ECDomainParameters CURVE; static final BigInteger HALF_CURVE_ORDER; } | @Test public void testGetPrivKeyBytes() { ECKey key = new ECKey(); assertNotNull(key.getPrivKeyBytes()); assertEquals(32, key.getPrivKeyBytes().length); } |
PendingFederation { public Keccak256 getHash() { byte[] encoded = BridgeSerializationUtils.serializePendingFederationOnlyBtcKeys(this); return new Keccak256(HashUtil.keccak256(encoded)); } PendingFederation(List<FederationMember> members); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); boolean isComplete(); PendingFederation addMember(FederationMember member); Federation buildFederation(Instant creationTime, long blockNumber, NetworkParameters btcParams); @Override String toString(); @Override boolean equals(Object other); Keccak256 getHash(); @Override int hashCode(); } | @PrepareForTest({ BridgeSerializationUtils.class }) @Test public void getHash() { PowerMockito.mockStatic(BridgeSerializationUtils.class); PowerMockito.when(BridgeSerializationUtils.serializePendingFederationOnlyBtcKeys(pendingFederation)).thenReturn(new byte[] { (byte) 0xaa }); Keccak256 expectedHash = new Keccak256(HashUtil.keccak256(new byte[] { (byte) 0xaa })); Assert.assertEquals(expectedHash, pendingFederation.getHash()); } |
BridgeSupport { @VisibleForTesting ActivationConfig.ForBlock getActivations() { return this.activations; } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void activations_is_set() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP124)).thenReturn(true); BridgeSupport bridgeSupport = getBridgeSupport( mock(BridgeConstants.class), mock(BridgeStorageProvider.class), mock(Repository.class), mock(BridgeEventLogger.class), mock(BtcLockSenderProvider.class), mock(Block.class), mock(BtcBlockStoreWithCache.Factory.class), activations); Assert.assertTrue(bridgeSupport.getActivations().isActive(ConsensusRule.RSKIP124)); } |
BridgeSupport { public Integer voteFeePerKbChange(Transaction tx, Coin feePerKb) { AddressBasedAuthorizer authorizer = bridgeConstants.getFeePerKbChangeAuthorizer(); if (!authorizer.isAuthorized(tx)) { return FEE_PER_KB_GENERIC_ERROR_CODE; } if(!feePerKb.isPositive()){ return NEGATIVE_FEE_PER_KB_ERROR_CODE; } if(feePerKb.isGreaterThan(bridgeConstants.getMaxFeePerKb())) { return EXCESSIVE_FEE_PER_KB_ERROR_CODE; } ABICallElection feePerKbElection = provider.getFeePerKbElection(authorizer); ABICallSpec feeVote = new ABICallSpec("setFeePerKb", new byte[][]{BridgeSerializationUtils.serializeCoin(feePerKb)}); boolean successfulVote = feePerKbElection.vote(feeVote, tx.getSender()); if (!successfulVote) { return -1; } ABICallSpec winner = feePerKbElection.getWinner(); if (winner == null) { logger.info("Successful fee per kb vote for {}", feePerKb); return 1; } Coin winnerFee; try { winnerFee = BridgeSerializationUtils.deserializeCoin(winner.getArguments()[0]); } catch (Exception e) { logger.warn("Exception deserializing winner feePerKb", e); return FEE_PER_KB_GENERIC_ERROR_CODE; } if (winnerFee == null) { logger.warn("Invalid winner feePerKb: feePerKb can't be null"); return FEE_PER_KB_GENERIC_ERROR_CODE; } if (!winnerFee.equals(feePerKb)) { logger.debug("Winner fee is different than the last vote: maybe you forgot to clear winners"); } logger.info("Fee per kb changed to {}", winnerFee); provider.setFeePerKb(winnerFee); feePerKbElection.clear(); return 1; } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test(expected = NullPointerException.class) public void voteFeePerKbChange_nullFeeThrows() { BridgeStorageProvider provider = mock(BridgeStorageProvider.class); Transaction tx = mock(Transaction.class); BridgeConstants constants = mock(BridgeConstants.class); AddressBasedAuthorizer authorizer = mock(AddressBasedAuthorizer.class); when(provider.getFeePerKbElection(any())) .thenReturn(new ABICallElection(null)); when(tx.getSender()) .thenReturn(new RskAddress(ByteUtil.leftPadBytes(new byte[]{0x43}, 20))); when(constants.getFeePerKbChangeAuthorizer()) .thenReturn(authorizer); when(authorizer.isAuthorized(tx)) .thenReturn(true); BridgeSupport bridgeSupport = getBridgeSupport(constants, provider); bridgeSupport.voteFeePerKbChange(tx, null); verify(provider, never()).setFeePerKb(any()); }
@Test public void voteFeePerKbChange_unsuccessfulVote_unauthorized() { BridgeStorageProvider provider = mock(BridgeStorageProvider.class); Transaction tx = mock(Transaction.class); BridgeConstants constants = mock(BridgeConstants.class); AddressBasedAuthorizer authorizer = mock(AddressBasedAuthorizer.class); byte[] senderBytes = ByteUtil.leftPadBytes(new byte[]{0x43}, 20); when(provider.getFeePerKbElection(any())) .thenReturn(new ABICallElection(authorizer)); when(tx.getSender()) .thenReturn(new RskAddress(senderBytes)); when(constants.getFeePerKbChangeAuthorizer()) .thenReturn(authorizer); when(authorizer.isAuthorized(tx)) .thenReturn(false); BridgeSupport bridgeSupport = getBridgeSupport(constants, provider); assertThat(bridgeSupport.voteFeePerKbChange(tx, Coin.CENT), is(-10)); verify(provider, never()).setFeePerKb(any()); }
@Test public void voteFeePerKbChange_unsuccessfulVote_negativeFeePerKb() { BridgeStorageProvider provider = mock(BridgeStorageProvider.class); Transaction tx = mock(Transaction.class); BridgeConstants constants = mock(BridgeConstants.class); AddressBasedAuthorizer authorizer = mock(AddressBasedAuthorizer.class); byte[] senderBytes = ByteUtil.leftPadBytes(new byte[]{0x43}, 20); when(provider.getFeePerKbElection(any())) .thenReturn(new ABICallElection(authorizer)); when(tx.getSender()) .thenReturn(new RskAddress(senderBytes)); when(constants.getFeePerKbChangeAuthorizer()) .thenReturn(authorizer); when(authorizer.isAuthorized(tx)) .thenReturn(true); when(authorizer.isAuthorized(tx.getSender())) .thenReturn(true); when(authorizer.getRequiredAuthorizedKeys()) .thenReturn(2); BridgeSupport bridgeSupport = getBridgeSupport(constants, provider); assertThat(bridgeSupport.voteFeePerKbChange(tx, Coin.NEGATIVE_SATOSHI), is(-1)); assertThat(bridgeSupport.voteFeePerKbChange(tx, Coin.ZERO), is(-1)); verify(provider, never()).setFeePerKb(any()); }
@Test public void voteFeePerKbChange_unsuccessfulVote_excessiveFeePerKb() { final long MAX_FEE_PER_KB = 5_000_000L; BridgeStorageProvider provider = mock(BridgeStorageProvider.class); Transaction tx = mock(Transaction.class); BridgeConstants constants = mock(BridgeConstants.class); AddressBasedAuthorizer authorizer = mock(AddressBasedAuthorizer.class); byte[] senderBytes = ByteUtil.leftPadBytes(new byte[]{0x43}, 20); when(provider.getFeePerKbElection(any())) .thenReturn(new ABICallElection(authorizer)); when(tx.getSender()) .thenReturn(new RskAddress(senderBytes)); when(constants.getFeePerKbChangeAuthorizer()) .thenReturn(authorizer); when(authorizer.isAuthorized(tx)) .thenReturn(true); when(authorizer.isAuthorized(tx.getSender())) .thenReturn(true); when(authorizer.getRequiredAuthorizedKeys()) .thenReturn(2); when(constants.getMaxFeePerKb()) .thenReturn(Coin.valueOf(MAX_FEE_PER_KB)); BridgeSupport bridgeSupport = getBridgeSupport(constants, provider); assertThat(bridgeSupport.voteFeePerKbChange(tx, Coin.valueOf(MAX_FEE_PER_KB)), is(1)); assertThat(bridgeSupport.voteFeePerKbChange(tx, Coin.valueOf(MAX_FEE_PER_KB + 1)), is(-2)); verify(provider, never()).setFeePerKb(any()); }
@Test public void voteFeePerKbChange_successfulVote() { final long MAX_FEE_PER_KB = 5_000_000L; BridgeStorageProvider provider = mock(BridgeStorageProvider.class); Transaction tx = mock(Transaction.class); BridgeConstants constants = mock(BridgeConstants.class); AddressBasedAuthorizer authorizer = mock(AddressBasedAuthorizer.class); byte[] senderBytes = ByteUtil.leftPadBytes(new byte[]{0x43}, 20); when(provider.getFeePerKbElection(any())) .thenReturn(new ABICallElection(authorizer)); when(tx.getSender()) .thenReturn(new RskAddress(senderBytes)); when(constants.getFeePerKbChangeAuthorizer()) .thenReturn(authorizer); when(authorizer.isAuthorized(tx)) .thenReturn(true); when(authorizer.isAuthorized(tx.getSender())) .thenReturn(true); when(authorizer.getRequiredAuthorizedKeys()) .thenReturn(2); when(constants.getMaxFeePerKb()) .thenReturn(Coin.valueOf(MAX_FEE_PER_KB)); BridgeSupport bridgeSupport = getBridgeSupport(constants, provider); assertThat(bridgeSupport.voteFeePerKbChange(tx, Coin.CENT), is(1)); verify(provider, never()).setFeePerKb(any()); }
@Test public void voteFeePerKbChange_successfulVoteWithFeeChange() { final long MAX_FEE_PER_KB = 5_000_000L; BridgeStorageProvider provider = mock(BridgeStorageProvider.class); Transaction tx = mock(Transaction.class); BridgeConstants constants = mock(BridgeConstants.class); AddressBasedAuthorizer authorizer = mock(AddressBasedAuthorizer.class); byte[] senderBytes = ByteUtil.leftPadBytes(new byte[]{0x43}, 20); when(provider.getFeePerKbElection(any())) .thenReturn(new ABICallElection(authorizer)); when(tx.getSender()) .thenReturn(new RskAddress(senderBytes)); when(constants.getFeePerKbChangeAuthorizer()) .thenReturn(authorizer); when(authorizer.isAuthorized(tx)) .thenReturn(true); when(authorizer.isAuthorized(tx.getSender())) .thenReturn(true); when(authorizer.getRequiredAuthorizedKeys()) .thenReturn(1); when(constants.getMaxFeePerKb()) .thenReturn(Coin.valueOf(MAX_FEE_PER_KB)); BridgeSupport bridgeSupport = getBridgeSupport(constants, provider); assertThat(bridgeSupport.voteFeePerKbChange(tx, Coin.CENT), is(1)); verify(provider).setFeePerKb(Coin.CENT); } |
BridgeSupport { public Coin getLockingCap() { if (activations.isActive(ConsensusRule.RSKIP134) && this.provider.getLockingCap() == null) { logger.debug("Setting initial locking cap value"); this.provider.setLockingCap(bridgeConstants.getInitialLockingCap()); } return this.provider.getLockingCap(); } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void getLockingCap() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP134)).thenReturn(true); BridgeConstants constants = mock(BridgeConstants.class); when(constants.getInitialLockingCap()).thenReturn(Coin.SATOSHI); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); when(provider.getLockingCap()).thenReturn(null).thenReturn(constants.getInitialLockingCap()); BridgeSupport bridgeSupport = getBridgeSupport( constants, provider, mock(Repository.class), mock(BridgeEventLogger.class), null, null, activations ); assertEquals(constants.getInitialLockingCap(), bridgeSupport.getLockingCap()); assertEquals(constants.getInitialLockingCap(), bridgeSupport.getLockingCap()); verify(provider, times(1)).setLockingCap(constants.getInitialLockingCap()); } |
BIUtil { public static boolean isIn20PercentRange(BigInteger first, BigInteger second) { BigInteger five = BigInteger.valueOf(5); BigInteger limit = first.add(first.divide(five)); return !isMoreThan(second, limit); } static boolean isZero(BigInteger value); static boolean isEqual(BigInteger valueA, BigInteger valueB); static boolean isNotEqual(BigInteger valueA, BigInteger valueB); static boolean isLessThan(BigInteger valueA, BigInteger valueB); static boolean isMoreThan(BigInteger valueA, BigInteger valueB); static BigInteger sum(BigInteger valueA, BigInteger valueB); static BigInteger toBI(byte[] data); static BigInteger toBI(long data); static boolean isPositive(BigInteger value); static boolean isCovers(Coin covers, Coin value); static boolean isNotCovers(Coin covers, Coin value); static boolean isIn20PercentRange(BigInteger first, BigInteger second); static BigInteger max(BigInteger first, BigInteger second); } | @Test public void testIsIn20PercentRange() { assertTrue(isIn20PercentRange(BigInteger.valueOf(20000), BigInteger.valueOf(24000))); assertTrue(isIn20PercentRange(BigInteger.valueOf(24000), BigInteger.valueOf(20000))); assertFalse(isIn20PercentRange(BigInteger.valueOf(20000), BigInteger.valueOf(25000))); assertTrue(isIn20PercentRange(BigInteger.valueOf(20), BigInteger.valueOf(24))); assertTrue(isIn20PercentRange(BigInteger.valueOf(24), BigInteger.valueOf(20))); assertFalse(isIn20PercentRange(BigInteger.valueOf(20), BigInteger.valueOf(25))); assertTrue(isIn20PercentRange(BigInteger.ZERO, BigInteger.ZERO)); assertFalse(isIn20PercentRange(BigInteger.ZERO, BigInteger.ONE)); assertTrue(isIn20PercentRange(BigInteger.ONE, BigInteger.ZERO)); }
@Test public void test1() { assertFalse(isIn20PercentRange(BigInteger.ONE, BigInteger.valueOf(5))); assertTrue(isIn20PercentRange(BigInteger.valueOf(5), BigInteger.ONE)); assertTrue(isIn20PercentRange(BigInteger.valueOf(5), BigInteger.valueOf(6))); assertFalse(isIn20PercentRange(BigInteger.valueOf(5), BigInteger.valueOf(7))); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.