src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
NativeContract extends PrecompiledContracts.PrecompiledContract { public ExecutionEnvironment getExecutionEnvironment() { return executionEnvironment; } NativeContract(ActivationConfig activationConfig, RskAddress contractAddress); ExecutionEnvironment getExecutionEnvironment(); abstract List<NativeMethod> getMethods()...
@Test public void createsExecutionEnvironmentUponInit() { Assert.assertNull(contract.getExecutionEnvironment()); doInit(); ExecutionEnvironment executionEnvironment = contract.getExecutionEnvironment(); Assert.assertNotNull(executionEnvironment); Assert.assertEquals(tx, executionEnvironment.getTransaction()); Assert.as...
NativeContract extends PrecompiledContracts.PrecompiledContract { @Override public long getGasForData(byte[] data) { if (executionEnvironment == null) { throw new RuntimeException("Execution environment is null"); } Optional<NativeMethod.WithArguments> methodWithArguments = parseData(data); if (!methodWithArguments.isP...
@Test public void getGasForDataFailsWhenNoInit() { assertFails(() -> contract.getGasForData(Hex.decode("aabb"))); } @Test public void getGasForDataZeroWhenNullData() { doInit(); Assert.assertEquals(0L, contract.getGasForData(null)); } @Test public void getGasForDataZeroWhenEmptyData() { doInit(); Assert.assertEquals(0L...
Migrator { public String migrateConfiguration() throws IOException { return migrateConfiguration( Files.newBufferedReader(configuration.getSourceConfiguration(), StandardCharsets.UTF_8), configuration.getMigrationConfiguration() ); } Migrator(MigratorConfiguration configuration); String migrateConfiguration(); static S...
@Test public void migrateConfiguration() { Reader initialConfiguration = new StringReader("inline.config.name=\"value\"\n" + "nested {\n" + " nested = {\n" + " #test comment\n" + " config = 13\n" + " }\n" + "}\n" + "flat.config = \"0.0.0.0\"\n" + "another.config=\"don't change\""); Properties migrationProperties = new ...
PeerScoringManager { public boolean hasGoodReputation(NodeID id) { synchronized (accessLock) { return this.getPeerScoring(id).hasGoodReputation(); } } PeerScoringManager( PeerScoring.Factory peerScoringFactory, int nodePeersSize, PunishmentParameters nodeParameters, Punis...
@Test public void newNodeHasGoodReputation() { NodeID id = generateNodeID(); PeerScoringManager manager = createPeerScoringManager(); Assert.assertTrue(manager.hasGoodReputation(id)); } @Test public void newAddressHasGoodReputation() throws UnknownHostException { InetAddress address = generateIPAddressV4(); PeerScoring...
ByteUtil { @Nonnull public static String toHexStringOrEmpty(@Nullable byte[] data) { return data == null ? "" : toHexString(data); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] big...
@Test public void testToHexStringOrEmpty_EmptyStringForNull() { assertEquals("", ByteUtil.toHexStringOrEmpty(null)); }
PunishmentCalculator { public long calculate(int punishmentCounter, int score) { long result = this.parameters.getDuration(); long rate = 100L + this.parameters.getIncrementRate(); int counter = punishmentCounter; long maxDuration = this.parameters.getMaximumDuration(); while (counter-- > 0) { result = multiplyExact(re...
@Test public void calculatePunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(100, calculator.calculate(0, 0)); } @Test public void calculatePunishmentTimeWithNegativeScore() { PunishmentCalculator calculator = new PunishmentCalcul...
PeerScoring { public boolean hasGoodReputation() { try { rwlock.writeLock().lock(); if (this.goodReputation) { return true; } if (this.punishmentTime > 0 && this.timeLostGoodReputation > 0 && this.punishmentTime + this.timeLostGoodReputation <= System.currentTimeMillis()) { this.endPunishment(); } return this.goodReput...
@Test public void newStatusHasGoodReputation() { PeerScoring scoring = new PeerScoring(); Assert.assertTrue(scoring.hasGoodReputation()); }
PeerScoring { public int getScore() { try { rwlock.readLock().lock(); return score; } finally { rwlock.readLock().unlock(); } } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); bool...
@Test public void getInformationFromNewScoring() { PeerScoring scoring = new PeerScoring(); PeerScoringInformation info = new PeerScoringInformation(scoring, "nodeid", "node"); Assert.assertTrue(info.getGoodReputation()); Assert.assertEquals(0, info.getValidBlocks()); Assert.assertEquals(0, info.getInvalidBlocks()); As...
PeerScoring { @VisibleForTesting public long getTimeLostGoodReputation() { return this.timeLostGoodReputation; } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodRepu...
@Test public void newStatusHasNoTimeLostGoodReputation() { PeerScoring scoring = new PeerScoring(); Assert.assertEquals(0, scoring.getTimeLostGoodReputation()); }
ByteUtil { public static byte[] calcPacketLength(byte[] msg) { int msgLen = msg.length; return new byte[]{ (byte) ((msgLen >> 24) & 0xFF), (byte) ((msgLen >> 16) & 0xFF), (byte) ((msgLen >> 8) & 0xFF), (byte) ((msgLen) & 0xFF)}; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneB...
@Test public void testCalcPacketLength() { byte[] test = new byte[]{0x0f, 0x10, 0x43}; byte[] expected = new byte[]{0x00, 0x00, 0x00, 0x03}; assertArrayEquals(expected, ByteUtil.calcPacketLength(test)); }
Web3Impl implements Web3 { @Override public String web3_sha3(String data) throws Exception { String s = null; try { byte[] result = HashUtil.keccak256(data.getBytes(StandardCharsets.UTF_8)); return s = TypeConverter.toJsonHex(result); } finally { if (logger.isDebugEnabled()) { logger.debug("web3_sha3({}): {}", data, s)...
@Test public void web3_sha3() throws Exception { String toHash = "RSK"; Web3 web3 = createWeb3(); String result = web3.web3_sha3(toHash); assertTrue("hash does not match", result.compareTo("0x80553b6b348ae45ab8e8bf75e77064818c0a772f13cf8d3a175d3815aec59b56") == 0); }
PeerScoring { public void recordEvent(EventType evt) { try { rwlock.writeLock().lock(); counters[evt.ordinal()]++; switch (evt) { case INVALID_NETWORK: case INVALID_BLOCK: case INVALID_TRANSACTION: case INVALID_MESSAGE: case INVALID_HEADER: if (score > 0) { score = 0; } score--; break; case UNEXPECTED_MESSAGE: case FAI...
@Test public void recordEvent() { PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.INVALID_BLOCK); Assert.assertEquals(1, scoring.getEventCounter(EventType.INVALID_BLOCK)); Assert.assertEquals(0, scoring.getEventCounter(EventType.INVALID_TRANSACTION)); Assert.assertEquals(1, scoring.getTotalEventC...
PeerScoring { @VisibleForTesting public void startPunishment(long expirationTime) { if (!punishmentEnabled) { return; } try { rwlock.writeLock().lock(); this.goodReputation = false; this.punishmentTime = expirationTime; this.punishmentCounter++; this.timeLostGoodReputation = System.currentTimeMillis(); } finally { rwlo...
@Test public void startPunishment() throws InterruptedException { PeerScoring scoring = new PeerScoring(); Assert.assertEquals(0, scoring.getPunishmentTime()); Assert.assertEquals(0, scoring.getPunishmentCounter()); scoring.startPunishment(1000); Assert.assertEquals(1, scoring.getPunishmentCounter()); Assert.assertFals...
InetAddressBlock { public boolean contains(InetAddress address) { byte[] addressBytes = address.getAddress(); if (addressBytes.length != this.bytes.length) { return false; } int k; for (k = 0; k < this.nbytes; k++) { if (addressBytes[k] != this.bytes[k]) { return false; } } if (this.mask != (byte)0xff) { return (addres...
@Test public void recognizeIPV4AddressMask8Bits() throws UnknownHostException { InetAddress address = generateIPAddressV4(); InetAddressBlock mask = new InetAddressBlock(address, 8); Assert.assertTrue(mask.contains(address)); } @Test public void containsIPV4() throws UnknownHostException { InetAddress address = generat...
ByteUtil { public static long byteArrayToLong(byte[] b) { if (b == null || b.length == 0) { return 0; } if (b.length > 8) { throw new IllegalArgumentException("byte array can't have more than 8 bytes if it is to be cast to long"); } long result = 0; for (int i = 0; i < b.length; i++) { result <<= 8; result |= (b[i] & 0...
@Test public void testByteArrayToLong() { assertEquals(Long.MAX_VALUE, ByteUtil.byteArrayToLong(new byte[]{ (byte)127, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, } )); assertEquals(0, ByteUtil.byteArrayToLong(new byte[]{ } )); } @Test(expected = IllegalArgumentException.class) public v...
InetAddressBlock { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof InetAddressBlock)) { return false; } InetAddressBlock block = (InetAddressBlock)obj; return block.mask == this.mask && Arrays.equals(block.bytes, this.bytes); } InetAddressBlock(InetAddress address, ...
@Test public void equals() throws UnknownHostException { InetAddress address1 = generateIPAddressV4(); InetAddress address2 = alterByte(address1, 0); InetAddress address3 = generateIPAddressV6(); InetAddressBlock block1 = new InetAddressBlock(address1, 8); InetAddressBlock block2 = new InetAddressBlock(address2, 9); In...
InetAddressTable { public boolean contains(InetAddress address) { if (this.addresses.contains(address)) { return true; } if (this.blocks.isEmpty()) { return false; } InetAddressBlock[] bs = this.blocks.toArray(new InetAddressBlock[0]); for (InetAddressBlock mask : bs) { if (mask.contains(address)) { return true; } } re...
@Test public void doesNotContainsNewIPV4Address() throws UnknownHostException { InetAddressTable table = new InetAddressTable(); Assert.assertFalse(table.contains(generateIPAddressV4())); } @Test public void doesNotContainsNewIPV6Address() throws UnknownHostException { InetAddressTable table = new InetAddressTable(); A...
InetAddressUtils { public static boolean hasMask(String text) { if (text == null) { return false; } String[] parts = text.split("/"); return parts.length == 2 && parts[0].length() != 0 && parts[1].length() != 0; } private InetAddressUtils(); static boolean hasMask(String text); static InetAddress getAddressForBan(@Che...
@Test public void hasMask() { Assert.assertFalse(InetAddressUtils.hasMask(null)); Assert.assertFalse(InetAddressUtils.hasMask("/")); Assert.assertFalse(InetAddressUtils.hasMask("1234/")); Assert.assertFalse(InetAddressUtils.hasMask("/1234")); Assert.assertFalse(InetAddressUtils.hasMask("1234/1234/1234")); Assert.assert...
InetAddressUtils { public static InetAddress getAddressForBan(@CheckForNull String hostname) throws InvalidInetAddressException { if (hostname == null) { throw new InvalidInetAddressException("null address", null); } String name = hostname.trim(); if (name.length() == 0) { throw new InvalidInetAddressException("empty a...
@Test public void getAddressFromIPV4() throws InvalidInetAddressException { InetAddress address = InetAddressUtils.getAddressForBan("192.168.56.1"); Assert.assertNotNull(address); byte[] bytes = address.getAddress(); Assert.assertNotNull(bytes); Assert.assertEquals(4, bytes.length); Assert.assertArrayEquals(new byte[] ...
InetAddressUtils { public static InetAddressBlock parse(String text) throws InvalidInetAddressException { String[] parts = text.split("/"); InetAddress address; address = InetAddressUtils.getAddressForBan(parts[0]); int nbits; try { nbits = Integer.parseInt(parts[1]); } catch (NumberFormatException ex) { throw new Inva...
@Test public void parseAddressBlock() throws InvalidInetAddressException, InvalidInetAddressBlockException, UnknownHostException { InetAddressBlock result = InetAddressUtils.parse("192.162.12.0/8"); Assert.assertNotNull(result); Assert.assertArrayEquals(InetAddress.getByName("192.162.12.0").getAddress(), result.getByte...
ByteUtil { public static int byteArrayToInt(byte[] b) { if (b == null || b.length == 0) { return 0; } return new BigInteger(1, b).intValue(); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static...
@Test public void testByteArrayToInt() { assertEquals(0, ByteUtil.byteArrayToInt(null)); assertEquals(0, ByteUtil.byteArrayToInt(new byte[0])); }
ScoringCalculator { public boolean hasGoodReputation(PeerScoring scoring) { return scoring.getEventCounter(EventType.INVALID_BLOCK) < 1 && scoring.getEventCounter(EventType.INVALID_MESSAGE) < 1 && scoring.getEventCounter(EventType.INVALID_HEADER) < 1; } boolean hasGoodReputation(PeerScoring scoring); }
@Test public void emptyScoringHasGoodReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); Assert.assertTrue(calculator.hasGoodReputation(scoring)); } @Test public void scoringWithOneValidBlockHasGoodReputation() { ScoringCalculator calculator = new ScoringCalcu...
ByteUtil { public static int numBytes(String val) { return new BigInteger(val).bitLength() / 8 + 1; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value...
@Test public void testNumBytes() { String test1 = "0"; String test2 = "1"; String test3 = "1000000000"; int expected1 = 1; int expected2 = 1; int expected3 = 4; assertEquals(expected1, ByteUtil.numBytes(test1)); assertEquals(expected2, ByteUtil.numBytes(test2)); assertEquals(expected3, ByteUtil.numBytes(test3)); }
ByteUtil { public static byte[] stripLeadingZeroes(byte[] data) { return stripLeadingZeroes(data, ZERO_BYTE_ARRAY); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(...
@Test public void testStripLeadingZeroes() { byte[] test1 = null; byte[] test2 = new byte[]{}; byte[] test3 = new byte[]{0x00}; byte[] test4 = new byte[]{0x00, 0x01}; byte[] test5 = new byte[]{0x00, 0x00, 0x01}; byte[] expected1 = null; byte[] expected2 = new byte[]{0}; byte[] expected3 = new byte[]{0}; byte[] expected...
ByteUtil { public static int matchingNibbleLength(byte[] a, byte[] b) { int i = 0; int length = a.length < b.length ? a.length : b.length; while (i < length) { if (a[i] != b[i]) { return i; } i++; } return i; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); ...
@Test public void testMatchingNibbleLength1() { byte[] a = new byte[]{0x00, 0x01}; byte[] b = new byte[]{0x00}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(1, result); } @Test public void testMatchingNibbleLength2() { byte[] a = new byte[]{0x00}; byte[] b = new byte[]{0x00, 0x01}; int result = ByteUt...
ByteUtil { public static String nibblesToPrettyString(byte[] nibbles) { StringBuilder builder = new StringBuilder(); for (byte nibble : nibbles) { final String nibbleString = oneByteToHexString(nibble); builder.append("\\x").append(nibbleString); } return builder.toString(); } private ByteUtil(); static byte[] appendB...
@Test public void testNiceNiblesOutput_1() { byte[] test = {7, 0, 7, 5, 7, 0, 7, 0, 7, 9}; String result = "\\x07\\x00\\x07\\x05\\x07\\x00\\x07\\x00\\x07\\x09"; assertEquals(result, ByteUtil.nibblesToPrettyString(test)); } @Test public void testNiceNiblesOutput_2() { byte[] test = {7, 0, 7, 0xf, 7, 0, 0xa, 0, 7, 9}; St...
Web3Impl implements Web3 { @Override public Object eth_syncing() { long currentBlock = this.blockchain.getBestBlock().getNumber(); long highestBlock = this.nodeBlockProcessor.getLastKnownBlockNumber(); if (highestBlock <= currentBlock){ return false; } SyncingResult s = new SyncingResult(); try { s.startingBlock = Type...
@Test public void eth_syncing_returnFalseWhenNotSyncing() { World world = new World(); SimpleBlockProcessor nodeProcessor = new SimpleBlockProcessor(); nodeProcessor.lastKnownBlockNumber = 0; Web3Impl web3 = createWeb3(world, nodeProcessor, null); Object result = web3.eth_syncing(); assertTrue("Node is not syncing, mus...
ByteUtil { public static int firstNonZeroByte(byte[] data) { for (int i = 0; i < data.length; ++i) { if (data[i] != 0) { return i; } } return -1; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); st...
@Test public void firstNonZeroByte_1() { byte[] data = Hex.decode("0000000000000000000000000000000000000000000000000000000000000000"); int result = ByteUtil.firstNonZeroByte(data); assertEquals(-1, result); } @Test public void firstNonZeroByte_2() { byte[] data = Hex.decode("00000000000000000000000000000000000000000000...
ByteUtil { public static byte[] setBit(byte[] data, int pos, int val) { if ((data.length * 8) - 1 < pos) { throw new Error("outside byte array limit, pos: " + pos); } int posByte = data.length - 1 - (pos) / 8; int posBit = (pos) % 8; byte setter = (byte) (1 << (posBit)); byte toBeSet = data[posByte]; byte result; if (v...
@Test public void setBitTest() { byte[] data = ByteBuffer.allocate(4).putInt(0).array(); int posBit = 24; int expected = 16777216; int result = -1; byte[] ret = ByteUtil.setBit(data, posBit, 1); result = ByteUtil.byteArrayToInt(ret); assertTrue(expected == result); posBit = 25; expected = 50331648; ret = ByteUtil.setBi...
ByteUtil { public static int getBit(byte[] data, int pos) { if ((data.length * 8) - 1 < pos) { throw new Error("outside byte array limit, pos: " + pos); } int posByte = data.length - 1 - pos / 8; int posBit = pos % 8; byte dataByte = data[posByte]; return Math.min(1, (dataByte & 0xff & (1 << (posBit)))); } private Byt...
@Test public void getBitTest() { byte[] data = ByteBuffer.allocate(4).putInt(0).array(); ByteUtil.setBit(data, 24, 1); ByteUtil.setBit(data, 25, 1); ByteUtil.setBit(data, 2, 1); List<Integer> found = new ArrayList<>(); for (int i = 0; i < (data.length * 8); i++) { int res = ByteUtil.getBit(data, i); if (res == 1) if (i...
ByteUtil { public static int numberOfLeadingZeros(byte[] bytes) { int i = firstNonZeroByte(bytes); if (i == -1) { return bytes.length * 8; } else { int byteLeadingZeros = Integer.numberOfLeadingZeros((int)bytes[i] & 0xff) - 24; return i * 8 + byteLeadingZeros; } } private ByteUtil(); static byte[] appendByte(byte[] by...
@Test public void testNumberOfLeadingZeros() { int n0 = ByteUtil.numberOfLeadingZeros(new byte[0]); assertEquals(0, n0); int n1 = ByteUtil.numberOfLeadingZeros(Hex.decode("05")); assertEquals(5, n1); int n2 = ByteUtil.numberOfLeadingZeros(Hex.decode("01")); assertEquals(7, n2); int n3 = ByteUtil.numberOfLeadingZeros(He...
ByteUtil { public static byte[] parseBytes(byte[] input, int offset, int len) { if (offset >= input.length || len == 0) { return EMPTY_BYTE_ARRAY; } byte[] bytes = new byte[len]; System.arraycopy(input, offset, bytes, 0, Math.min(input.length - offset, len)); return bytes; } private ByteUtil(); static byte[] appendByt...
@Test public void testParseBytes() { byte[] shortByteArray = new byte[]{0,1}; byte[] normalByteArray = new byte[]{0,1,2,3,4,5}; byte[] normalByteArrayOffset3LeadingZeroes = new byte[]{3,4,5,0,0,0}; byte[] b1 = ByteUtil.parseBytes(shortByteArray, shortByteArray.length+1, 10); assertEquals(b1,ByteUtil.EMPTY_BYTE_ARRAY); ...
Web3Impl implements Web3 { @Override public String eth_getBalance(String address, String block) { AccountInformationProvider accountInformationProvider = web3InformationRetriever.getInformationProvider(block); RskAddress addr = new RskAddress(address); Coin balance = accountInformationProvider.getBalance(addr); return ...
@Test public void getBalanceWithAccount() throws Exception { World world = new World(); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(10000)).build(); Web3Impl web3 = createWeb3(world); org.junit.Assert.assertEquals("0x" + ByteUtil.toHexString(BigInteger.valueOf(10000).toByteArray()), web3....
Utils { public static String getValueShortString(BigInteger number) { BigInteger result = number; int pow = 0; while (result.compareTo(_1000_) == 1 || result.compareTo(_1000_) == 0) { result = result.divide(_1000_); pow += 3; } return result.toString() + "·(" + "10^" + pow + ")"; } static BigInteger unifiedNumericToBi...
@Test public void testGetValueShortString1() { String expected = "123·(10^24)"; String result = Utils.getValueShortString(new BigInteger("123456789123445654363653463")); assertEquals(expected, result); } @Test public void testGetValueShortString2() { String expected = "123·(10^3)"; String result = Utils.getValueShortSt...
Utils { public static byte[] addressStringToBytes(String hex) { final byte[] addr; try { addr = Hex.decode(hex); } catch (DecoderException addressIsNotValid) { return null; } if (isValidAddress(addr)) { return addr; } return null; } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateT...
@Test public void testAddressStringToBytes() { String HexStr = "6c386a4b26f73c802f34673f7248bb118f97424a"; byte[] expected = Hex.decode(HexStr); byte[] result = Utils.addressStringToBytes(HexStr); assertEquals(Arrays.areEqual(expected, result), true); HexStr = "6c386a4b26f73c802f34673f7248bb118f97424"; expected = null;...
Utils { public static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize) { if (data.length < Math.addExact(allegedSize, offset)) { throw new IllegalArgumentException("The specified size exceeds the size of the payload"); } } static BigInteger unifiedNumericToBigInteger(String number); static Strin...
@Test public void TestValidateArrayWithOffset() { byte[] data = new byte[10]; Utils.validateArrayAllegedSize(data, 1, 0); Utils.validateArrayAllegedSize(data, 8, 1); Utils.validateArrayAllegedSize(data, 0, 10); Utils.validateArrayAllegedSize(data, 8, 2); Utils.validateArrayAllegedSize(data, 11, -1); Utils.validateArray...
Utils { public static byte[] safeCopyOfRange(byte[] data, int from, int size) { validateArrayAllegedSize(data, from, size); return Arrays.copyOfRange(data, from, from + size); } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(...
@Test public void TestSafeCopyOfRangeWithValidArrays() { Utils.safeCopyOfRange(new byte[2], 0, 1); Utils.safeCopyOfRange(new byte[100], 97, 3); Utils.safeCopyOfRange(new byte[0], 0, 0); } @Test public void TestSafeCopyOfRangeWithInvalidArrays() { try { Utils.safeCopyOfRange(new byte[2], 1, 2); fail("should have failed"...
Utils { public static boolean isHexadecimalString(String s) { return s.matches("^0x[\\da-fA-F]+$"); } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static b...
@Test public void isHexadecimalString() { String[] hexStrings = new String[] { "0x1", "0xaaa", "0xAAA", "0xAFe1", "0x10", "0xA12" }; java.util.Arrays.stream(hexStrings).forEach(s -> Assert.assertTrue(s, Utils.isHexadecimalString(s))); String[] nonHexStrings = new String[] { "hellothisisnotahex", "123", "AAA", "AFe1", "...
Utils { public static boolean isDecimalString(String s) { return s.matches("^\\d+$"); } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValid...
@Test public void isDecimalString() { String[] decStrings = new String[] { "1", "123", "045670", "220", "0", "01" }; java.util.Arrays.stream(decStrings).forEach(s -> Assert.assertTrue(s, Utils.isDecimalString(s))); String[] nonDecStrings = new String[] { "hellothisisnotadec", "123a", "0b", "b1", "AAA", "0xabcd", "0x123...
Utils { public static long decimalStringToLong(String s) { try { return Long.parseLong(s, 10); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("Invalid decimal number: %s", s), e); } } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long ti...
@Test public void decimalStringToLong() { Object[] cases = new Object[] { "1", 1L, "123", 123L, "045670", 45670L, "220", 220L, "0", 0L, "01", 1L }; for (int i = 0; i < cases.length/2; i++) { String s = (String) cases[i*2]; long expected = (long) cases[i*2+1]; Assert.assertEquals(expected, Utils.decimalStringToLong(s));...
Utils { public static long hexadecimalStringToLong(String s) { if (!s.startsWith("0x")) { throw new IllegalArgumentException(String.format("Invalid hexadecimal number: %s", s)); } try { return Long.parseLong(s.substring(2), 16); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("Inval...
@Test public void hexadecimalStringToLong() { Object[] cases = new Object[] { "0x1", 1L, "0xaaa", 2730L, "0xAAA", 2730L, "0xAFe1", 45025L, "0x10", 16L, "0xA12", 2578L }; for (int i = 0; i < cases.length/2; i++) { String s = (String) cases[i*2]; long expected = (long) cases[i*2+1]; Assert.assertEquals(expected, Utils.he...
Utils { public static int significantBitCount(int number) { int result = 0; while (number > 0) { result++; number >>= 1; } return result; } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addr...
@Test public void significantBitCount() { Assert.assertEquals(0, Utils.significantBitCount(0b0)); Assert.assertEquals(1, Utils.significantBitCount(0b1)); Assert.assertEquals(2, Utils.significantBitCount(0b10)); Assert.assertEquals(2, Utils.significantBitCount(0b11)); Assert.assertEquals(3, Utils.significantBitCount(0b1...
ByteArrayWrapper implements Comparable<ByteArrayWrapper>, Serializable { public boolean equals(Object other) { if (!(other instanceof ByteArrayWrapper)) { return false; } byte[] otherData = ((ByteArrayWrapper) other).data; return ByteUtil.fastEquals(data, otherData); } ByteArrayWrapper(byte[] data); boolean equals(Obje...
@Test public void testEqualsObject() { assertTrue(wrapper1.equals(wrapper2)); assertFalse(wrapper1.equals(wrapper3)); assertFalse(wrapper1.equals(wrapper4)); assertFalse(wrapper1.equals(null)); assertFalse(wrapper2.equals(wrapper3)); }
ByteArrayWrapper implements Comparable<ByteArrayWrapper>, Serializable { @Override public int compareTo(ByteArrayWrapper o) { return FastByteComparisons.compareTo( data, 0, data.length, o.data, 0, o.data.length); } ByteArrayWrapper(byte[] data); boolean equals(Object other); @Override int hashCode(); @Override int comp...
@Test public void testCompareTo() { assertTrue(wrapper1.compareTo(wrapper2) == 0); assertTrue(wrapper1.compareTo(wrapper3) > 1); assertTrue(wrapper1.compareTo(wrapper4) > 1); assertTrue(wrapper2.compareTo(wrapper3) > 1); }
ReceiptStoreImpl implements ReceiptStore { @Override public TransactionInfo get(byte[] transactionHash){ List<TransactionInfo> txs = getAll(transactionHash); if (txs.isEmpty()) { return null; } return txs.get(txs.size() - 1); } ReceiptStoreImpl(KeyValueDataSource receiptsDS); @Override void add(byte[] blockHash, int tr...
@Test public void getUnknownKey() { ReceiptStore store = new ReceiptStoreImpl(new HashMapDB()); byte[] key = new byte[] { 0x01, 0x02 }; TransactionInfo result = store.get(key); Assert.assertNull(result); } @Test public void getUnknownTransactionByBlock() { ReceiptStore store = new ReceiptStoreImpl(new HashMapDB()); Tra...
IndexedBlockStore implements BlockStore { public void rewind(long blockNumber) { if (index.isEmpty()) { return; } long maxNumber = getMaxNumber(); for (long i = maxNumber; i > blockNumber; i--) { List<BlockInfo> blockInfos = index.removeLast(); for (BlockInfo blockInfo : blockInfos) { this.blocks.delete(blockInfo.getHa...
@Test public void rewind() { IndexedBlockStore indexedBlockStore = new IndexedBlockStore( mock(BlockFactory.class), mock(KeyValueDataSource.class), new HashMapBlocksIndex()); long blocksToGenerate = 14; for (long i = 0; i < blocksToGenerate; i++) { Block block = mock(Block.class); Keccak256 blockHash = randomHash(); wh...
Constants { public static Constants devnetWithFederation(List<BtcECKey> federationPublicKeys) { return new Constants( DEVNET_CHAIN_ID, false, 14, new BlockDifficulty(BigInteger.valueOf(131072)), new BlockDifficulty(BigInteger.valueOf((long) 14E15)), BigInteger.valueOf(50), 540, new BridgeDevNetConstants(federationPubli...
@Test public void devnetWithFederationTest() { Constants constants = Constants.devnetWithFederation(TEST_FED_KEYS.subList(0, 3)); assertThat(constants.getBridgeConstants().getGenesisFederation().hasBtcPublicKey(TEST_FED_KEYS.get(0)), is(true)); assertThat(constants.getBridgeConstants().getGenesisFederation().hasBtcPubl...
ActivationConfig { public static ActivationConfig read(Config config) { Map<NetworkUpgrade, Long> networkUpgrades = new EnumMap<>(NetworkUpgrade.class); Config networkUpgradesConfig = config.getConfig(PROPERTY_ACTIVATION_HEIGHTS); for (Map.Entry<String, ConfigValue> e : networkUpgradesConfig.entrySet()) { NetworkUpgrad...
@Test(expected = IllegalArgumentException.class) public void failsReadingWithMissingNetworkUpgrade() { ActivationConfig.read(BASE_CONFIG .withoutPath("consensusRules.rskip85") ); } @Test(expected = IllegalArgumentException.class) public void failsReadingWithMissingHardFork() { ActivationConfig.read(BASE_CONFIG .without...
EncryptionHandshake { public AuthInitiateMessage createAuthInitiate(@Nullable byte[] token, ECKey key) { AuthInitiateMessage message = new AuthInitiateMessage(); boolean isToken; if (token == null) { isToken = false; BigInteger secretScalar = remotePublicKey.multiply(key.getPrivKey()).normalize().getXCoord().toBigInteg...
@Test public void testCreateAuthInitiate() throws Exception { AuthInitiateMessage message = initiator.createAuthInitiate(new byte[32], myKey); int expectedLength = 65+32+64+32+1; byte[] buffer = message.encode(); assertEquals(expectedLength, buffer.length); }
Node implements Serializable { public InetSocketAddress getAddress() { return new InetSocketAddress(this.getHost(), this.getPort()); } Node(String enodeURL); Node(byte[] id, String host, int port); Node(byte[] rlp); NodeID getId(); String getHexId(); String getHost(); int getPort(); byte[] getRLP(); InetSocketAddress...
@Test public void getAddress() { Node node = new Node(NODE_ID_1, GOOGLE, GOOGLE_PORT); Pattern pattern = Pattern.compile(IP_ADDRESS_PATTERN); String address = node.getAddress().getAddress().getHostAddress(); Matcher matcher = pattern.matcher(address); Assert.assertTrue(StringUtils.isNotBlank(address)); Assert.assertTru...
NodeManager { public synchronized List<NodeHandler> getNodes(Set<String> nodesInUse) { List<NodeHandler> handlers = new ArrayList<>(); List<Node> foundNodes = this.peerExplorer.getNodes(); if (this.discoveryEnabled && !foundNodes.isEmpty()) { logger.debug("{} Nodes retrieved from the PE.", foundNodes.size()); foundNode...
@Test public void getNodesPeerDiscoveryDisable() { List<Node> activePeers = new ArrayList<>(); activePeers.add(new Node(Hex.decode(NODE_ID_2), "127.0.0.2", 8081)); List<Node> bootNodes = new ArrayList<>(); bootNodes.add(new Node(Hex.decode(NODE_ID_3), "127.0.0.3", 8083)); Mockito.when(config.peerActive()).thenReturn(ac...
NodeManager { public NodeStatistics getNodeStatistics(Node n) { return discoveryEnabled ? getNodeHandler(n).getNodeStatistics() : DUMMY_STAT; } NodeManager(PeerExplorer peerExplorer, SystemProperties config); NodeStatistics getNodeStatistics(Node n); synchronized List<NodeHandler> getNodes(Set<String> nodesInUse); }
@Test public void purgeNodesTest() { Random random = new Random(); Mockito.when(config.isPeerDiscoveryEnabled()).thenReturn(true); NodeManager nodeManager = new NodeManager(peerExplorer, config); Set<String> keys = new HashSet<>(); for (int i = 0; i <= NodeManager.NODES_TRIM_THRESHOLD+1;i++) { byte[] nodeId = new byte[...
Channel implements Peer { public void setInetSocketAddress(InetSocketAddress inetSocketAddress) { this.inetSocketAddress = inetSocketAddress; } Channel(MessageQueue msgQueue, MessageCodec messageCodec, NodeManager nodeManager, RskWireProtocol.Factory rskWireProto...
@Test public void equals_true() { InetSocketAddress inetSocketAddress = mock(InetSocketAddress.class); Channel otherChannel = new Channel( messageQueue, messageCodec, nodeManager, rskWireProtocolFactory, eth62MessageFactory, staticMessages, remoteId); target.setInetSocketAddress(inetSocketAddress); otherChannel.setInet...
ChannelManagerImpl implements ChannelManager { @VisibleForTesting int getNumberOfPeersToSendStatusTo(int peerCount) { int peerCountSqrt = (int) Math.sqrt(peerCount); return Math.min(10, Math.min(Math.max(3, peerCountSqrt), peerCount)); } ChannelManagerImpl(RskSystemProperties config, SyncPool syncPool); @Override void ...
@Test public void getNumberOfPeersToSendStatusTo() { ChannelManagerImpl channelManagerImpl = new ChannelManagerImpl(new TestSystemProperties(), null);; assertEquals(1, channelManagerImpl.getNumberOfPeersToSendStatusTo(1)); assertEquals(2, channelManagerImpl.getNumberOfPeersToSendStatusTo(2)); assertEquals(3, channelMan...
ChannelManagerImpl implements ChannelManager { public boolean isAddressBlockAvailable(InetAddress inetAddress) { synchronized (activePeersLock) { return activePeers.values().stream() .map(ch -> new InetAddressBlock(ch.getInetSocketAddress().getAddress(), networkCIDR)) .filter(block -> block.contains(inetAddress)) .coun...
@Test public void blockAddressIsAvailable() throws UnknownHostException { ChannelManagerImpl channelManagerImpl = new ChannelManagerImpl(new TestSystemProperties(), null);; Assert.assertTrue(channelManagerImpl.isAddressBlockAvailable(InetAddress.getLocalHost())); }
ChannelManagerImpl implements ChannelManager { @Nonnull public Set<NodeID> broadcastBlock(@Nonnull final Block block) { final Set<NodeID> nodesIdsBroadcastedTo = new HashSet<>(); final BlockIdentifier bi = new BlockIdentifier(block.getHash().getBytes(), block.getNumber()); final Message newBlock = new BlockMessage(bloc...
@Test public void broadcastBlock() { ChannelManager target = new ChannelManagerImpl(mock(RskSystemProperties.class), mock(SyncPool.class)); Block block = mock(Block.class); when(block.getHash()).thenReturn(new Keccak256(new byte[32])); Set<NodeID> nodeIds = target.broadcastBlock(block); assertTrue(nodeIds.isEmpty()); }
DataSourceWithCache implements KeyValueDataSource { @Override public byte[] put(byte[] key, byte[] value) { ByteArrayWrapper wrappedKey = ByteUtil.wrap(key); return put(wrappedKey, value); } DataSourceWithCache(KeyValueDataSource base, int cacheSize); @Override byte[] get(byte[] key); @Override byte[] put(byte[] key, b...
@Test public void put() { byte[] randomKey = TestUtils.randomBytes(20); byte[] randomValue = TestUtils.randomBytes(20); dataSourceWithCache.put(randomKey, randomValue); assertThat(baseDataSource.get(randomKey), is(nullValue())); dataSourceWithCache.flush(); assertThat(baseDataSource.get(randomKey), is(randomValue)); }
DataSourceWithCache implements KeyValueDataSource { @Override public Set<byte[]> keys() { Stream<ByteArrayWrapper> baseKeys; Stream<ByteArrayWrapper> committedKeys; Stream<ByteArrayWrapper> uncommittedKeys; Set<ByteArrayWrapper> uncommittedKeysToRemove; this.lock.readLock().lock(); try { baseKeys = base.keys().stream()...
@Test public void keys() { Map<ByteArrayWrapper, byte[]> initialEntries = generateRandomValuesToUpdate(CACHE_SIZE); Set<byte[]> initialKeys = initialEntries.keySet().stream().map(ByteArrayWrapper::getData).collect(Collectors.toSet()); baseDataSource.updateBatch(initialEntries, Collections.emptySet()); assertThat(dataSo...
DataSourceWithCache implements KeyValueDataSource { @Override public void delete(byte[] key) { delete(ByteUtil.wrap(key)); } DataSourceWithCache(KeyValueDataSource base, int cacheSize); @Override byte[] get(byte[] key); @Override byte[] put(byte[] key, byte[] value); @Override void delete(byte[] key); @Override Set<byt...
@Test public void delete() { byte[] randomKey = TestUtils.randomBytes(20); baseDataSource.put(randomKey, TestUtils.randomBytes(20)); dataSourceWithCache.delete(randomKey); dataSourceWithCache.flush(); assertThat(baseDataSource.get(randomKey), is(nullValue())); }
DataSourceWithCache implements KeyValueDataSource { @Override public void updateBatch(Map<ByteArrayWrapper, byte[]> rows, Set<ByteArrayWrapper> keysToRemove) { if (rows.containsKey(null) || rows.containsValue(null)) { throw new IllegalArgumentException("Cannot update null values"); } rows.keySet().removeAll(keysToRemov...
@Test public void updateBatch() { Map<ByteArrayWrapper, byte[]> initialEntries = generateRandomValuesToUpdate(CACHE_SIZE); baseDataSource.updateBatch(initialEntries, Collections.emptySet()); Set<ByteArrayWrapper> keysToBatchRemove = initialEntries.keySet().stream().limit(CACHE_SIZE / 2).collect(Collectors.toSet()); dat...
TransactionReceipt { public byte[] getStatus() { return this.status; } TransactionReceipt(); TransactionReceipt(byte[] rlp); TransactionReceipt(byte[] postTxState, byte[] cumulativeGas, byte[] gasUsed, Bloom bloomFilter, List<LogInfo> logInfoList, byte[] status); byte[] getPostTxState();...
@Test public void test_2() { assertTrue(TypeConverter.toJsonHex(EMPTY_BYTE_ARRAY).equals("0x00")); byte[] rlpSuccess = Hex.decode("f9010c808255aeb901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000...
TransactionExecutor { public boolean executeTransaction() { if (!this.init()) { return false; } this.execute(); this.go(); this.finalization(); return true; } TransactionExecutor( Constants constants, ActivationConfig activationConfig, Transaction tx, int txindex, RskAddress coinbase, Repository...
@Test public void testInitHandlesFreeTransactionsOK() { BlockTxSignatureCache blockTxSignatureCache = mock(BlockTxSignatureCache.class); Transaction transaction = mock(Transaction.class); TransactionExecutor txExecutor = new TransactionExecutor( constants, activationConfig, transaction, txIndex, rskAddress, repository,...
BlockHeaderBuilder { public BlockHeader build() { initializeWithDefaultValues(); if (createConsensusCompliantHeader) { useRskip92Encoding = activationConfig.isActive(ConsensusRule.RSKIP92, number); includeForkDetectionData = activationConfig.isActive(ConsensusRule.RSKIP110, number) && mergedMiningForkDetectionData.leng...
@Test public void createsHeaderWithEmptyStateRoot() { BlockHeader header = blockHeaderBuilder.build(); assertArrayEquals(HashUtil.EMPTY_TRIE_HASH, header.getStateRoot()); } @Test public void createsHeaderWithEmptyTxTrieRoot() { BlockHeader header = blockHeaderBuilder.build(); assertArrayEquals(HashUtil.EMPTY_TRIE_HASH,...
Web3Impl implements Web3 { @Override public boolean eth_mining() { Boolean s = null; try { return s = minerClient.isMining(); } finally { if (logger.isDebugEnabled()) { logger.debug("eth_mining(): {}", s); } } } protected Web3Impl( Ethereum eth, Blockchain blockchain, BlockStore blo...
@Test public void eth_mining() { Ethereum ethMock = Web3Mocks.getMockEthereum(); Blockchain blockchain = Web3Mocks.getMockBlockchain(); BlockStore blockStore = Web3Mocks.getMockBlockStore(); RskSystemProperties mockProperties = Web3Mocks.getMockProperties(); MinerClient minerClient = new SimpleMinerClient(); PersonalMo...
TransactionSet { public List<Transaction> getTransactions() { return transactionsByHash.values().stream() .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } TransactionSet(); TransactionSet(TransactionSet transactionSet); TransactionSet(Map<Keccak256, Transaction> transactio...
@Test public void getEmptyTransactionList() { TransactionSet txset = new TransactionSet(); List<Transaction> result = txset.getTransactions(); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); }
TransactionSet { public boolean hasTransaction(Transaction transaction) { return this.transactionsByHash.containsKey(transaction.getHash()); } TransactionSet(); TransactionSet(TransactionSet transactionSet); TransactionSet(Map<Keccak256, Transaction> transactionsByHash, Map<RskAddress, List<Transaction>> transactions...
@Test public void hasTransaction() { TransactionSet txset = new TransactionSet(); Transaction transaction1 = createSampleTransaction(10); Transaction transaction2 = createSampleTransaction(20); Transaction transaction3 = createSampleTransaction(30); txset.addTransaction(transaction1); txset.addTransaction(transaction2)...
TransactionSet { public List<Transaction> getTransactionsWithSender(RskAddress senderAddress) { List<Transaction> list = this.transactionsByAddress.get(senderAddress); if (list == null) { return Collections.emptyList(); } return list; } TransactionSet(); TransactionSet(TransactionSet transactionSet); TransactionSet(M...
@Test public void getEmptyTransactionListByUnknownSender() { TransactionSet txset = new TransactionSet(); List<Transaction> result = txset.getTransactionsWithSender(new RskAddress(new byte[20])); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); }
Web3Impl implements Web3 { @Override public String eth_gasPrice() { String gasPrice = null; try { gasPrice = TypeConverter.toQuantityJsonHex(eth.getGasPrice().asBigInteger().longValue()); return gasPrice; } finally { if (logger.isDebugEnabled()) { logger.debug("eth_gasPrice(): {}", gasPrice); } } } protected Web3Impl(...
@Test public void getGasPrice() { Web3Impl web3 = createWeb3(); web3.eth = new SimpleEthereum(); String expectedValue = ByteUtil.toHexString(new BigInteger("20000000000").toByteArray()); expectedValue = "0x" + (expectedValue.startsWith("0") ? expectedValue.substring(1) : expectedValue); org.junit.Assert.assertEquals(ex...
Transaction { public byte[] getEncoded() { if (this.rlpEncoding == null) { byte[] v; byte[] r; byte[] s; if (this.signature != null) { v = RLP.encodeByte((byte) (chainId == 0 ? signature.getV() : (signature.getV() - LOWER_REAL_V) + (chainId * 2 + CHAIN_ID_INC))); r = RLP.encodeElement(BigIntegers.asUnsignedByteArray(si...
@Ignore @Test public void encodeReceiptTest() { String data = "f90244a0f5ff3fbd159773816a7c707a9b8cb6bb778b934a8f6466c7830ed970498f4b688301e848b90200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000...
Transaction { public void verify() { validate(); } protected Transaction(byte[] rawData); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data, ...
@Test public void verifyTx_noSignature() { BigInteger value = new BigInteger("1000000000000000000000"); byte[] privKey = HashUtil.keccak256("cat".getBytes()); ECKey ecKey = ECKey.fromPrivate(privKey); byte[] gasPrice = Hex.decode("09184e72a000"); byte[] gas = Hex.decode("4255"); Transaction tx = new Transaction(new byt...
Transaction { @Override public String toString() { return "TransactionData [" + "hash=" + ByteUtil.toHexStringOrEmpty(getHash().getBytes()) + " nonce=" + ByteUtil.toHexStringOrEmpty(nonce) + ", gasPrice=" + gasPrice + ", gas=" + ByteUtil.toHexStringOrEmpty(gasLimit) + ", receiveAddress=" + receiveAddress + ", value=" +...
@Test public void toString_nullElements() { byte[] encodedNull = RLP.encodeElement(null); byte[] encodedEmptyArray = RLP.encodeElement(EMPTY_BYTE_ARRAY); byte[] rawData = RLP.encodeList(encodedNull, encodedNull, encodedNull, encodedNull, encodedNull, encodedNull, encodedEmptyArray, encodedEmptyArray, encodedEmptyArray)...
AccountState { public byte[] getEncoded() { if (rlpEncoded == null) { byte[] anonce = RLP.encodeBigInteger(this.nonce); byte[] abalance = RLP.encodeSignedCoinNonNullZero(this.balance); if (stateFlags != 0) { byte[] astateFlags = RLP.encodeInt(this.stateFlags); this.rlpEncoded = RLP.encodeList(anonce, abalance, astateFl...
@Test public void testGetEncoded() { String expected = "dc809a0100000000000000000000000000000000000000000000000000"; AccountState acct = new AccountState(BigInteger.ZERO, new Coin(BigInteger.valueOf(2).pow(200))); assertEquals(expected, ByteUtil.toHexString(acct.getEncoded())); }
DifficultyRule extends DependentBlockHeaderRule { @Override public boolean validate(BlockHeader header, BlockHeader parent) { BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.error(...
@Ignore @Test public void parentDifficultyLessHeaderDifficulty() { BlockHeader header = getHeader(10004); BlockHeader parent = getHeader(10000); assertTrue(rule.validate(header, parent)); } @Test public void parentDifficultyEqualHeaderDifficulty() { BlockHeader header = getHeader(10000); BlockHeader parent = getHeader(...
ParentNumberRule extends DependentBlockHeaderRule { @Override public boolean validate(BlockHeader header, BlockHeader parent) { if (header.getNumber() != (parent.getNumber() + 1)) { logger.error(String.format("#%d: block number is not parentBlock number + 1", header.getNumber())); return false; } return true; } @Overr...
@Test public void parentNumberEqualBlockNumberMinusOne() { BlockHeader header = getHeader(10000); BlockHeader parent = getHeader(9999); assertTrue(rule.validate(header, parent)); } @Test public void parentNumberEqualBlockNumber() { BlockHeader header = getHeader(100); BlockHeader parent = getHeader(100); assertFalse(ru...
ParentGasLimitRule extends DependentBlockHeaderRule { @Override public boolean validate(BlockHeader header, BlockHeader parent) { BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parent.getGasLimit()); BigInteger deltaLimit = parentGasLimit.divide(gasLim...
@Test public void parentGasLimitLessThanGasLimit() { BlockHeader header = getHeader(10000); BlockHeader parent = getHeader(9999); assertTrue(rule.validate(header, parent)); } @Test public void parentGasLimitTooLessThanGasLimit() { BlockHeader header = getHeader(100); BlockHeader parent = getHeader(9); assertFalse(rule....
Web3Impl implements Web3 { @Override public TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash) { logger.trace("eth_getTransactionReceipt({})", transactionHash); byte[] hash = stringHexToByteArray(transactionHash); TransactionInfo txInfo = receiptStore.getInMainChain(hash, blockStore); if (txInfo ==...
@Test public void getUnknownTransactionReceipt() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); Web3Impl web3 = createWeb3(world, receiptStore); Account acc1 = new AccountBuilder().name("acc1").build(); Account acc2 = new AccountBuilder().nam...
GasCost { public static long toGas(byte[] bytes) throws InvalidGasException { if (bytes.length > 8) { return Long.MAX_VALUE; } long result = ByteUtil.byteArrayToLong(bytes); if (result < 0) { throw new InvalidGasException(bytes); } return result; } private GasCost(); static long toGas(byte[] bytes); static long toGas(...
@Test public void toGas() { Assert.assertEquals(0, GasCost.toGas(new byte[0])); Assert.assertEquals(1, GasCost.toGas(new byte[] { 0x01 })); Assert.assertEquals(255, GasCost.toGas(new byte[] { (byte)0xff })); Assert.assertEquals( Long.MAX_VALUE, GasCost.toGas(BigInteger.valueOf(Long.MAX_VALUE).toByteArray()) ); } @Test ...
GasCost { public static long add(long x, long y) throws InvalidGasException { if (x < 0 || y < 0) { throw new InvalidGasException(String.format("%d + %d", x, y)); } long result = x + y; if (result < 0) { return Long.MAX_VALUE; } return result; } private GasCost(); static long toGas(byte[] bytes); static long toGas(Big...
@Test public void calculateAddGas() { Assert.assertEquals(1, GasCost.add(1, 0)); Assert.assertEquals(2, GasCost.add(1, 1)); Assert.assertEquals(1000000, GasCost.add(500000, 500000)); } @Test public void calculateAddGasWithOverflow() { Assert.assertEquals(Long.MAX_VALUE, GasCost.add(Long.MAX_VALUE, 1)); Assert.assertEqu...
GasCost { public static long subtract(long x, long y) throws InvalidGasException { if (y < 0 || y > x) { throw new InvalidGasException(String.format("%d - %d", x, y)); } return x - y; } private GasCost(); static long toGas(byte[] bytes); static long toGas(BigInteger big); static long toGas(long number); static long ad...
@Test public void calculateSubtractGasCost() { Assert.assertEquals(1, GasCost.subtract(1, 0)); Assert.assertEquals(0, GasCost.subtract(1, 1)); Assert.assertEquals(1000000, GasCost.subtract(1500000, 500000)); Assert.assertEquals(0, GasCost.subtract(Long.MAX_VALUE, Long.MAX_VALUE)); } @Test(expected = GasCost.InvalidGasE...
GasCost { public static long multiply(long x, long y) throws InvalidGasException { if (x < 0 || y < 0) { throw new InvalidGasException(String.format("%d * %d", x, y)); } long result = x * y; if (multiplicationOverflowed(x, y, result)) { return Long.MAX_VALUE; } return result; } private GasCost(); static long toGas(byt...
@Test(expected = GasCost.InvalidGasException.class) public void multiplyWithNegativeValues() throws GasCost.InvalidGasException { GasCost.multiply(-1, -2); } @Test(expected = GasCost.InvalidGasException.class) public void multiplyWithXNegative() throws GasCost.InvalidGasException { GasCost.multiply(-1, 123); } @Test(ex...
Web3Impl implements Web3 { @Override public TransactionResultDTO eth_getTransactionByHash(String transactionHash) { TransactionResultDTO s = null; try { Keccak256 txHash = new Keccak256(stringHexToByteArray(transactionHash)); Block block = null; TransactionInfo txInfo = this.receiptStore.getInMainChain(txHash.getBytes(...
@Test public void getTransactionByHash() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); Web3Impl web3 = createWeb3(world, receiptStore); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc...
GasCost { public static long calculateTotal(long baseCost, long unitCost, long units) throws InvalidGasException { if (baseCost < 0 || unitCost < 0 || units < 0) { throw new InvalidGasException(String.format("%d + %d * %d", baseCost, unitCost, units)); } long mult = unitCost * units; if (multiplicationOverflowed(unitCo...
@Test public void calculateGasCost() throws GasCost.InvalidGasException { Assert.assertEquals(1, GasCost.calculateTotal(1, 0, 0)); Assert.assertEquals(2, GasCost.calculateTotal(0, 2, 1)); Assert.assertEquals(7, GasCost.calculateTotal(1, 2, 3)); Assert.assertEquals(10, GasCost.calculateTotal(4, 3, 2)); Assert.assertEqua...
DataWord implements Comparable<DataWord> { public DataWord add(DataWord word) { byte[] newdata = new byte[BYTES]; for (int i = 31, overflow = 0; i >= 0; i--) { int v = (this.data[i] & 0xff) + (word.data[i] & 0xff) + overflow; newdata[i] = (byte) v; overflow = v >>> 8; } return new DataWord(newdata); } private DataWord...
@Test public void testAdd() { byte[] three = new byte[32]; for (int i = 0; i < three.length; i++) { three[i] = (byte) 0xff; } DataWord x = DataWord.valueOf(three); byte[] xdata = x.getData(); DataWord result = x.add(DataWord.valueOf(three)); assertArrayEquals(xdata, x.getData()); assertEquals(32, result.getData().lengt...
DataWord implements Comparable<DataWord> { public DataWord mod(DataWord word) { if (word.isZero()) { return DataWord.ZERO; } BigInteger result = value().mod(word.value()); return valueOf(result.and(MAX_VALUE)); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStora...
@Test public void testMod() { String expected = "000000000000000000000000000000000000000000000000000000000000001a"; byte[] one = new byte[32]; one[31] = 0x1e; byte[] two = new byte[32]; for (int i = 0; i < two.length; i++) { two[i] = (byte) 0xff; } two[31] = 0x56; DataWord x = DataWord.valueOf(one); byte[] xdata = x.ge...
DataWord implements Comparable<DataWord> { public DataWord mul(DataWord word) { BigInteger result = value().multiply(word.value()); return valueOf(result.and(MAX_VALUE)); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigIntege...
@Test public void testMul() { byte[] one = new byte[32]; one[31] = 0x1; byte[] two = new byte[32]; two[11] = 0x1; DataWord x = DataWord.valueOf(one); DataWord y = DataWord.valueOf(two); byte[] xdata = x.getData(); byte[] ydata = y.getData(); DataWord result = x.mul(y); assertArrayEquals(xdata, x.getData()); assertArray...
DataWord implements Comparable<DataWord> { public DataWord div(DataWord word) { if (word.isZero()) { return DataWord.ZERO; } BigInteger result = value().divide(word.value()); return valueOf(result.and(MAX_VALUE)); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForSt...
@Test public void testDiv() { byte[] one = new byte[32]; one[30] = 0x01; one[31] = 0x2c; byte[] two = new byte[32]; two[31] = 0x0f; DataWord x = DataWord.valueOf(one); DataWord y = DataWord.valueOf(two); byte[] xdata = x.getData(); byte[] ydata = y.getData(); DataWord result =x.div(y); assertArrayEquals(xdata, x.getDat...
DataWord implements Comparable<DataWord> { public static DataWord valueOf(int num) { byte[] data = new byte[BYTES]; ByteBuffer.wrap(data).putInt(data.length - Integer.BYTES, num); return valueOf(data); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byt...
@Test public void testPow() { BigInteger x = BigInteger.valueOf(Integer.MAX_VALUE); BigInteger y = BigInteger.valueOf(1000); BigInteger result1 = x.modPow(x, y); BigInteger result2 = pow(x, y); }
DataWord implements Comparable<DataWord> { public DataWord signExtend(byte k) { byte[] newdata = getData(); if (0 > k || k > 31) { throw new IndexOutOfBoundsException(); } byte mask = (new BigInteger(newdata)).testBit((k * 8) + 7) ? (byte) 0xff : 0; for (int i = 31; i > k; i--) { newdata[31 - i] = mask; } return new Da...
@Test(expected = IndexOutOfBoundsException.class) public void testSignExtendException1() { byte k = -1; DataWord x = DataWord.ZERO; x.signExtend(k); } @Test(expected = IndexOutOfBoundsException.class) public void testSignExtendException2() { byte k = 32; DataWord x = DataWord.ZERO; x.signExtend(k); }
DataWord implements Comparable<DataWord> { public static DataWord fromString(String value) { return valueOf(value.getBytes(StandardCharsets.UTF_8)); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValu...
@Test public void testFromString() { DataWord parsed = DataWord.fromString("01234567890123456789012345678901"); assertEquals(new String(parsed.getData()),"01234567890123456789012345678901"); }
DataWord implements Comparable<DataWord> { public static DataWord fromLongString(String value) { return valueOf(HashUtil.keccak256(value.getBytes(StandardCharsets.UTF_8))); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInte...
@Test public void testFromLongString() { String value = "012345678901234567890123456789012345678901234567890123456789"; byte[] hashedValue = HashUtil.keccak256(value.getBytes(StandardCharsets.UTF_8)); DataWord parsed = DataWord.fromLongString(value); assertArrayEquals(parsed.getData(),hashedValue); }
VM { public void steps(Program aprogram, long steps) { program = aprogram; stack = program.getStack(); try { for(long s=0;s<steps;s++) { if (program.isStopped()) { break; } if (vmConfig.vmTrace()) { program.saveOpTrace(); } op = OpCode.code(program.getCurrentOp()); checkOpcode(); program.setLastOp(op.val()); program.ve...
@Test public void testCALLWithBigUserSpecifiedGas() { String maxGasValue = "7FFFFFFFFFFFFFFF"; RskAddress callee = createAddress("callee"); invoke = new ProgramInvokeMockImpl(compile("" + " ADD" ), callee); program = getProgram(compile("" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x01" +...
Web3Impl implements Web3 { @Override public TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index) { TransactionResultDTO s = null; try { Block b = getBlockByJSonHash(blockHash); if (b == null) { return null; } int idx = JSonHexToInt(index); if (idx >= b.getTransactionsList().size())...
@Test public void getTransactionByBlockHashAndIndex() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionB...
CallArgumentsToByteArray { public byte[] getGasLimit() { String maxGasLimit = "0x5AF3107A4000"; byte[] gasLimit = stringHexToByteArray(maxGasLimit); if (args.gas != null && args.gas.length() != 0) { gasLimit = stringHexToByteArray(args.gas); } return gasLimit; } CallArgumentsToByteArray(Web3.CallArguments args); byte[]...
@Test public void getGasLimitWhenValueIsNull() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); String maxGasLimit = "0x5AF3107A4000"; byte[] expectedGasLimit = TypeConverter.stringHexToByteArray(maxGasLimit); Assert.asse...
Web3Impl implements Web3 { @Override public TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index) { TransactionResultDTO s = null; try { Optional<Block> block = web3InformationRetriever.getBlock(bnOrId); if (!block.isPresent()) { return null; } int idx = JSonHexToInt(index); List<Tra...
@Test public void getTransactionByBlockNumberAndIndex() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new Transactio...
Web3Impl implements Web3 { @Override public String eth_getTransactionCount(String address, String blockId) { String s = null; try { RskAddress addr = new RskAddress(address); AccountInformationProvider accountInformationProvider = web3InformationRetriever .getInformationProvider(blockId); BigInteger nonce = accountInfo...
@Test public void getTransactionCount() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(100000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sen...
Web3Impl implements Web3 { @Override public BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects) { BlockResultDTO s = null; try { s = web3InformationRetriever.getBlock(bnOrId) .map(b -> getBlockResult(b, fullTransactionObjects)) .orElse(null); return s; } finally { if (logger.isDebugEnable...
@Test public void getBlockByNumber() { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(10).parent(...
Web3Impl implements Web3 { public BlockInformationResult[] eth_getBlocksByNumber(String number) { long blockNumber; try { blockNumber = TypeConverter.stringNumberAsBigInt(number).longValue(); } catch (NumberFormatException | StringIndexOutOfBoundsException e) { throw invalidParamError(String.format("invalid blocknumber...
@Test public void getBlocksByNumber() { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(10).parent...
Web3Impl implements Web3 { @Override public BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects) { BlockResultDTO s = null; try { Block b = getBlockByJSonHash(blockHash); return s = (b == null ? null : getBlockResult(b, fullTransactionObjects)); } finally { if (logger.isDebugEnabled()) { ...
@Test public void getBlockByHash() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficu...
Web3Impl implements Web3 { @Override public BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx) { BlockResultDTO s = null; try { Block block = blockchain.getBlockByHash(stringHexToByteArray(blockHash)); if (block == null) { return null; } s = getUncleResultDTO(uncleIdx, block); return s; }...
@Test public void getUncleByBlockHashAndIndexBlockWithUncles() { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block blockA = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStor...
EthSubscriptionNotificationEmitter implements EthSubscribeParamsVisitor { @Override public SubscriptionId visit(EthSubscribeNewHeadsParams params, Channel channel) { SubscriptionId subscriptionId = new SubscriptionId(); blockHeader.subscribe(subscriptionId, channel); return subscriptionId; } EthSubscriptionNotification...
@Test public void subscribeToNewHeads() { Channel channel = mock(Channel.class); EthSubscribeNewHeadsParams params = mock(EthSubscribeNewHeadsParams.class); SubscriptionId subscriptionId = emitter.visit(params, channel); assertThat(subscriptionId, notNullValue()); verify(newHeads).subscribe(subscriptionId, channel); } ...