target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void parseIPv6() { InetSocketAddress result = IpUtils.parseAddress(IPV6_WITH_PORT); Assert.assertNotNull(result); }
public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
@Test public void parseIPv6NoPort() { InetSocketAddress result = IpUtils.parseAddress(IPV6_NO_PORT); Assert.assertNull(result); }
public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
@Test public void parseIPv6InvalidFormat() { InetSocketAddress result = IpUtils.parseAddress(IPV6_INVALID); Assert.assertNull(result); }
public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
@Test public void oneTransactionAndEvents() { PendingTransactionFilter filter = new PendingTransactionFilter(); Account sender = new AccountBuilder().name("sender").build(); Account receiver = new AccountBuilder().name("receiver").build(); Transaction tx = new TransactionBuilder() .sender(sender) .receiver(receiver) .value(BigInteger.TEN) .build(); filter.newPendingTx(tx); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(1, result.length); Assert.assertEquals("0x" + tx.getHash().toHexString(), result[0]); }
@Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); }
PendingTransactionFilter extends Filter { @Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); } }
PendingTransactionFilter extends Filter { @Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); } }
PendingTransactionFilter extends Filter { @Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); } @Override void newPendingTx(Transaction tx); }
PendingTransactionFilter extends Filter { @Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); } @Override void newPendingTx(Transaction tx); }
@Test public void parseIPv4() { InetSocketAddress result = IpUtils.parseAddress(IPV4_WITH_PORT); Assert.assertNotNull(result); }
public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
@Test public void parseIPv4NoPort() { InetSocketAddress result = IpUtils.parseAddress(IPV4_NO_PORT); Assert.assertNull(result); }
public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
@Test public void parseHostnameWithPort() { InetSocketAddress result = IpUtils.parseAddress(HOSTNAME_WITH_PORT); Assert.assertNotNull(result); }
public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
IpUtils { public static InetSocketAddress parseAddress(String address) { if(StringUtils.isBlank(address)) { return null; } Matcher matcher = ipv6Pattern.matcher(address); if(matcher.matches()) { return parseMatch(matcher); } matcher = ipv4Pattern.matcher(address); if (matcher.matches() && matcher.groupCount() == 2) { return parseMatch(matcher); } logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address); return null; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
@Test public void parseAddresses() { List<String> addresses = new ArrayList<>(); addresses.add(IPV6_WITH_PORT); addresses.add(IPV6_NO_PORT); addresses.add(IPV6_INVALID); addresses.add(IPV4_WITH_PORT); addresses.add(IPV4_NO_PORT); List<InetSocketAddress> result = IpUtils.parseAddresses(addresses); Assert.assertFalse(result.isEmpty()); Assert.assertEquals(2, result.size()); }
public static List<InetSocketAddress> parseAddresses(List<String> addresses) { List<InetSocketAddress> result = new ArrayList<>(); for(String a : addresses) { InetSocketAddress res = parseAddress(a); if (res != null) { result.add(res); } } return result; }
IpUtils { public static List<InetSocketAddress> parseAddresses(List<String> addresses) { List<InetSocketAddress> result = new ArrayList<>(); for(String a : addresses) { InetSocketAddress res = parseAddress(a); if (res != null) { result.add(res); } } return result; } }
IpUtils { public static List<InetSocketAddress> parseAddresses(List<String> addresses) { List<InetSocketAddress> result = new ArrayList<>(); for(String a : addresses) { InetSocketAddress res = parseAddress(a); if (res != null) { result.add(res); } } return result; } }
IpUtils { public static List<InetSocketAddress> parseAddresses(List<String> addresses) { List<InetSocketAddress> result = new ArrayList<>(); for(String a : addresses) { InetSocketAddress res = parseAddress(a); if (res != null) { result.add(res); } } return result; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
IpUtils { public static List<InetSocketAddress> parseAddresses(List<String> addresses) { List<InetSocketAddress> result = new ArrayList<>(); for(String a : addresses) { InetSocketAddress res = parseAddress(a); if (res != null) { result.add(res); } } return result; } static InetSocketAddress parseAddress(String address); static List<InetSocketAddress> parseAddresses(List<String> addresses); }
@Test public void formatNanosecondsToSeconds() { Assert.assertEquals("1.234568", FormatUtils.formatNanosecondsToSeconds(1_234_567_890L)); Assert.assertEquals("1234.567890", FormatUtils.formatNanosecondsToSeconds(1_234_567_890_123L)); Assert.assertEquals("1234567.890123", FormatUtils.formatNanosecondsToSeconds(1_234_567_890_123_000L)); Assert.assertEquals("0.000000", FormatUtils.formatNanosecondsToSeconds(0L)); Assert.assertEquals("0.000001", FormatUtils.formatNanosecondsToSeconds(1_234L)); }
public static String formatNanosecondsToSeconds(long nanoseconds) { return String.format("%.6f", nanoseconds / 1_000_000_000.0); }
FormatUtils { public static String formatNanosecondsToSeconds(long nanoseconds) { return String.format("%.6f", nanoseconds / 1_000_000_000.0); } }
FormatUtils { public static String formatNanosecondsToSeconds(long nanoseconds) { return String.format("%.6f", nanoseconds / 1_000_000_000.0); } private FormatUtils(); }
FormatUtils { public static String formatNanosecondsToSeconds(long nanoseconds) { return String.format("%.6f", nanoseconds / 1_000_000_000.0); } private FormatUtils(); static String formatNanosecondsToSeconds(long nanoseconds); }
FormatUtils { public static String formatNanosecondsToSeconds(long nanoseconds) { return String.format("%.6f", nanoseconds / 1_000_000_000.0); } private FormatUtils(); static String formatNanosecondsToSeconds(long nanoseconds); }
@Test public void callingRunStartsInternalServices() { runner.run(); for (InternalService internalService : internalServices) { verify(internalService).start(); } }
@Override public void run() { logger.info("Starting RSK"); logger.info( "Running {}, core version: {}-{}", rskSystemProperties.genesisInfo(), rskSystemProperties.projectVersion(), rskSystemProperties.projectVersionModifier() ); buildInfo.printInfo(logger); for (InternalService internalService : internalServices) { internalService.start(); } if (logger.isInfoEnabled()) { String versions = EthVersion.supported().stream().map(EthVersion::name).collect(Collectors.joining(", ")); logger.info("Capability eth version: [{}]", versions); } logger.info("done"); }
FullNodeRunner implements NodeRunner { @Override public void run() { logger.info("Starting RSK"); logger.info( "Running {}, core version: {}-{}", rskSystemProperties.genesisInfo(), rskSystemProperties.projectVersion(), rskSystemProperties.projectVersionModifier() ); buildInfo.printInfo(logger); for (InternalService internalService : internalServices) { internalService.start(); } if (logger.isInfoEnabled()) { String versions = EthVersion.supported().stream().map(EthVersion::name).collect(Collectors.joining(", ")); logger.info("Capability eth version: [{}]", versions); } logger.info("done"); } }
FullNodeRunner implements NodeRunner { @Override public void run() { logger.info("Starting RSK"); logger.info( "Running {}, core version: {}-{}", rskSystemProperties.genesisInfo(), rskSystemProperties.projectVersion(), rskSystemProperties.projectVersionModifier() ); buildInfo.printInfo(logger); for (InternalService internalService : internalServices) { internalService.start(); } if (logger.isInfoEnabled()) { String versions = EthVersion.supported().stream().map(EthVersion::name).collect(Collectors.joining(", ")); logger.info("Capability eth version: [{}]", versions); } logger.info("done"); } FullNodeRunner( List<InternalService> internalServices, RskSystemProperties rskSystemProperties, BuildInfo buildInfo); }
FullNodeRunner implements NodeRunner { @Override public void run() { logger.info("Starting RSK"); logger.info( "Running {}, core version: {}-{}", rskSystemProperties.genesisInfo(), rskSystemProperties.projectVersion(), rskSystemProperties.projectVersionModifier() ); buildInfo.printInfo(logger); for (InternalService internalService : internalServices) { internalService.start(); } if (logger.isInfoEnabled()) { String versions = EthVersion.supported().stream().map(EthVersion::name).collect(Collectors.joining(", ")); logger.info("Capability eth version: [{}]", versions); } logger.info("done"); } FullNodeRunner( List<InternalService> internalServices, RskSystemProperties rskSystemProperties, BuildInfo buildInfo); @Override void run(); @Override void stop(); }
FullNodeRunner implements NodeRunner { @Override public void run() { logger.info("Starting RSK"); logger.info( "Running {}, core version: {}-{}", rskSystemProperties.genesisInfo(), rskSystemProperties.projectVersion(), rskSystemProperties.projectVersionModifier() ); buildInfo.printInfo(logger); for (InternalService internalService : internalServices) { internalService.start(); } if (logger.isInfoEnabled()) { String versions = EthVersion.supported().stream().map(EthVersion::name).collect(Collectors.joining(", ")); logger.info("Capability eth version: [{}]", versions); } logger.info("done"); } FullNodeRunner( List<InternalService> internalServices, RskSystemProperties rskSystemProperties, BuildInfo buildInfo); @Override void run(); @Override void stop(); }
@Test public void callingStopStopsInternalServices() { runner.stop(); for (InternalService internalService : internalServices) { verify(internalService).stop(); } }
@Override public void stop() { logger.info("Shutting down RSK node"); for (int i = internalServices.size() - 1; i >= 0; i--) { internalServices.get(i).stop(); } logger.info("RSK node Shut down"); }
FullNodeRunner implements NodeRunner { @Override public void stop() { logger.info("Shutting down RSK node"); for (int i = internalServices.size() - 1; i >= 0; i--) { internalServices.get(i).stop(); } logger.info("RSK node Shut down"); } }
FullNodeRunner implements NodeRunner { @Override public void stop() { logger.info("Shutting down RSK node"); for (int i = internalServices.size() - 1; i >= 0; i--) { internalServices.get(i).stop(); } logger.info("RSK node Shut down"); } FullNodeRunner( List<InternalService> internalServices, RskSystemProperties rskSystemProperties, BuildInfo buildInfo); }
FullNodeRunner implements NodeRunner { @Override public void stop() { logger.info("Shutting down RSK node"); for (int i = internalServices.size() - 1; i >= 0; i--) { internalServices.get(i).stop(); } logger.info("RSK node Shut down"); } FullNodeRunner( List<InternalService> internalServices, RskSystemProperties rskSystemProperties, BuildInfo buildInfo); @Override void run(); @Override void stop(); }
FullNodeRunner implements NodeRunner { @Override public void stop() { logger.info("Shutting down RSK node"); for (int i = internalServices.size() - 1; i >= 0; i--) { internalServices.get(i).stop(); } logger.info("RSK node Shut down"); } FullNodeRunner( List<InternalService> internalServices, RskSystemProperties rskSystemProperties, BuildInfo buildInfo); @Override void run(); @Override void stop(); }
@Test public void rejectBlockWithSiblingUncle() { BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); Block uncle = blockGenerator.createChildBlock(block1); List<BlockHeader> uncles = new ArrayList<>(); uncles.add(uncle.getHeader()); Block block = blockGenerator.createChildBlock(block1, null, uncles, 1, null); BlockStore blockStore = new IndexedBlockStore(null, new HashMapDB(), new HashMapBlocksIndex()); blockStore.saveBlock(genesis, new BlockDifficulty(BigInteger.valueOf(1)), true); blockStore.saveBlock(block1, new BlockDifficulty(BigInteger.valueOf(2)), true); BlockUnclesValidationRule rule = new BlockUnclesValidationRule(blockStore,10, 10, new BlockHeaderCompositeRule(), new BlockHeaderParentCompositeRule()); Assert.assertFalse(rule.isValid(block)); }
@Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; }
BlockUnclesValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; } }
BlockUnclesValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; } BlockUnclesValidationRule( BlockStore blockStore, int uncleListLimit, int uncleGenerationLimit, BlockHeaderValidationRule validations, BlockHeaderParentDependantValidationRule parentValidations); }
BlockUnclesValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; } BlockUnclesValidationRule( BlockStore blockStore, int uncleListLimit, int uncleGenerationLimit, BlockHeaderValidationRule validations, BlockHeaderParentDependantValidationRule parentValidations); @Override boolean isValid(Block block); boolean validateUncleList(long blockNumber, List<BlockHeader> uncles, Set<Keccak256> ancestors, Set<Keccak256> used); }
BlockUnclesValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; } BlockUnclesValidationRule( BlockStore blockStore, int uncleListLimit, int uncleGenerationLimit, BlockHeaderValidationRule validations, BlockHeaderParentDependantValidationRule parentValidations); @Override boolean isValid(Block block); boolean validateUncleList(long blockNumber, List<BlockHeader> uncles, Set<Keccak256> ancestors, Set<Keccak256> used); static final String INVALIDUNCLE; }
@Test public void rejectBlockWithUncleHavingHigherNumber() { BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); Block uncle1 = blockGenerator.createChildBlock(block1); Block uncle2 = blockGenerator.createChildBlock(uncle1); List<BlockHeader> uncles = new ArrayList<>(); uncles.add(uncle2.getHeader()); Block block = blockGenerator.createChildBlock(block1, null, uncles, 1, null); BlockStore blockStore = new IndexedBlockStore(null, new HashMapDB(), new HashMapBlocksIndex()); blockStore.saveBlock(genesis, new BlockDifficulty(BigInteger.valueOf(1)), true); blockStore.saveBlock(block1, new BlockDifficulty(BigInteger.valueOf(2)), true); BlockUnclesValidationRule rule = new BlockUnclesValidationRule(blockStore, 10, 10, new BlockHeaderCompositeRule(), new BlockHeaderParentCompositeRule()); Assert.assertFalse(rule.isValid(block)); }
@Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; }
BlockUnclesValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; } }
BlockUnclesValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; } BlockUnclesValidationRule( BlockStore blockStore, int uncleListLimit, int uncleGenerationLimit, BlockHeaderValidationRule validations, BlockHeaderParentDependantValidationRule parentValidations); }
BlockUnclesValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; } BlockUnclesValidationRule( BlockStore blockStore, int uncleListLimit, int uncleGenerationLimit, BlockHeaderValidationRule validations, BlockHeaderParentDependantValidationRule parentValidations); @Override boolean isValid(Block block); boolean validateUncleList(long blockNumber, List<BlockHeader> uncles, Set<Keccak256> ancestors, Set<Keccak256> used); }
BlockUnclesValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { if (!blockValidationRule.isValid(block)) { return false; } List<BlockHeader> uncles = block.getUncleList(); if (!uncles.isEmpty() && !validateUncleList(block.getNumber(), uncles, FamilyUtils.getAncestors(blockStore, block, uncleGenerationLimit), FamilyUtils.getUsedUncles(blockStore, block, uncleGenerationLimit))) { logger.warn("Uncles list validation failed"); return false; } return true; } BlockUnclesValidationRule( BlockStore blockStore, int uncleListLimit, int uncleGenerationLimit, BlockHeaderValidationRule validations, BlockHeaderParentDependantValidationRule parentValidations); @Override boolean isValid(Block block); boolean validateUncleList(long blockNumber, List<BlockHeader> uncles, Set<Keccak256> ancestors, Set<Keccak256> used); static final String INVALIDUNCLE; }
@Test public void validWhenCalculatedDifficultyMatches() { whenCalculatedDifficulty(452); whenBlockDifficulty(452); Assert.assertTrue(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; }
BlockDifficultyRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } }
BlockDifficultyRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } BlockDifficultyRule(DifficultyCalculator difficultyCalculator); }
BlockDifficultyRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } BlockDifficultyRule(DifficultyCalculator difficultyCalculator); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockDifficultyRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } BlockDifficultyRule(DifficultyCalculator difficultyCalculator); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void twoTransactionsAndEvents() { PendingTransactionFilter filter = new PendingTransactionFilter(); Account sender = new AccountBuilder().name("sender").build(); Account receiver = new AccountBuilder().name("receiver").build(); Transaction tx1 = new TransactionBuilder() .sender(sender) .receiver(receiver) .value(BigInteger.TEN) .build(); Transaction tx2 = new TransactionBuilder() .sender(sender) .receiver(receiver) .value(BigInteger.ONE) .build(); filter.newPendingTx(tx1); filter.newPendingTx(tx2); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(2, result.length); Assert.assertEquals("0x" + tx1.getHash().toHexString(), result[0]); Assert.assertEquals("0x" + tx2.getHash().toHexString(), result[1]); }
@Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); }
PendingTransactionFilter extends Filter { @Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); } }
PendingTransactionFilter extends Filter { @Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); } }
PendingTransactionFilter extends Filter { @Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); } @Override void newPendingTx(Transaction tx); }
PendingTransactionFilter extends Filter { @Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); } @Override void newPendingTx(Transaction tx); }
@Test public void invalidWhenCalculatedDifficultyDoesntMatch() { whenCalculatedDifficulty(452); whenBlockDifficulty(999); Assert.assertFalse(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; }
BlockDifficultyRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } }
BlockDifficultyRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } BlockDifficultyRule(DifficultyCalculator difficultyCalculator); }
BlockDifficultyRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } BlockDifficultyRule(DifficultyCalculator difficultyCalculator); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockDifficultyRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockDifficultyRule - block or parent are null"); return false; } BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent.getHeader()); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.warn("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } BlockDifficultyRule(DifficultyCalculator difficultyCalculator); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void validForBlocksBeforeRskip110UsingMethodThatReceivesBlockAsParameter() { long blockNumber = 4242; ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mock(ConsensusValidationMainchainView.class), mock(ForkDetectionDataCalculator.class), 449 ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); Block block = mock(Block.class); when(block.getHeader()).thenReturn(header); assertTrue(rule.isValid(header)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
@Test public void validForBlocksBeforeRskip110() { long blockNumber = 4242; ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mock(ConsensusValidationMainchainView.class), mock(ForkDetectionDataCalculator.class), 449 ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); assertTrue(rule.isValid(header)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
@Test public void invalidForRskip110ActiveButForkDetectionData() { long blockNumber = 42; enableRulesAt(blockNumber, ConsensusRule.RSKIP110); ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mock(ConsensusValidationMainchainView.class), mock(ForkDetectionDataCalculator.class), 449 ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); when(header.getMiningForkDetectionData()).thenReturn(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }); assertFalse(rule.isValid(header)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
@Test public void validForRskip110ActiveButNoForkDetectionDataBecauseNoEnoughBlocksToCalculateIt() { long blockNumber = 42; enableRulesAt(blockNumber, ConsensusRule.RSKIP110); ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mock(ConsensusValidationMainchainView.class), mock(ForkDetectionDataCalculator.class), 449 ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); when(header.getMiningForkDetectionData()).thenReturn(new byte[0]); assertTrue(rule.isValid(header)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
@Test public void invalidForRskip110ActiveAndForkDetectionDataButMissingBlocksForCalculation() { long blockNumber = 4242; enableRulesAt(blockNumber, ConsensusRule.RSKIP110); Keccak256 parentBlockHash = new Keccak256(getRandomHash()); int requiredBlocksForForkDataCalculation = 449; ConsensusValidationMainchainView mainchainView = mock(ConsensusValidationMainchainView.class); when(mainchainView.get(parentBlockHash, requiredBlocksForForkDataCalculation)).thenReturn(new ArrayList<>()); ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mainchainView, mock(ForkDetectionDataCalculator.class), requiredBlocksForForkDataCalculation ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); when(header.getParentHash()).thenReturn(parentBlockHash); Keccak256 blockHash = new Keccak256(getRandomHash()); when(header.getHash()).thenReturn(blockHash); byte[] forkDetectionData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; when(header.getMiningForkDetectionData()).thenReturn(forkDetectionData); assertFalse(rule.isValid(header)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
@Test public void validForRskip110ActiveAndForkDetectionData() { long blockNumber = 4242; enableRulesAt(blockNumber, ConsensusRule.RSKIP110); Keccak256 parentBlockHash = new Keccak256(getRandomHash()); int requiredBlocksForForkDataCalculation = 449; List<BlockHeader> previousBlocks = IntStream .range(0, requiredBlocksForForkDataCalculation) .mapToObj(i -> mock(BlockHeader.class)) .collect(Collectors.toList()); ConsensusValidationMainchainView mainchainView = mock(ConsensusValidationMainchainView.class); when(mainchainView.get(parentBlockHash, requiredBlocksForForkDataCalculation)).thenReturn(previousBlocks); ForkDetectionDataCalculator calculator = mock(ForkDetectionDataCalculator.class); Keccak256 blockHash = new Keccak256(getRandomHash()); byte[] forkDetectionData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; when(calculator.calculateWithBlockHeaders(previousBlocks)).thenReturn(forkDetectionData); ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mainchainView, calculator, requiredBlocksForForkDataCalculation ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); when(header.getHash()).thenReturn(blockHash); when(header.getParentHash()).thenReturn(parentBlockHash); when(header.getMiningForkDetectionData()).thenReturn(forkDetectionData); assertTrue(rule.isValid(header)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
@Test public void invalidForRskip110ActiveAndForkDetectionDataBecauseDataDoesNotMatch() { long blockNumber = 4242; enableRulesAt(blockNumber, ConsensusRule.RSKIP110); Keccak256 parentBlockHash = new Keccak256(getRandomHash()); int requiredBlocksForForkDataCalculation = 449; List<BlockHeader> previousBlocks = IntStream .range(0, requiredBlocksForForkDataCalculation) .mapToObj(i -> mock(BlockHeader.class)) .collect(Collectors.toList()); ConsensusValidationMainchainView mainchainView = mock(ConsensusValidationMainchainView.class); when(mainchainView.get(parentBlockHash, requiredBlocksForForkDataCalculation)).thenReturn(previousBlocks); ForkDetectionDataCalculator calculator = mock(ForkDetectionDataCalculator.class); Keccak256 blockHash = new Keccak256(getRandomHash()); byte[] forkDetectionData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; when(calculator.calculateWithBlockHeaders(previousBlocks)).thenReturn(forkDetectionData); ForkDetectionDataRule rule = new ForkDetectionDataRule( activationConfig, mainchainView, calculator, requiredBlocksForForkDataCalculation ); BlockHeader header = mock(BlockHeader.class); when(header.getNumber()).thenReturn(blockNumber); when(header.getHash()).thenReturn(blockHash); when(header.getParentHash()).thenReturn(parentBlockHash); byte[] headerForkDetectionData = new byte[] { 1, 2, 3, 4, 5, 6, 42, 8, 9, 10, 11, 12 }; when(header.getMiningForkDetectionData()).thenReturn(headerForkDetectionData); assertFalse(rule.isValid(header)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
ForkDetectionDataRule implements BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } ForkDetectionDataRule( ActivationConfig activationConfig, ConsensusValidationMainchainView mainchainView, ForkDetectionDataCalculator forkDetectionDataCalculator, int requiredBlocksForForkDetectionDataCalculation); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); }
@Test public void validNonceSame() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 42)); Assert.assertTrue(rule.isValid(block, parent)); }
@Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
@Test public void invalidNonceLower() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 41)); Assert.assertFalse(rule.isValid(block, parent)); }
@Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
@Test public void matchAddress() { Account account = new AccountBuilder().name("account").build(); RskAddress address = account.getAddress(); AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[] { address }, null); Assert.assertTrue(filter.matchesContractAddress(address)); Assert.assertFalse(filter.matchesContractAddress(RskAddress.nullAddress())); }
boolean matchesContractAddress(RskAddress toAddr) { for (RskAddress address : addresses) { if (address.equals(toAddr)) { return true; } } return addresses.length == 0; }
AddressesTopicsFilter { boolean matchesContractAddress(RskAddress toAddr) { for (RskAddress address : addresses) { if (address.equals(toAddr)) { return true; } } return addresses.length == 0; } }
AddressesTopicsFilter { boolean matchesContractAddress(RskAddress toAddr) { for (RskAddress address : addresses) { if (address.equals(toAddr)) { return true; } } return addresses.length == 0; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); }
AddressesTopicsFilter { boolean matchesContractAddress(RskAddress toAddr) { for (RskAddress address : addresses) { if (address.equals(toAddr)) { return true; } } return addresses.length == 0; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
AddressesTopicsFilter { boolean matchesContractAddress(RskAddress toAddr) { for (RskAddress address : addresses) { if (address.equals(toAddr)) { return true; } } return addresses.length == 0; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
@Test public void invalidNonceHigher() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 43)); Assert.assertFalse(rule.isValid(block, parent)); }
@Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
@Test public void validTransactionsWithSameNonceAndDifferentSenders() { RskAddress sender1 = TestUtils.randomAddress(); initialNonce(sender1, 64); RskAddress sender2 = TestUtils.randomAddress(); initialNonce(sender2, 64); Block block = block(transaction(sender1, 64), transaction(sender2, 64)); Assert.assertTrue(rule.isValid(block, parent)); }
@Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
@Test public void validConsecutiveTransactionsFromSameSender() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 42), transaction(sender, 43)); Assert.assertTrue(rule.isValid(block, parent)); }
@Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
@Test public void invalidTransactionsFromSameSenderWithSkippedNonce() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 42), transaction(sender, 44)); Assert.assertFalse(rule.isValid(block, parent)); }
@Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
@Test public void invalidTransactionsWithSameNonceAndSameSender() { RskAddress sender = TestUtils.randomAddress(); initialNonce(sender, 42); Block block = block(transaction(sender, 42), transaction(sender, 42)); Assert.assertFalse(rule.isValid(block, parent)); }
@Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
BlockTxsValidationRule implements BlockParentDependantValidationRule { @Override public boolean isValid(Block block, Block parent) { if(block == null || parent == null) { logger.warn("BlockTxsValidationRule - block or parent are null"); return false; } List<Transaction> txs = block.getTransactionsList(); if (txs.isEmpty()) { return true; } RepositorySnapshot parentRepo = repositoryLocator.snapshotAt(parent.getHeader()); Map<RskAddress, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { try { tx.verify(); } catch (RuntimeException e) { logger.warn("Unable to verify transaction", e); return false; } RskAddress sender = tx.getSender(); BigInteger expectedNonce = curNonce.get(sender); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(sender); } curNonce.put(sender, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(sender), tx); panicProcessor.panic("invalidtransaction", String.format("Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce, expectedNonce, parentRepo.getNonce(sender), tx.getHash())); return false; } } return true; } BlockTxsValidationRule(RepositoryLocator repositoryLocator); @Override boolean isValid(Block block, Block parent); }
@Test public void validWhenGasIsTheSame() { whenGasLimitBoundDivisor(10); whenGasLimit(parentHeader, 1000); whenGasLimit(blockHeader, 1000); Assert.assertTrue(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void validWhenGasIsOnLeftLimit() { whenGasLimitBoundDivisor(10); whenGasLimit(parentHeader, 1000); whenGasLimit(blockHeader, 900); Assert.assertTrue(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void validWhenGasIsOnRightLimit() { whenGasLimitBoundDivisor(20); whenGasLimit(parentHeader, 1000); whenGasLimit(blockHeader, 1050); Assert.assertTrue(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void invalidWhenGasIsOnLeftLimit() { whenGasLimitBoundDivisor(10); whenGasLimit(parentHeader, 1000); whenGasLimit(blockHeader, 899); Assert.assertFalse(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void invalidWhenGasIsOnRightLimit() { whenGasLimitBoundDivisor(20); whenGasLimit(parentHeader, 1000); whenGasLimit(blockHeader, 1051); Assert.assertFalse(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockParentGasLimitRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentGasLimitRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parentHeader.getGasLimit()); if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor - 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) < 0 || headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(gasLimitBoundDivisor + 1L)).divide(BigInteger.valueOf(gasLimitBoundDivisor))) > 0) { logger.warn(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } BlockParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void matchEmptyBloomWithAllFilter() { AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[0], null); Assert.assertTrue(filter.matchBloom(new Bloom())); }
public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
@Test public void blockInThePast() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Mockito.when(header.getTimestamp()) .thenReturn((System.currentTimeMillis() / 1000) - 1000); Assert.assertTrue(validationRule.isValid(header)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void blockInTheFutureLimit() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Mockito.when(header.getTimestamp()) .thenReturn((System.currentTimeMillis() / 1000) + validPeriod); Assert.assertTrue(validationRule.isValid(header)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void blockInTheFuture() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Mockito.when(header.getTimestamp()) .thenReturn((System.currentTimeMillis() / 1000) + 2*validPeriod); Assert.assertFalse(validationRule.isValid(header)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void blockTimeLowerThanParentTime() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Block parent = Mockito.mock(Block.class); Mockito.when(header.getTimestamp()) .thenReturn(System.currentTimeMillis() / 1000); Mockito.when(parent.getTimestamp()) .thenReturn((System.currentTimeMillis() / 1000) + 1000); Assert.assertFalse(validationRule.isValid(header, parent)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void blockTimeGreaterThanParentTime() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Block parent = Mockito.mock(Block.class); Mockito.when(header.getTimestamp()) .thenReturn(System.currentTimeMillis() / 1000); Mockito.when(parent.getTimestamp()) .thenReturn((System.currentTimeMillis() / 1000) - 1000); Assert.assertTrue(validationRule.isValid(header, parent)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void blockTimeEqualsParentTime() { int validPeriod = 540; BlockTimeStampValidationRule validationRule = new BlockTimeStampValidationRule(validPeriod); BlockHeader header = Mockito.mock(BlockHeader.class); Block block = Mockito.mock(Block.class); Mockito.when(block.getHeader()).thenReturn(header); Block parent = Mockito.mock(Block.class); Mockito.when(header.getTimestamp()) .thenReturn(System.currentTimeMillis() / 1000); Mockito.when(parent.getTimestamp()) .thenReturn(System.currentTimeMillis() / 1000); Assert.assertFalse(validationRule.isValid(header, parent)); }
@Override public boolean isValid(Block block) { return isValid(block.getHeader()); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockTimeStampValidationRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule, BlockValidationRule, BlockHeaderValidationRule { @Override public boolean isValid(Block block) { return isValid(block.getHeader()); } BlockTimeStampValidationRule(int validPeriodLength); @Override boolean isValid(Block block); @Override boolean isValid(BlockHeader header); @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void noTxInTheBlock() { Block b = Mockito.mock(Block.class); RemascValidationRule rule = new RemascValidationRule(); Assert.assertFalse(rule.isValid(b)); }
@Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } @Override boolean isValid(Block block); }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } @Override boolean isValid(Block block); }
@Test public void noRemascTxInTheBlock() { Block b = Mockito.mock(Block.class); List<Transaction> tx = new ArrayList<>(); tx.add(new Transaction("0000000000000000000000000000000000000001", BigInteger.ZERO, BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, Constants.REGTEST_CHAIN_ID)); Mockito.when(b.getTransactionsList()).thenReturn(tx); RemascValidationRule rule = new RemascValidationRule(); Assert.assertFalse(rule.isValid(b)); }
@Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } @Override boolean isValid(Block block); }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } @Override boolean isValid(Block block); }
@Test public void remascTxIsNotTheLastOne() { Block b = Mockito.mock(Block.class); List<Transaction> tx = new ArrayList<>(); tx.add(new RemascTransaction(1L)); tx.add(new Transaction("0000000000000000000000000000000000000001", BigInteger.ZERO, BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, Constants.REGTEST_CHAIN_ID)); Mockito.when(b.getTransactionsList()).thenReturn(tx); RemascValidationRule rule = new RemascValidationRule(); Assert.assertFalse(rule.isValid(b)); }
@Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } @Override boolean isValid(Block block); }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } @Override boolean isValid(Block block); }
@Test public void remascTxInBlock() { Block b = Mockito.mock(Block.class); List<Transaction> tx = new ArrayList<>(); tx.add(new Transaction("0000000000000000000000000000000000000001", BigInteger.ZERO, BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, Constants.REGTEST_CHAIN_ID)); tx.add(new RemascTransaction(1L)); Mockito.when(b.getTransactionsList()).thenReturn(tx); RemascValidationRule rule = new RemascValidationRule(); Assert.assertTrue(rule.isValid(b)); }
@Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } @Override boolean isValid(Block block); }
RemascValidationRule implements BlockValidationRule { @Override public boolean isValid(Block block) { List<Transaction> txs = block.getTransactionsList(); boolean result = !txs.isEmpty() && (txs.get(txs.size()-1) instanceof RemascTransaction); if(!result) { logger.warn("Remasc tx not found in block"); panicProcessor.panic("invalidremasctx", "Remasc tx not found in block"); } return result; } @Override boolean isValid(Block block); }
@Test public void noMatchEmptyBloomWithFilterWithAccount() { Account account = new AccountBuilder().name("account").build(); RskAddress address = account.getAddress(); AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[] { address }, null); Assert.assertFalse(filter.matchBloom(new Bloom())); }
public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
@Test public void validWhenNumberIsOneMore() { whenBlockNumber(parentHeader, 451); whenBlockNumber(blockHeader, 452); Assert.assertTrue(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void invalidWhenNumberIsTheSame() { whenBlockNumber(parentHeader, 451); whenBlockNumber(blockHeader, 451); Assert.assertFalse(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void invalidWhenNumberIsLess() { whenBlockNumber(parentHeader, 451); whenBlockNumber(blockHeader, 450); Assert.assertFalse(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void invalidWhenNumberIsMoreThanOne() { whenBlockNumber(parentHeader, 451); whenBlockNumber(blockHeader, 999); Assert.assertFalse(rule.isValid(block, parent)); }
@Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
BlockParentNumberRule implements BlockParentDependantValidationRule, BlockHeaderParentDependantValidationRule { @Override public boolean isValid(BlockHeader header, Block parent) { if (header == null || parent == null) { logger.warn("BlockParentNumberRule - block or parent are null"); return false; } BlockHeader parentHeader = parent.getHeader(); if (header.getNumber() != (parentHeader.getNumber() + 1)) { logger.warn("#{}: block number is not parentBlock number + 1", header.getNumber()); return false; } return true; } @Override boolean isValid(BlockHeader header, Block parent); @Override boolean isValid(Block block, Block parent); }
@Test public void getsSnapshotFromTranslatedStateRoot() { BlockHeader header = mock(BlockHeader.class); Keccak256 stateRoot = TestUtils.randomHash(); when(stateRootHandler.translate(header)).thenReturn(stateRoot); Trie underlyingTrie = mock(Trie.class); when(underlyingTrie.getHash()).thenReturn(TestUtils.randomHash()); when(trieStore.retrieve(stateRoot.getBytes())).thenReturn(Optional.of(underlyingTrie)); RepositorySnapshot actualRepository = target.snapshotAt(header); assertEquals(underlyingTrie.getHash(), new Keccak256(actualRepository.getRoot())); }
public RepositorySnapshot snapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header) .map(MutableRepository::new) .orElseThrow(() -> trieNotFoundException(header)); }
RepositoryLocator { public RepositorySnapshot snapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header) .map(MutableRepository::new) .orElseThrow(() -> trieNotFoundException(header)); } }
RepositoryLocator { public RepositorySnapshot snapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header) .map(MutableRepository::new) .orElseThrow(() -> trieNotFoundException(header)); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); }
RepositoryLocator { public RepositorySnapshot snapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header) .map(MutableRepository::new) .orElseThrow(() -> trieNotFoundException(header)); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header); RepositorySnapshot snapshotAt(BlockHeader header); Repository startTrackingAt(BlockHeader header); }
RepositoryLocator { public RepositorySnapshot snapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header) .map(MutableRepository::new) .orElseThrow(() -> trieNotFoundException(header)); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header); RepositorySnapshot snapshotAt(BlockHeader header); Repository startTrackingAt(BlockHeader header); }
@Test public void findSnapshotAt_notFound() { BlockHeader header = mock(BlockHeader.class); Keccak256 stateRoot = TestUtils.randomHash(); when(stateRootHandler.translate(header)).thenReturn(stateRoot); Trie underlyingTrie = mock(Trie.class); when(underlyingTrie.getHash()).thenReturn(TestUtils.randomHash()); when(trieStore.retrieve(stateRoot.getBytes())).thenReturn(Optional.empty()); Optional<RepositorySnapshot> result = target.findSnapshotAt(header); assertFalse(result.isPresent()); }
public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); }
RepositoryLocator { public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); } }
RepositoryLocator { public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); }
RepositoryLocator { public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header); RepositorySnapshot snapshotAt(BlockHeader header); Repository startTrackingAt(BlockHeader header); }
RepositoryLocator { public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header); RepositorySnapshot snapshotAt(BlockHeader header); Repository startTrackingAt(BlockHeader header); }
@Test public void findSnapshotAt_found() { BlockHeader header = mock(BlockHeader.class); Keccak256 stateRoot = TestUtils.randomHash(); when(stateRootHandler.translate(header)).thenReturn(stateRoot); Trie underlyingTrie = mock(Trie.class); when(underlyingTrie.getHash()).thenReturn(TestUtils.randomHash()); when(trieStore.retrieve(stateRoot.getBytes())).thenReturn(Optional.of(mock(Trie.class))); Optional<RepositorySnapshot> result = target.findSnapshotAt(header); assertTrue(result.isPresent()); }
public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); }
RepositoryLocator { public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); } }
RepositoryLocator { public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); }
RepositoryLocator { public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header); RepositorySnapshot snapshotAt(BlockHeader header); Repository startTrackingAt(BlockHeader header); }
RepositoryLocator { public Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header) { return mutableTrieSnapshotAt(header).map(MutableRepository::new); } RepositoryLocator(TrieStore store, StateRootHandler stateRootHandler); Optional<RepositorySnapshot> findSnapshotAt(BlockHeader header); RepositorySnapshot snapshotAt(BlockHeader header); Repository startTrackingAt(BlockHeader header); }
@Test public void testStorageKeysMixOneLevel() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); MutableTrieCache otherCache = new MutableTrieCache(mtCache); MutableRepository baseRepository = new MutableRepository(baseMutableTrie); MutableRepository cacheRepository = new MutableRepository(mtCache); MutableRepository otherCacheRepository = new MutableRepository(otherCache); RskAddress addr = new RskAddress("b86ca7db8c7ae687ac8d098789987eee12333fc7"); baseRepository.createAccount(addr); baseRepository.setupContract(addr); DataWord sk120 = toStorageKey("120"); DataWord sk121 = toStorageKey("121"); DataWord sk122 = toStorageKey("122"); DataWord sk123 = toStorageKey("123"); DataWord sk124 = toStorageKey("124"); baseRepository.addStorageBytes(addr, sk120, toBytes("HAL")); baseRepository.addStorageBytes(addr, sk121, toBytes("HAL")); baseRepository.addStorageBytes(addr, sk122, toBytes("HAL")); cacheRepository.addStorageBytes(addr, sk120, null); cacheRepository.addStorageBytes(addr, sk121, toBytes("LAH")); cacheRepository.addStorageBytes(addr, sk123, toBytes("LAH")); otherCacheRepository.addStorageBytes(addr, sk124, toBytes("HAL")); Iterator<DataWord> storageKeys = mtCache.getStorageKeys(addr); Set<DataWord> keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertFalse(keys.contains(sk120)); assertTrue(keys.contains(sk121)); assertTrue(keys.contains(sk122)); assertTrue(keys.contains(sk123)); assertFalse(keys.contains(sk124)); assertEquals(3, keys.size()); storageKeys = otherCache.getStorageKeys(addr); keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertFalse(keys.contains(sk120)); assertTrue(keys.contains(sk121)); assertTrue(keys.contains(sk122)); assertTrue(keys.contains(sk123)); assertTrue(keys.contains(sk124)); assertEquals(4, keys.size()); }
public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
@Test public void testStorageKeysNoCache() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); MutableRepository baseRepository = new MutableRepository(baseMutableTrie); RskAddress addr = new RskAddress("b86ca7db8c7ae687ac8d098789987eee12333fc7"); DataWord sk120 = toStorageKey("120"); DataWord sk121 = toStorageKey("121"); baseRepository.addStorageBytes(addr, sk120, toBytes("HAL")); baseRepository.addStorageBytes(addr, sk121, toBytes("HAL")); Iterator<DataWord> storageKeys = mtCache.getStorageKeys(addr); Set<DataWord> keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertTrue(keys.contains(sk120)); assertTrue(keys.contains(sk121)); assertEquals(2, keys.size()); }
public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
@Test public void testStorageKeysNoTrie() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); MutableRepository cacheRepository = new MutableRepository(mtCache); RskAddress addr = new RskAddress("b86ca7db8c7ae687ac8d098789987eee12333fc7"); DataWord skzero = DataWord.ZERO; DataWord sk120 = toStorageKey("120"); DataWord sk121 = toStorageKey("121"); cacheRepository.addStorageBytes(addr, sk120, toBytes("HAL")); cacheRepository.addStorageBytes(addr, sk121, toBytes("HAL")); cacheRepository.addStorageBytes(addr, skzero, toBytes("HAL")); Iterator<DataWord> storageKeys = mtCache.getStorageKeys(addr); Set<DataWord> keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertTrue(keys.contains(sk120)); assertTrue(keys.contains(sk121)); assertTrue(keys.contains(skzero)); assertEquals(3, keys.size()); }
public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
@Test public void noMatchEmptyBloomWithFilterWithTopic() { Topic topic = createTopic(); AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[0], new Topic[][] {{ topic }}); Assert.assertFalse(filter.matchBloom(new Bloom())); }
public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
@Test public void testStorageKeysDeletedAccount() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); MutableRepository cacheRepository = new MutableRepository(mtCache); MutableRepository baseRepository = new MutableRepository(baseMutableTrie); RskAddress addr = new RskAddress("b86ca7db8c7ae687ac8d098789987eee12333fc7"); DataWord sk120 = toStorageKey("120"); DataWord sk121 = toStorageKey("121"); baseRepository.addStorageBytes(addr, sk120, toBytes("HAL")); cacheRepository.delete(addr); Iterator<DataWord> storageKeys = mtCache.getStorageKeys(addr); Set<DataWord> keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertFalse(keys.contains(sk120)); assertFalse(keys.contains(sk121)); assertEquals(0, keys.size()); cacheRepository.addStorageBytes(addr, sk121, toBytes("HAL")); storageKeys = mtCache.getStorageKeys(addr); keys = new HashSet<>(); storageKeys.forEachRemaining(keys::add); assertFalse(keys.contains(sk120)); assertTrue(keys.contains(sk121)); assertEquals(1, keys.size()); }
public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
MutableTrieCache implements MutableTrie { public Iterator<DataWord> getStorageKeys(RskAddress addr) { byte[] accountStoragePrefixKey = trieKeyMapper.getAccountStoragePrefixKey(addr); ByteArrayWrapper accountWrapper = getAccountWrapper(new ByteArrayWrapper(accountStoragePrefixKey)); boolean isDeletedAccount = deleteRecursiveLog.contains(accountWrapper); Map<ByteArrayWrapper, byte[]> accountItems = cache.get(accountWrapper); if (accountItems == null && isDeletedAccount) { return Collections.emptyIterator(); } if (isDeletedAccount) { return new StorageKeysIterator(Collections.emptyIterator(), accountItems, addr, trieKeyMapper); } Iterator<DataWord> storageKeys = trie.getStorageKeys(addr); if (accountItems == null) { return storageKeys; } return new StorageKeysIterator(storageKeys, accountItems, addr, trieKeyMapper); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
@Test public void testGetValueNotStoredAndGetSize() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); byte[] wrongKey = toBytes("BOB"); Uint24 valueLength = baseMutableTrie.getValueLength(wrongKey); assertEquals(Uint24.ZERO, valueLength); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); Uint24 cacheValueLength = mtCache.getValueLength(wrongKey); assertEquals(Uint24.ZERO, cacheValueLength); }
@Override public Uint24 getValueLength(byte[] key) { return internalGet(key, trie::getValueLength, cachedBytes -> new Uint24(cachedBytes.length)).orElse(Uint24.ZERO); }
MutableTrieCache implements MutableTrie { @Override public Uint24 getValueLength(byte[] key) { return internalGet(key, trie::getValueLength, cachedBytes -> new Uint24(cachedBytes.length)).orElse(Uint24.ZERO); } }
MutableTrieCache implements MutableTrie { @Override public Uint24 getValueLength(byte[] key) { return internalGet(key, trie::getValueLength, cachedBytes -> new Uint24(cachedBytes.length)).orElse(Uint24.ZERO); } MutableTrieCache(MutableTrie parentTrie); }
MutableTrieCache implements MutableTrie { @Override public Uint24 getValueLength(byte[] key) { return internalGet(key, trie::getValueLength, cachedBytes -> new Uint24(cachedBytes.length)).orElse(Uint24.ZERO); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
MutableTrieCache implements MutableTrie { @Override public Uint24 getValueLength(byte[] key) { return internalGet(key, trie::getValueLength, cachedBytes -> new Uint24(cachedBytes.length)).orElse(Uint24.ZERO); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
@Test public void testStoreValueOnTrieAndGetHash() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); byte[] value = toBytes("11111111112222222222333333333344"); byte[] key = toBytes("ALICE"); byte[] keyForCache = toBytes("ALICE2"); Keccak256 expectedHash = new Keccak256(Keccak256Helper.keccak256(value)); baseMutableTrie.put(key, value); mtCache.put(keyForCache, value); getValueHashAndAssert(baseMutableTrie, key, expectedHash); getValueHashAndAssert(mtCache, keyForCache, expectedHash); }
@Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); }
MutableTrieCache implements MutableTrie { @Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); } }
MutableTrieCache implements MutableTrie { @Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); } MutableTrieCache(MutableTrie parentTrie); }
MutableTrieCache implements MutableTrie { @Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
MutableTrieCache implements MutableTrie { @Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
@Test public void testStoreEmptyValueOnTrieAndGetHash() { MutableTrieImpl baseMutableTrie = new MutableTrieImpl(null, new Trie()); MutableTrieCache mtCache = new MutableTrieCache(baseMutableTrie); byte[] emptyValue = new byte[0]; byte[] key = toBytes("ALICE"); byte[] keyForCache = toBytes("ALICE2"); Keccak256 emptyHash = new Keccak256(Keccak256Helper.keccak256(emptyValue)); baseMutableTrie.put(key, emptyValue); mtCache.put(keyForCache, emptyValue); getValueHashAndAssert(baseMutableTrie, key, null); getValueHashAndAssert(mtCache, keyForCache, emptyHash); }
@Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); }
MutableTrieCache implements MutableTrie { @Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); } }
MutableTrieCache implements MutableTrie { @Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); } MutableTrieCache(MutableTrie parentTrie); }
MutableTrieCache implements MutableTrie { @Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
MutableTrieCache implements MutableTrie { @Override public void put(byte[] key, byte[] value) { put(new ByteArrayWrapper(key), value); } MutableTrieCache(MutableTrie parentTrie); @Override Trie getTrie(); @Override Keccak256 getHash(); @Override byte[] get(byte[] key); Iterator<DataWord> getStorageKeys(RskAddress addr); @Override void put(byte[] key, byte[] value); @Override void put(ByteArrayWrapper wrapper, byte[] value); @Override void put(String key, byte[] value); @Override void deleteRecursive(byte[] key); @Override void commit(); @Override void save(); @Override void rollback(); @Override Set<ByteArrayWrapper> collectKeys(int size); @Override Uint24 getValueLength(byte[] key); @Override Optional<Keccak256> getValueHash(byte[] key); }
@Test public void verifyFileEmpty() { BootstrapDataVerifier bootstrapDataVerifier = new BootstrapDataVerifier(); assertEquals(0, bootstrapDataVerifier.verifyEntries(new HashMap<>())); }
public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries); }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries); }
@Test public void verifyFileMany() { BootstrapDataVerifier bootstrapDataVerifier = new BootstrapDataVerifier(); HashMap<String, BootstrapDataEntry> entries = new HashMap<>(); List<String> keys = new ArrayList<>(); keys.add("04330037e82c177d7108077c80440821e13c1c62105f85e030214b48d7b5dff0b8e7c158b171546a71139e4de56c8535c964514033b89a669a8e87a5e8770c147c"); keys.add("0473602083afe175e7cae12dbc27da54ec5ac77f99920787f3e891e7af303aaed480770c0de4c991aea1712729260175e158fa73f63c60f0f1de057139c52714de"); keys.add("04bf74915a14e96df0b520a659acc28ae21aada3b0415e35f82f0c7b546338fc48bbfdce858ce3e4690feeb443d7f4955881ba0b793999e4fef7e46732e7fedf02"); String hash = "53cb8e93030183c5ba198433e8cd1f013f3d113e0f4d1756de0d1f124ead155a"; String r1 = "8dba957877d5bdcb26d551dfa2fa509dfe3fe327caf0166130b9f467a0a0c249"; String s1 = "dab3fdf2031515d2de1d420310c69153fcc356f22b50dfd53c6e13e74e346eee"; String r2 = "f0e8aab4fdd83382292a1bbc5480e2ae8084dc245f000f4bc4534d383a3a7919"; String s2 = "a30891f2176bd87b4a3ac5c75167f2442453c17c6e2fbfb36c3b972ee67a4c2d"; String r3 = "00"; String s3 = "00"; entries.put(keys.get(0), new BootstrapDataEntry(1, "", "dbPath", hash, new BootstrapDataSignature(r1, s1))); entries.put(keys.get(1), new BootstrapDataEntry(1, "", "dbPath", hash, new BootstrapDataSignature(r2, s2))); entries.put(keys.get(2), new BootstrapDataEntry(1, "", "dbPath", hash, new BootstrapDataSignature(r3, s3))); assertEquals(2, bootstrapDataVerifier.verifyEntries(entries)); }
public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries); }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries); }
@Test(expected = BootstrapImportException.class) public void doNotVerifyForDifferentHashes() { BootstrapDataVerifier bootstrapDataVerifier = new BootstrapDataVerifier(); HashMap<String, BootstrapDataEntry> entries = new HashMap<>(); List<String> keys = new ArrayList<>(); keys.add("04330037e82c177d7108077c80440821e13c1c62105f85e030214b48d7b5dff0b8e7c158b171546a71139e4de56c8535c964514033b89a669a8e87a5e8770c147c"); keys.add("04dffaa346b18c26230d6050c6ab67f0761ab12136b0dc3a1f1c6ed31890ffac38baa3d8da1df4aa2acc72e45dc3599797ba668666c5395280217f2fd215262b8a"); keys.add("04bf74915a14e96df0b520a659acc28ae21aada3b0415e35f82f0c7b546338fc48bbfdce858ce3e4690feeb443d7f4955881ba0b793999e4fef7e46732e7fedf02"); String hash1 = "53cb8e93030183c5ba198433e8cd1f013f3d113e0f4d1756de0d1f124ead155a"; String hash2 = "87d149cb424c0387656f211d2589fb5b1e16229921309e98588419ccca8a7362"; String hash3 = "53cb8e93030183c5ba198433e8cd1f013f3d113e0f4d1756de0d1f124ead155c"; String r1 = "8dba957877d5bdcb26d551dfa2fa509dfe3fe327caf0166130b9f467a0a0c249"; String s1 = "dab3fdf2031515d2de1d420310c69153fcc356f22b50dfd53c6e13e74e346eee"; String r2 = "0efa8e0738468e434e443676b5a91fe15b0c416ff7190d8d912dff65161ad33c"; String s2 = "aae27edef80e137dc1a0e92b6ae7fed0d1dc1b4a0ea8930bad6abec5ca1297c1"; String r3 = "00"; String s3 = "00"; entries.put(keys.get(0), new BootstrapDataEntry(1, "", "dbPath", hash1, new BootstrapDataSignature(r1, s1))); entries.put(keys.get(1), new BootstrapDataEntry(1, "", "dbPath", hash2, new BootstrapDataSignature(r2, s2))); entries.put(keys.get(2), new BootstrapDataEntry(1, "", "dbPath", hash3, new BootstrapDataSignature(r3, s3))); bootstrapDataVerifier.verifyEntries(entries); }
public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries); }
BootstrapDataVerifier { public int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries) { int verifications = 0; if (selectedEntries.isEmpty()) { return 0; } String hashToVerify = selectedEntries.values().iterator().next().getHash(); byte[] dbHash = Hex.decode(hashToVerify); for (Map.Entry<String, BootstrapDataEntry> entry : selectedEntries.entrySet()) { BootstrapDataEntry bde = entry.getValue(); String currentHash = bde.getHash(); if (!hashToVerify.equals(currentHash)){ throw new BootstrapImportException(String.format( "Error trying to verify different hashes: %s vs %s", hashToVerify, currentHash)); } BootstrapDataSignature bds = bde.getSig(); byte[] publicKey = Hex.decode(entry.getKey()); BigInteger r = new BigInteger(1, Hex.decode(bds.getR())); BigInteger s = new BigInteger(1, Hex.decode(bds.getS())); ECDSASignature signature = new ECDSASignature(r, s); if (Secp256k1.getInstance().verify(dbHash, signature, publicKey)) { verifications++; } } return verifications; } int verifyEntries(Map<String, BootstrapDataEntry> selectedEntries); }
@Test(expected = BootstrapImportException.class) public void retrieveDataInsufficientsSources() { BootstrapDataVerifier bootstrapDataVerifier = mock(BootstrapDataVerifier.class); when(bootstrapDataVerifier.verifyEntries(any())).thenReturn(1); BootstrapFileHandler bootstrapFileHandler = mock(BootstrapFileHandler.class); BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector = mock(BootstrapIndexCandidateSelector.class); Map<String, BootstrapDataEntry> entries = new HashMap<>(); BootstrapIndexCandidateSelector.HeightCandidate mchd = new BootstrapIndexCandidateSelector.HeightCandidate(1L, entries); when(bootstrapIndexCandidateSelector.getHeightData(any())).thenReturn(mchd); BootstrapDataProvider bootstrapDataProvider = new BootstrapDataProvider( bootstrapDataVerifier, bootstrapFileHandler, bootstrapIndexCandidateSelector, mock(BootstrapIndexRetriever.class), 2 ); bootstrapDataProvider.retrieveData(); }
public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); }
BootstrapDataProvider { public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); } }
BootstrapDataProvider { public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); } BootstrapDataProvider( BootstrapDataVerifier bootstrapDataVerifier, BootstrapFileHandler bootstrapFileHandler, BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector, BootstrapIndexRetriever bootstrapIndexRetriever, int minimumRequiredVerifications); }
BootstrapDataProvider { public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); } BootstrapDataProvider( BootstrapDataVerifier bootstrapDataVerifier, BootstrapFileHandler bootstrapFileHandler, BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector, BootstrapIndexRetriever bootstrapIndexRetriever, int minimumRequiredVerifications); void retrieveData(); byte[] getBootstrapData(); long getSelectedHeight(); }
BootstrapDataProvider { public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); } BootstrapDataProvider( BootstrapDataVerifier bootstrapDataVerifier, BootstrapFileHandler bootstrapFileHandler, BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector, BootstrapIndexRetriever bootstrapIndexRetriever, int minimumRequiredVerifications); void retrieveData(); byte[] getBootstrapData(); long getSelectedHeight(); }
@Test public void retrieveData() { BootstrapDataVerifier bootstrapDataVerifier = mock(BootstrapDataVerifier.class); when(bootstrapDataVerifier.verifyEntries(any())).thenReturn(2); BootstrapFileHandler bootstrapFileHandler = mock(BootstrapFileHandler.class); BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector = mock(BootstrapIndexCandidateSelector.class); Map<String, BootstrapDataEntry> entries = new HashMap<>(); BootstrapIndexCandidateSelector.HeightCandidate mchd = new BootstrapIndexCandidateSelector.HeightCandidate(1L, entries); when(bootstrapIndexCandidateSelector.getHeightData(any())).thenReturn(mchd); BootstrapDataProvider bootstrapDataProvider = new BootstrapDataProvider( bootstrapDataVerifier, bootstrapFileHandler, bootstrapIndexCandidateSelector, mock(BootstrapIndexRetriever.class), 2 ); bootstrapDataProvider.retrieveData(); }
public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); }
BootstrapDataProvider { public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); } }
BootstrapDataProvider { public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); } BootstrapDataProvider( BootstrapDataVerifier bootstrapDataVerifier, BootstrapFileHandler bootstrapFileHandler, BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector, BootstrapIndexRetriever bootstrapIndexRetriever, int minimumRequiredVerifications); }
BootstrapDataProvider { public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); } BootstrapDataProvider( BootstrapDataVerifier bootstrapDataVerifier, BootstrapFileHandler bootstrapFileHandler, BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector, BootstrapIndexRetriever bootstrapIndexRetriever, int minimumRequiredVerifications); void retrieveData(); byte[] getBootstrapData(); long getSelectedHeight(); }
BootstrapDataProvider { public void retrieveData() { BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = bootstrapIndexCandidateSelector.getHeightData(getIndices()); Map<String, BootstrapDataEntry> selectedEntries = heightCandidate.getEntries(); verify(heightCandidate); height = heightCandidate.getHeight(); bootstrapFileHandler.setTempDirectory(); bootstrapFileHandler.retrieveAndUnpack(selectedEntries); } BootstrapDataProvider( BootstrapDataVerifier bootstrapDataVerifier, BootstrapFileHandler bootstrapFileHandler, BootstrapIndexCandidateSelector bootstrapIndexCandidateSelector, BootstrapIndexRetriever bootstrapIndexRetriever, int minimumRequiredVerifications); void retrieveData(); byte[] getBootstrapData(); long getSelectedHeight(); }
@Test(expected= BootstrapImportException.class) public void getMaximumCommonHeightDataEmpty() { List<String> keys = Arrays.asList("key1", "key2"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); indexMCH.getHeightData(indexes); }
public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
@Test public void matchAllBloomWithFilterWithTopic() { Topic topic = createTopic(); AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[0], new Topic[][] {{ topic }}); Assert.assertTrue(filter.matchBloom(getAllBloom())); }
public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
@Test public void getValueWhenValueIsEmpty() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); args.value = ""; CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertArrayEquals(new byte[] {0}, byteArrayArgs.getValue()); }
public byte[] getValue() { byte[] value = new byte[] { 0 }; if (args.value != null && args.value.length() != 0) { value = stringHexToByteArray(args.value); } return value; }
CallArgumentsToByteArray { public byte[] getValue() { byte[] value = new byte[] { 0 }; if (args.value != null && args.value.length() != 0) { value = stringHexToByteArray(args.value); } return value; } }
CallArgumentsToByteArray { public byte[] getValue() { byte[] value = new byte[] { 0 }; if (args.value != null && args.value.length() != 0) { value = stringHexToByteArray(args.value); } return value; } CallArgumentsToByteArray(Web3.CallArguments args); }
CallArgumentsToByteArray { public byte[] getValue() { byte[] value = new byte[] { 0 }; if (args.value != null && args.value.length() != 0) { value = stringHexToByteArray(args.value); } return value; } CallArgumentsToByteArray(Web3.CallArguments args); byte[] getGasPrice(); byte[] getGasLimit(); byte[] getToAddress(); byte[] getValue(); byte[] getData(); RskAddress getFromAddress(); }
CallArgumentsToByteArray { public byte[] getValue() { byte[] value = new byte[] { 0 }; if (args.value != null && args.value.length() != 0) { value = stringHexToByteArray(args.value); } return value; } CallArgumentsToByteArray(Web3.CallArguments args); byte[] getGasPrice(); byte[] getGasLimit(); byte[] getToAddress(); byte[] getValue(); byte[] getData(); RskAddress getFromAddress(); }
@Test(expected=BootstrapImportException.class) public void getMaximumCommonHeightDataOneEntry() { List<String> keys = Arrays.asList("key1", "key2"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries = new ArrayList<>(); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); indexes.add(new BootstrapDataIndex(entries)); indexMCH.getHeightData(indexes); }
public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
@Test(expected=BootstrapImportException.class) public void getMaximumCommonHeightDataDuplicatedEntries() { List<String> keys = Arrays.asList("key1", "key2"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries = new ArrayList<>(); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); indexes.add(new BootstrapDataIndex(entries)); indexMCH.getHeightData(indexes); }
public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
@Test public void getMaximumCommonHeightDataTwoEntries() { List<String> keys = Arrays.asList("key1", "key2"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries2 = new ArrayList<>(); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries2.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); indexes.add(new BootstrapDataIndex(entries)); indexes.add(new BootstrapDataIndex(entries2)); BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = indexMCH.getHeightData(indexes); assertEquals(1, heightCandidate.getHeight()); }
public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
@Test public void getMaximumCommonHeightDataThreeEntries() { List<String> keys = Arrays.asList("key1", "key2"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries2 = new ArrayList<>(); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries.add(new BootstrapDataEntry(2, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries2.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); indexes.add(new BootstrapDataIndex(entries)); indexes.add(new BootstrapDataIndex(entries2)); BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = indexMCH.getHeightData(indexes); assertEquals(1, heightCandidate.getHeight()); }
public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
@Test public void getMaximumCommonHeightDataManyEntries() { List<String> keys = Arrays.asList("key1", "key2", "keys3"); BootstrapIndexCandidateSelector indexMCH = new BootstrapIndexCandidateSelector(keys, 2); List<BootstrapDataIndex> indexes = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries2 = new ArrayList<>(); ArrayList<BootstrapDataEntry> entries3 = new ArrayList<>(); entries.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries2.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries3.add(new BootstrapDataEntry(1, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries.add(new BootstrapDataEntry(2, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries2.add(new BootstrapDataEntry(2, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); entries3.add(new BootstrapDataEntry(2, "", "dbPath", "hash", new BootstrapDataSignature("r", "s"))); indexes.add(new BootstrapDataIndex(entries)); indexes.add(new BootstrapDataIndex(entries2)); indexes.add(new BootstrapDataIndex(entries3)); BootstrapIndexCandidateSelector.HeightCandidate heightCandidate = indexMCH.getHeightData(indexes); assertEquals(heightCandidate.getHeight(), 2L); }
public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
BootstrapIndexCandidateSelector { public HeightCandidate getHeightData(List<BootstrapDataIndex> indexes) { Map<Long, Map<String, BootstrapDataEntry>> entriesPerHeight = getEntriesPerHeight(indexes); return getHeightCandidate(entriesPerHeight); } BootstrapIndexCandidateSelector(List<String> publicKeys, int minimumRequiredSources); HeightCandidate getHeightData(List<BootstrapDataIndex> indexes); }
@Test public void retrieveEmpty() { BootstrapIndexRetriever bootstrapIndexRetriever = new BootstrapIndexRetriever( new ArrayList<>(), mock(BootstrapURLProvider.class), mock(ObjectMapper.class) ); List<BootstrapDataIndex> indices = bootstrapIndexRetriever.retrieve(); Assert.assertTrue(indices.isEmpty()); }
public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; }
BootstrapIndexRetriever { public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; } }
BootstrapIndexRetriever { public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; } BootstrapIndexRetriever( List<String> publicKeys, BootstrapURLProvider bootstrapUrlProvider, ObjectMapper objectMapper); }
BootstrapIndexRetriever { public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; } BootstrapIndexRetriever( List<String> publicKeys, BootstrapURLProvider bootstrapUrlProvider, ObjectMapper objectMapper); List<BootstrapDataIndex> retrieve(); }
BootstrapIndexRetriever { public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; } BootstrapIndexRetriever( List<String> publicKeys, BootstrapURLProvider bootstrapUrlProvider, ObjectMapper objectMapper); List<BootstrapDataIndex> retrieve(); }
@Test public void retrievePublicKey() throws IOException { ObjectMapper objectMapper = mock(ObjectMapper.class); BootstrapDataIndex bdi = new BootstrapDataIndex(Collections.singletonList( new BootstrapDataEntry(1, "", "db", "hash", new BootstrapDataSignature("r", "s")))); when(objectMapper.readValue(any(URL.class), eq(BootstrapDataIndex.class))).thenReturn(bdi); BootstrapURLProvider bootstrapUrlProvider = mock(BootstrapURLProvider.class); when(bootstrapUrlProvider.getFullURL(any())).thenReturn(new URL("http: BootstrapIndexRetriever bootstrapIndexRetriever = new BootstrapIndexRetriever( Collections.singletonList("key1"), bootstrapUrlProvider, objectMapper ); List<BootstrapDataIndex> indices = bootstrapIndexRetriever.retrieve(); Assert.assertTrue(indices.contains(bdi)); }
public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; }
BootstrapIndexRetriever { public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; } }
BootstrapIndexRetriever { public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; } BootstrapIndexRetriever( List<String> publicKeys, BootstrapURLProvider bootstrapUrlProvider, ObjectMapper objectMapper); }
BootstrapIndexRetriever { public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; } BootstrapIndexRetriever( List<String> publicKeys, BootstrapURLProvider bootstrapUrlProvider, ObjectMapper objectMapper); List<BootstrapDataIndex> retrieve(); }
BootstrapIndexRetriever { public List<BootstrapDataIndex> retrieve() { List<BootstrapDataIndex> indices = new ArrayList<>(); for (String pk : publicKeys) { String indexSuffix = pk +"/" + INDEX_NAME; URL indexURL = bootstrapUrlProvider.getFullURL(indexSuffix); indices.add(readJson(indexURL)); } return indices; } BootstrapIndexRetriever( List<String> publicKeys, BootstrapURLProvider bootstrapUrlProvider, ObjectMapper objectMapper); List<BootstrapDataIndex> retrieve(); }
@Test public void importData() throws IOException, URISyntaxException { BlockStore blockStore = mock(BlockStore.class); when(blockStore.getMaxNumber()).thenReturn(0L); when(blockStore.isEmpty()).thenReturn(false); BlockFactory blockFactory = mock(BlockFactory.class); TrieStore trieStore = mock(TrieStore.class); BootstrapDataProvider bootstrapDataProvider = mock(BootstrapDataProvider.class); Path path = Paths.get(getClass().getClassLoader().getResource("import/bootstrap-data.bin").toURI()); byte[] oneBlockAndState = Files.readAllBytes(path); when(bootstrapDataProvider.getBootstrapData()).thenReturn(oneBlockAndState); when(bootstrapDataProvider.getSelectedHeight()).thenReturn(1L); BootstrapImporter bootstrapImporter = new BootstrapImporter(blockStore, trieStore, blockFactory, bootstrapDataProvider ); bootstrapImporter.importData(); verify(blockFactory, atLeastOnce()).decodeBlock(any()); }
public void importData() { bootstrapDataProvider.retrieveData(); updateDatabase(); }
BootstrapImporter { public void importData() { bootstrapDataProvider.retrieveData(); updateDatabase(); } }
BootstrapImporter { public void importData() { bootstrapDataProvider.retrieveData(); updateDatabase(); } BootstrapImporter( BlockStore blockStore, TrieStore trieStore, BlockFactory blockFactory, BootstrapDataProvider bootstrapDataProvider); }
BootstrapImporter { public void importData() { bootstrapDataProvider.retrieveData(); updateDatabase(); } BootstrapImporter( BlockStore blockStore, TrieStore trieStore, BlockFactory blockFactory, BootstrapDataProvider bootstrapDataProvider); void importData(); }
BootstrapImporter { public void importData() { bootstrapDataProvider.retrieveData(); updateDatabase(); } BootstrapImporter( BlockStore blockStore, TrieStore trieStore, BlockFactory blockFactory, BootstrapDataProvider bootstrapDataProvider); void importData(); }
@Test public void getFullURL() { String BASE_URL = "http: BootstrapURLProvider bootstrapURLProvider = new BootstrapURLProvider(BASE_URL); String suffix = "suffix"; URL fullURL = bootstrapURLProvider.getFullURL(suffix); try { URL expected = new URL(BASE_URL + suffix); assertEquals(expected, fullURL); } catch (MalformedURLException e) { e.printStackTrace(); } }
public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } }
BootstrapURLProvider { public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } } }
BootstrapURLProvider { public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } } BootstrapURLProvider(String bootstrapBaseURL); }
BootstrapURLProvider { public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } } BootstrapURLProvider(String bootstrapBaseURL); URL getFullURL(String uriSuffix); }
BootstrapURLProvider { public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } } BootstrapURLProvider(String bootstrapBaseURL); URL getFullURL(String uriSuffix); }
@Test(expected=BootstrapImportException.class) public void getWrongFullURL() { String BASE_URL = "localhost/baseURL"; BootstrapURLProvider bootstrapURLProvider = new BootstrapURLProvider(BASE_URL); String suffix = "suffix"; bootstrapURLProvider.getFullURL(suffix); }
public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } }
BootstrapURLProvider { public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } } }
BootstrapURLProvider { public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } } BootstrapURLProvider(String bootstrapBaseURL); }
BootstrapURLProvider { public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } } BootstrapURLProvider(String bootstrapBaseURL); URL getFullURL(String uriSuffix); }
BootstrapURLProvider { public URL getFullURL(String uriSuffix) { try { return new URL(bootstrapBaseURL + uriSuffix); } catch (MalformedURLException e) { throw new BootstrapImportException(String.format( "The defined url for database.import.url %s is not valid", bootstrapBaseURL ), e); } } BootstrapURLProvider(String bootstrapBaseURL); URL getFullURL(String uriSuffix); }
@Test public void matchAllBloomWithFilterWithAccount() { Account account = new AccountBuilder().name("account").build(); RskAddress address = account.getAddress(); AddressesTopicsFilter filter = new AddressesTopicsFilter(new RskAddress[] { address }, null); Assert.assertTrue(filter.matchBloom(getAllBloom())); }
public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
AddressesTopicsFilter { public boolean matchBloom(Bloom blockBloom) { for (Bloom[] andBloom : filterBlooms) { boolean orMatches = false; for (Bloom orBloom : andBloom) { if (blockBloom.matches(orBloom)) { orMatches = true; break; } } if (!orMatches) { return false; } } return true; } AddressesTopicsFilter(RskAddress[] addresses, Topic[][] topics); boolean matchBloom(Bloom blockBloom); boolean matchesExactly(LogInfo logInfo); }
@Test(expected = IllegalStateException.class) public void getMinNumber_emptyIndex() { target.getMinNumber(); }
@Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; } }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; } MapDBBlocksIndex(DB indexDB); }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
@Test public void getMinNumber_nonEmptyIndex() { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(9)); index.put(9L, new ArrayList<>()); index.put(8L, new ArrayList<>()); assertEquals(8L, target.getMinNumber()); }
@Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; } }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; } MapDBBlocksIndex(DB indexDB); }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMinNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return getMaxNumber() - index.size() + 1; } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
@Test(expected = IllegalStateException.class) public void getMaxNumber_emptyIndex() { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(9)); target.getMaxNumber(); }
@Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); } }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); } MapDBBlocksIndex(DB indexDB); }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
@Test public void getMaxNumber() { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(9)); index.put(9L, new ArrayList<>()); assertEquals(target.getMaxNumber(),9); }
@Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); } }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); } MapDBBlocksIndex(DB indexDB); }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
MapDBBlocksIndex implements BlocksIndex { @Override public long getMaxNumber() { if (index.isEmpty()) { throw new IllegalStateException("Index is empty"); } return ByteUtil.byteArrayToLong(metadata.get(MAX_BLOCK_NUMBER_KEY)); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
@Test public void contains_true() { long blockNumber = 12; index.put(blockNumber, new ArrayList<>()); assertTrue(target.contains(blockNumber)); }
@Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); } }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); } MapDBBlocksIndex(DB indexDB); }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
@Test public void contains_false() { long blockNumber = 12; assertFalse(target.contains(blockNumber)); }
@Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); } }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); } MapDBBlocksIndex(DB indexDB); }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean contains(long blockNumber) { return index.containsKey(blockNumber); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
@Test public void getBlocksByNumber_found() { long blockNumber = 20; List<IndexedBlockStore.BlockInfo> expectedResult = mock(List.class); index.put(blockNumber, expectedResult); List<IndexedBlockStore.BlockInfo> result = target.getBlocksByNumber(blockNumber); assertEquals(expectedResult, result); }
@Override public List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber) { return index.getOrDefault(blockNumber, new ArrayList<>()); }
MapDBBlocksIndex implements BlocksIndex { @Override public List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber) { return index.getOrDefault(blockNumber, new ArrayList<>()); } }
MapDBBlocksIndex implements BlocksIndex { @Override public List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber) { return index.getOrDefault(blockNumber, new ArrayList<>()); } MapDBBlocksIndex(DB indexDB); }
MapDBBlocksIndex implements BlocksIndex { @Override public List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber) { return index.getOrDefault(blockNumber, new ArrayList<>()); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
MapDBBlocksIndex implements BlocksIndex { @Override public List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber) { return index.getOrDefault(blockNumber, new ArrayList<>()); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
@Test(expected = IllegalArgumentException.class) public void putBlocks_nullList() { target.putBlocks(20L, null); }
@Override public void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks) { if (blocks == null || blocks.isEmpty()) { throw new IllegalArgumentException("Block list cannot be empty nor null."); } long maxNumber = -1; if (index.size() > 0) { maxNumber = getMaxNumber(); } if (blockNumber > maxNumber) { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(blockNumber)); } index.put(blockNumber, blocks); }
MapDBBlocksIndex implements BlocksIndex { @Override public void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks) { if (blocks == null || blocks.isEmpty()) { throw new IllegalArgumentException("Block list cannot be empty nor null."); } long maxNumber = -1; if (index.size() > 0) { maxNumber = getMaxNumber(); } if (blockNumber > maxNumber) { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(blockNumber)); } index.put(blockNumber, blocks); } }
MapDBBlocksIndex implements BlocksIndex { @Override public void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks) { if (blocks == null || blocks.isEmpty()) { throw new IllegalArgumentException("Block list cannot be empty nor null."); } long maxNumber = -1; if (index.size() > 0) { maxNumber = getMaxNumber(); } if (blockNumber > maxNumber) { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(blockNumber)); } index.put(blockNumber, blocks); } MapDBBlocksIndex(DB indexDB); }
MapDBBlocksIndex implements BlocksIndex { @Override public void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks) { if (blocks == null || blocks.isEmpty()) { throw new IllegalArgumentException("Block list cannot be empty nor null."); } long maxNumber = -1; if (index.size() > 0) { maxNumber = getMaxNumber(); } if (blockNumber > maxNumber) { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(blockNumber)); } index.put(blockNumber, blocks); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
MapDBBlocksIndex implements BlocksIndex { @Override public void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks) { if (blocks == null || blocks.isEmpty()) { throw new IllegalArgumentException("Block list cannot be empty nor null."); } long maxNumber = -1; if (index.size() > 0) { maxNumber = getMaxNumber(); } if (blockNumber > maxNumber) { metadata.put(MAX_BLOCK_NUMBER_KEY, ByteUtil.longToBytes(blockNumber)); } index.put(blockNumber, blocks); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
@Test public void isEmpty_empty() { assertTrue(target.isEmpty()); }
@Override public boolean isEmpty() { return index.isEmpty(); }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean isEmpty() { return index.isEmpty(); } }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean isEmpty() { return index.isEmpty(); } MapDBBlocksIndex(DB indexDB); }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean isEmpty() { return index.isEmpty(); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
MapDBBlocksIndex implements BlocksIndex { @Override public boolean isEmpty() { return index.isEmpty(); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
@Test public void flush() { target.flush(); verify(indexDB, times(1)).commit(); }
@Override public void flush() { indexDB.commit(); }
MapDBBlocksIndex implements BlocksIndex { @Override public void flush() { indexDB.commit(); } }
MapDBBlocksIndex implements BlocksIndex { @Override public void flush() { indexDB.commit(); } MapDBBlocksIndex(DB indexDB); }
MapDBBlocksIndex implements BlocksIndex { @Override public void flush() { indexDB.commit(); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
MapDBBlocksIndex implements BlocksIndex { @Override public void flush() { indexDB.commit(); } MapDBBlocksIndex(DB indexDB); @Override boolean isEmpty(); @Override long getMaxNumber(); @Override long getMinNumber(); @Override boolean contains(long blockNumber); @Override List<IndexedBlockStore.BlockInfo> getBlocksByNumber(long blockNumber); @Override void putBlocks(long blockNumber, List<IndexedBlockStore.BlockInfo> blocks); @Override List<IndexedBlockStore.BlockInfo> removeLast(); @Override void flush(); @Override void close(); }
@Test public void mimeTest() { final String SIMPLE_CONTENT_TYPE = "text/html"; final String NORMAL_CONTENT_TYPE = "text/html; charset=utf-8"; HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders headers = message.headers(); String contentType = HttpHeaders.Names.CONTENT_TYPE; Assert.assertNull(HttpUtils.getMimeType(headers.get(contentType))); headers.set(contentType, ""); Assert.assertNull(HttpUtils.getMimeType(headers.get(contentType))); Assert.assertNull(HttpUtils.getMimeType("")); headers.set(contentType, SIMPLE_CONTENT_TYPE); Assert.assertEquals("text/html", HttpUtils.getMimeType(headers.get(contentType))); Assert.assertEquals("text/html", HttpUtils.getMimeType(SIMPLE_CONTENT_TYPE)); headers.set(contentType, NORMAL_CONTENT_TYPE); Assert.assertEquals("text/html", HttpUtils.getMimeType(headers.get(contentType))); Assert.assertEquals("text/html", HttpUtils.getMimeType(NORMAL_CONTENT_TYPE)); }
public static String getMimeType(String contentTypeValue) { if (contentTypeValue == null) { return null; } int indexOfSemicolon = contentTypeValue.indexOf(';'); if (indexOfSemicolon != -1) { return contentTypeValue.substring(0, indexOfSemicolon); } else { return contentTypeValue.length() > 0 ? contentTypeValue : null; } }
HttpUtils { public static String getMimeType(String contentTypeValue) { if (contentTypeValue == null) { return null; } int indexOfSemicolon = contentTypeValue.indexOf(';'); if (indexOfSemicolon != -1) { return contentTypeValue.substring(0, indexOfSemicolon); } else { return contentTypeValue.length() > 0 ? contentTypeValue : null; } } }
HttpUtils { public static String getMimeType(String contentTypeValue) { if (contentTypeValue == null) { return null; } int indexOfSemicolon = contentTypeValue.indexOf(';'); if (indexOfSemicolon != -1) { return contentTypeValue.substring(0, indexOfSemicolon); } else { return contentTypeValue.length() > 0 ? contentTypeValue : null; } } }
HttpUtils { public static String getMimeType(String contentTypeValue) { if (contentTypeValue == null) { return null; } int indexOfSemicolon = contentTypeValue.indexOf(';'); if (indexOfSemicolon != -1) { return contentTypeValue.substring(0, indexOfSemicolon); } else { return contentTypeValue.length() > 0 ? contentTypeValue : null; } } static String getMimeType(String contentTypeValue); }
HttpUtils { public static String getMimeType(String contentTypeValue) { if (contentTypeValue == null) { return null; } int indexOfSemicolon = contentTypeValue.indexOf(';'); if (indexOfSemicolon != -1) { return contentTypeValue.substring(0, indexOfSemicolon); } else { return contentTypeValue.length() > 0 ? contentTypeValue : null; } } static String getMimeType(String contentTypeValue); }
@Test public void getCliArgsSmokeTest() { RskTestContext devnetContext = new RskTestContext(new String[] { "--devnet" }); assertThat(devnetContext.getCliArgs(), notNullValue()); assertThat(devnetContext.getCliArgs().getFlags(), contains(NodeCliFlags.NETWORK_DEVNET)); }
public CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs() { return cliArgs; }
RskContext implements NodeBootstrapper { public CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs() { return cliArgs; } }
RskContext implements NodeBootstrapper { public CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs() { return cliArgs; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); }
RskContext implements NodeBootstrapper { public CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs() { return cliArgs; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
RskContext implements NodeBootstrapper { public CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs() { return cliArgs; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
@Test public void shouldBuildSimpleTrieStore() throws IOException { Path testDatabasesDirectory = databaseDir.getRoot().toPath(); doReturn(new GarbageCollectorConfig(false, 1000, 3)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); TrieStore trieStore = rskContext.getTrieStore(); Assert.assertThat(trieStore, is(instanceOf(TrieStoreImpl.class))); Assert.assertThat(Files.list(testDatabasesDirectory).count(), is(1L)); }
public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
@Test public void shouldBuildSimpleTrieStoreCleaningUpMultiTrieStore() throws IOException, InterruptedException { Path testDatabasesDirectory = databaseDir.getRoot().toPath(); doReturn(new GarbageCollectorConfig(false, 1000, 3)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); long preExistingEpochs = 4; for (int i = 0; i < preExistingEpochs; i++) { Files.createDirectory(testDatabasesDirectory.resolve(String.format("unitrie_%d", i))); } Assert.assertThat(Files.list(testDatabasesDirectory).count(), is(preExistingEpochs)); TrieStore trieStore = rskContext.getTrieStore(); Assert.assertThat(trieStore, is(instanceOf(TrieStoreImpl.class))); Assert.assertThat(Files.list(testDatabasesDirectory).count(), is(1L)); }
public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
@Test public void shouldBuildMultiTrieStore() throws IOException { long numberOfEpochs = 3; Path testDatabasesDirectory = databaseDir.getRoot().toPath(); doReturn(new GarbageCollectorConfig(true, 1000, (int) numberOfEpochs)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); TrieStore trieStore = rskContext.getTrieStore(); Assert.assertThat(trieStore, is(instanceOf(MultiTrieStore.class))); Assert.assertThat(Files.list(testDatabasesDirectory).count(), is(numberOfEpochs)); }
public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
@Test public void shouldBuildMultiTrieStoreMigratingSingleTrieStore() throws IOException { long numberOfEpochs = 3; Path testDatabasesDirectory = databaseDir.getRoot().toPath(); doReturn(new GarbageCollectorConfig(true, 1000, (int) numberOfEpochs)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); Files.createDirectory(testDatabasesDirectory.resolve("unitrie")); TrieStore trieStore = rskContext.getTrieStore(); Assert.assertThat(trieStore, is(instanceOf(MultiTrieStore.class))); Assert.assertThat(Files.list(testDatabasesDirectory).count(), is(numberOfEpochs)); Assert.assertThat(Files.list(testDatabasesDirectory).noneMatch(p -> p.getFileName().toString().equals("unitrie")), is(true)); }
public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
@Test public void shouldBuildMultiTrieStoreFromExistingDirectories() throws IOException { int numberOfEpochs = 3; Path testDatabasesDirectory = databaseDir.getRoot().toPath(); doReturn(new GarbageCollectorConfig(true, 1000, numberOfEpochs)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); int initialEpoch = 3; for (int i = initialEpoch; i < initialEpoch + numberOfEpochs; i++) { Files.createDirectory(testDatabasesDirectory.resolve(String.format("unitrie_%d", i))); } TrieStore trieStore = rskContext.getTrieStore(); Assert.assertThat(trieStore, is(instanceOf(MultiTrieStore.class))); Assert.assertThat(Files.list(testDatabasesDirectory).count(), is((long) numberOfEpochs)); int[] directorySufixes = Files.list(testDatabasesDirectory) .map(Path::getFileName) .map(Path::toString) .map(fileName -> fileName.replaceAll("unitrie_", "")) .mapToInt(Integer::valueOf) .sorted() .toArray(); Assert.assertThat(directorySufixes, is(IntStream.range(initialEpoch, initialEpoch + numberOfEpochs).toArray())); }
public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
@Test(expected = IllegalStateException.class) @Ignore("Permissions set fails under CircleCI") public void shouldFailIfCannotBuildMultiTrieStore() throws IOException { Path testDatabasesDirectory = Files.createTempDirectory("test", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("---------"))); doReturn(new GarbageCollectorConfig(true, 1000, 3)).when(testProperties).garbageCollectorConfig(); doReturn(testDatabasesDirectory.toString()).when(testProperties).databaseDir(); RskContext rskContext = new RskContext(new String[0]) { @Override public RskSystemProperties getRskSystemProperties() { return testProperties; } }; rskContext.getTrieStore(); }
public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }
RskContext implements NodeBootstrapper { public TrieStore getTrieStore() { if (trieStore == null) { trieStore = buildAbstractTrieStore(Paths.get(getRskSystemProperties().databaseDir())); } return trieStore; } RskContext(String[] args); private RskContext(CliArgs<NodeCliOptions, NodeCliFlags> cliArgs); BootstrapImporter getBootstrapImporter(); @Override NodeRunner getNodeRunner(); Blockchain getBlockchain(); MiningMainchainView getMiningMainchainView(); ConsensusValidationMainchainView getConsensusValidationMainchainView(); BlockFactory getBlockFactory(); TransactionPool getTransactionPool(); ReceivedTxSignatureCache getReceivedTxSignatureCache(); RepositoryLocator getRepositoryLocator(); StateRootHandler getStateRootHandler(); TrieConverter getTrieConverter(); ReceiptStore getReceiptStore(); TrieStore getTrieStore(); BlockExecutor getBlockExecutor(); PrecompiledContracts getPrecompiledContracts(); BridgeSupportFactory getBridgeSupportFactory(); BtcBlockStoreWithCache.Factory getBtcBlockStoreFactory(); org.ethereum.db.BlockStore getBlockStore(); Ethereum getRsk(); ReversibleTransactionExecutor getReversibleTransactionExecutor(); TransactionExecutorFactory getTransactionExecutorFactory(); NodeBlockProcessor getNodeBlockProcessor(); RskSystemProperties getRskSystemProperties(); PeerScoringManager getPeerScoringManager(); HashRateCalculator getHashRateCalculator(); EthModule getEthModule(); EvmModule getEvmModule(); PeerServer getPeerServer(); PersonalModule getPersonalModule(); CliArgs<NodeCliOptions, NodeCliFlags> getCliArgs(); BuildInfo getBuildInfo(); ChannelManager getChannelManager(); ConfigCapabilities getConfigCapabilities(); DebugModule getDebugModule(); TraceModule getTraceModule(); MnrModule getMnrModule(); TxPoolModule getTxPoolModule(); RskModule getRskModule(); NetworkStateExporter getNetworkStateExporter(); MinerClient getMinerClient(); MinerServer getMinerServer(); ProgramInvokeFactory getProgramInvokeFactory(); CompositeEthereumListener getCompositeEthereumListener(); BlocksBloomStore getBlocksBloomStore(); List<InternalService> buildInternalServices(); GenesisLoader getGenesisLoader(); Genesis getGenesis(); Wallet getWallet(); BlockValidationRule getBlockValidationRule(); BlockParentDependantValidationRule getBlockParentDependantValidationRule(); org.ethereum.db.BlockStore buildBlockStore(String databaseDir); }