method2testcases
stringlengths
118
6.63k
### Question: 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[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @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}; String result = "\\x07\\x00\\x07\\x0f\\x07\\x00\\x0a\\x00\\x07\\x09"; assertEquals(result, ByteUtil.nibblesToPrettyString(test)); }
### Question: 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); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @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("0000000000000000000000000000000000000000000000000000000000332211"); int result = ByteUtil.firstNonZeroByte(data); assertEquals(29, result); } @Test public void firstNonZeroByte_3() { byte[] data = Hex.decode("2211009988776655443322110099887766554433221100998877665544332211"); int result = ByteUtil.firstNonZeroByte(data); assertEquals(0, result); }
### Question: 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 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); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @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 != 24 && i != 25 && i != 2) assertTrue(false); else found.add(i); else { if (i == 24 || i == 25 || i == 2) assertTrue(false); } } if (found.size() != 3) assertTrue(false); assertTrue(found.get(0) == 2); assertTrue(found.get(1) == 24); assertTrue(found.get(2) == 25); }
### Question: 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[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @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(Hex.decode("00")); assertEquals(8, n3); int n4 = ByteUtil.numberOfLeadingZeros(Hex.decode("ff")); assertEquals(0, n4); byte[] v1 = Hex.decode("1040"); int n5 = ByteUtil.numberOfLeadingZeros(v1); assertEquals(3, n5); byte[] v2 = new byte[4]; System.arraycopy(v1, 0, v2, 2, v1.length); int n6 = ByteUtil.numberOfLeadingZeros(v2); assertEquals(19, n6); byte[] v3 = new byte[8]; int n7 = ByteUtil.numberOfLeadingZeros(v3); assertEquals(64, n7); }
### Question: 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[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @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); byte[] b2 = ByteUtil.parseBytes(shortByteArray, shortByteArray.length-1, 0); assertEquals(b1,ByteUtil.EMPTY_BYTE_ARRAY); byte[] b3 = ByteUtil.parseBytes(normalByteArray, normalByteArray.length -3, normalByteArrayOffset3LeadingZeroes.length); for (int i=0; i < b3.length; i++) { assertEquals(b3[i],normalByteArrayOffset3LeadingZeroes[i]); } }
### Question: 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 unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; }### Answer: @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.getValueShortString(new BigInteger("123456")); assertEquals(expected, result); } @Test public void testGetValueShortString3() { String expected = "1·(10^3)"; String result = Utils.getValueShortString(new BigInteger("1234")); assertEquals(expected, result); } @Test public void testGetValueShortString4() { String expected = "123·(10^0)"; String result = Utils.getValueShortString(new BigInteger("123")); assertEquals(expected, result); } @Test public void testGetValueShortString5() { byte[] decimal = Hex.decode("3913517ebd3c0c65000000"); String expected = "69·(10^24)"; String result = Utils.getValueShortString(new BigInteger(decimal)); assertEquals(expected, result); }
### Question: 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 longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; }### Answer: @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; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); HexStr = new String(Hex.encode("I am longer than 20 bytes, i promise".getBytes())); expected = null; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); HexStr = new String(Hex.encode("I am short".getBytes())); expected = null; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); }
### Question: 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 String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; }### Answer: @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.validateArrayAllegedSize(data, -2, 12); try { Utils.validateArrayAllegedSize(data, 0, 11); fail("should have failed"); } catch (IllegalArgumentException e) { } try { Utils.validateArrayAllegedSize(data, 2, 9); fail("should have failed"); } catch (IllegalArgumentException e) { } try { Utils.validateArrayAllegedSize(new byte[0], 1, 0); fail("should have failed"); } catch (IllegalArgumentException e) { } byte[] noData = null; try { Utils.validateArrayAllegedSize(noData, 1, 1); fail("should have failed"); } catch (NullPointerException e) { } }
### Question: 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(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; }### Answer: @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"); } catch (IllegalArgumentException e){ } try { Utils.safeCopyOfRange(new byte[100], 98, 3); fail("should have failed"); } catch (IllegalArgumentException e){ } try { Utils.safeCopyOfRange(new byte[0], 0, 1); fail("should have failed"); } catch (IllegalArgumentException e){ } try { Utils.safeCopyOfRange(new byte[0], 1, 0); fail("should have failed"); } catch (IllegalArgumentException e){ } }
### Question: 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 boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; }### Answer: @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", "0xab123z", "0xnothing" }; java.util.Arrays.stream(nonHexStrings).forEach(s -> Assert.assertFalse(s, Utils.isHexadecimalString(s))); }
### Question: 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 isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; }### Answer: @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" }; java.util.Arrays.stream(nonDecStrings).forEach(s -> Assert.assertFalse(s, Utils.isDecimalString(s))); }
### Question: 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 timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; }### Answer: @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)); } } @Test(expected = IllegalArgumentException.class) public void decimalStringToLongFail() { Utils.decimalStringToLong("zzz"); }
### Question: 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("Invalid hexadecimal number: %s", s), e); } } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; }### Answer: @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.hexadecimalStringToLong(s)); } } @Test(expected = IllegalArgumentException.class) public void hexadecimalStringToLongFail() { Utils.hexadecimalStringToLong("abcd"); } @Test(expected = IllegalArgumentException.class) public void hexadecimalStringToLongFailBis() { Utils.hexadecimalStringToLong("zzz"); }
### Question: 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[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; }### Answer: @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(0b111)); Assert.assertEquals(3, Utils.significantBitCount(0b100)); Assert.assertEquals(3, Utils.significantBitCount(0b101)); Assert.assertEquals(13, Utils.significantBitCount(0b1000111000101)); Assert.assertEquals(9, Utils.significantBitCount(0b000111000101)); }
### Question: 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(Object other); @Override int hashCode(); @Override int compareTo(ByteArrayWrapper o); byte[] getData(); @Override String toString(); boolean equalsToByteArray(byte[] otherData); }### Answer: @Test public void testEqualsObject() { assertTrue(wrapper1.equals(wrapper2)); assertFalse(wrapper1.equals(wrapper3)); assertFalse(wrapper1.equals(wrapper4)); assertFalse(wrapper1.equals(null)); assertFalse(wrapper2.equals(wrapper3)); }
### Question: 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 compareTo(ByteArrayWrapper o); byte[] getData(); @Override String toString(); boolean equalsToByteArray(byte[] otherData); }### Answer: @Test public void testCompareTo() { assertTrue(wrapper1.compareTo(wrapper2) == 0); assertTrue(wrapper1.compareTo(wrapper3) > 1); assertTrue(wrapper1.compareTo(wrapper4) > 1); assertTrue(wrapper2.compareTo(wrapper3) > 1); }
### Question: 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 transactionIndex, TransactionReceipt receipt); @Override TransactionInfo get(byte[] transactionHash); @Override Optional<TransactionInfo> get(Keccak256 transactionHash, Keccak256 blockHash); @Override TransactionInfo getInMainChain(byte[] transactionHash, BlockStore store); @Override List<TransactionInfo> getAll(byte[] transactionHash); @Override void saveMultiple(byte[] blockHash, List<TransactionReceipt> receipts); @Override void flush(); }### Answer: @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()); TransactionReceipt receipt = createReceipt(); Keccak256 blockHash = TestUtils.randomHash(); Optional<TransactionInfo> resultOpt = store.get(receipt.getTransaction().getHash(), blockHash); Assert.assertFalse(resultOpt.isPresent()); }
### Question: 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.getHash().getBytes()); } } flush(); } IndexedBlockStore( BlockFactory blockFactory, KeyValueDataSource blocks, BlocksIndex index); @Override synchronized void removeBlock(Block block); @Override synchronized Block getBestBlock(); @Override byte[] getBlockHashByNumber(long blockNumber, byte[] branchBlockHash); @Override // This method is an optimized way to traverse a branch in search for a block at a given depth. Starting at a given // block (by hash) it tries to find the first block that is part of the best chain, when it finds one we now that // we can jump to the block that is at the remaining depth. If not block is found then it continues traversing the // branch from parent to parent. The search is limited by the maximum depth received as parameter. // This method either needs to traverse the parent chain or if a block in the parent chain is part of the best chain // then it can skip the traversal by going directly to the block at the remaining depth. Block getBlockAtDepthStartingAt(long depth, byte[] hash); boolean isBlockInMainChain(long blockNumber, Keccak256 blockHash); @Override synchronized void flush(); void close(); @Override synchronized void saveBlock(Block block, BlockDifficulty cummDifficulty, boolean mainChain); @Override synchronized List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean isEmpty(); @Override synchronized Block getChainBlockByNumber(long number); @Override synchronized Block getBlockByHash(byte[] hash); @Override synchronized Map<Long, List<Sibling>> getSiblingsFromBlockByHash(Keccak256 hash); @Override synchronized boolean isBlockExist(byte[] hash); @Override synchronized BlockDifficulty getTotalDifficultyForHash(byte[] hash); @Override long getMaxNumber(); @Override long getMinNumber(); @Override synchronized List<byte[]> getListHashesEndWith(byte[] hash, long number); @Override synchronized void reBranch(Block forkBlock); @VisibleForTesting synchronized List<byte[]> getListHashesStartWith(long number, long maxBlocks); @Override synchronized List<Block> getChainBlocksByNumber(long number); void rewind(long blockNumber); static final Serializer<List<BlockInfo>> BLOCK_INFO_SERIALIZER; }### Answer: @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(); when(block.getHash()).thenReturn(blockHash); when(block.getNumber()).thenReturn(i); indexedBlockStore.saveBlock(block, ZERO, true); } Block bestBlock = indexedBlockStore.getBestBlock(); assertThat(bestBlock.getNumber(), is(blocksToGenerate - 1)); long blockToRewind = blocksToGenerate / 2; indexedBlockStore.rewind(blockToRewind); bestBlock = indexedBlockStore.getBestBlock(); assertThat(bestBlock.getNumber(), is(blockToRewind)); }
### Question: 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(federationPublicKeys) ); } Constants( byte chainId, boolean seedCowAccounts, int durationLimit, BlockDifficulty minimumDifficulty, BlockDifficulty fallbackMiningDifficulty, BigInteger difficultyBoundDivisor, int newBlockMaxSecondsInTheFuture, BridgeConstants bridgeConstants); boolean seedCowAccounts(); int getDurationLimit(); BlockDifficulty getMinimumDifficulty(); BlockDifficulty getFallbackMiningDifficulty(); BigInteger getDifficultyBoundDivisor(ActivationConfig.ForBlock activationConfig); byte getChainId(); int getNewBlockMaxSecondsInTheFuture(); BridgeConstants getBridgeConstants(); BigInteger getInitialNonce(); byte[] getFallbackMiningPubKey0(); byte[] getFallbackMiningPubKey1(); int getMaximumExtraDataSize(); int getMinGasLimit(); int getGasLimitBoundDivisor(); int getExpDifficultyPeriod(); int getUncleGenerationLimit(); int getUncleListLimit(); int getBestNumberDiffLimit(); BigInteger getMinimumPayableGas(); BigInteger getFederatorMinimumPayableGas(); static BigInteger getSECP256K1N(); static BigInteger getTransactionGasCap(); static int getMaxContractSize(); static int getMaxAddressByteLength(); static Constants mainnet(); static Constants devnetWithFederation(List<BtcECKey> federationPublicKeys); static Constants testnet(); static Constants regtest(); static Constants regtestWithFederation(List<BtcECKey> genesisFederationPublicKeys); static final byte MAINNET_CHAIN_ID; static final byte TESTNET_CHAIN_ID; static final byte DEVNET_CHAIN_ID; static final byte REGTEST_CHAIN_ID; final BridgeConstants bridgeConstants; }### Answer: @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().hasBtcPublicKey(TEST_FED_KEYS.get(1)), is(true)); assertThat(constants.getBridgeConstants().getGenesisFederation().hasBtcPublicKey(TEST_FED_KEYS.get(2)), is(true)); assertThat(constants.getBridgeConstants().getGenesisFederation().hasBtcPublicKey(TEST_FED_KEYS.get(3)), is(false)); }
### Question: 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()) { NetworkUpgrade networkUpgrade = NetworkUpgrade.named(e.getKey()); long activationHeight = networkUpgradesConfig.getLong(networkUpgrade.getName()); networkUpgrades.put(networkUpgrade, activationHeight); } Map<ConsensusRule, Long> activationHeights = new EnumMap<>(ConsensusRule.class); Config consensusRulesConfig = config.getConfig(PROPERTY_CONSENSUS_RULES); for (Map.Entry<String, ConfigValue> e : consensusRulesConfig.entrySet()) { ConsensusRule consensusRule = ConsensusRule.fromConfigKey(e.getKey()); long activationHeight = parseActivationHeight(networkUpgrades, consensusRulesConfig, consensusRule); activationHeights.put(consensusRule, activationHeight); } return new ActivationConfig(activationHeights); } ActivationConfig(Map<ConsensusRule, Long> activationHeights); boolean isActive(ConsensusRule consensusRule, long blockNumber); ForBlock forBlock(long blockNumber); static ActivationConfig read(Config config); }### Answer: @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 .withoutPath("hardforkActivationHeights.orchid") ); } @Test(expected = IllegalArgumentException.class) public void failsReadingWithUnknownForkConfiguration() { ActivationConfig.read(BASE_CONFIG .withValue("hardforkActivationHeights.orkid", ConfigValueFactory.fromAnyRef(200)) ); } @Test(expected = IllegalArgumentException.class) public void failsReadingWithUnknownUpgradeConfiguration() { ActivationConfig.read(BASE_CONFIG .withValue("consensusRules.rskip420", ConfigValueFactory.fromAnyRef("orchid")) ); }
### Question: 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().toBigInteger(); token = ByteUtil.bigIntegerToBytes(secretScalar, NONCE_SIZE); } else { isToken = true; } byte[] nonce = initiatorNonce; byte[] signed = xor(token, nonce); message.setSignature(ECDSASignature.fromSignature(ephemeralKey.sign(signed))); message.isTokenUsed = isToken; message.ephemeralPublicHash = keccak256(ephemeralKey.getPubKeyPoint().getEncoded(false), 1, 64); message.publicKey = key.getPubKeyPoint(); message.nonce = initiatorNonce; return message; } EncryptionHandshake(ECPoint remotePublicKey); EncryptionHandshake(ECPoint remotePublicKey, ECKey ephemeralKey, byte[] initiatorNonce, byte[] responderNonce, boolean isInitiator); EncryptionHandshake(); AuthInitiateMessageV4 createAuthInitiateV4(ECKey key); byte[] encryptAuthInitiateV4(AuthInitiateMessageV4 message); AuthInitiateMessageV4 decryptAuthInitiateV4(byte[] in, ECKey myKey); byte[] encryptAuthResponseV4(AuthResponseMessageV4 message); AuthResponseMessageV4 decryptAuthResponseV4(byte[] in, ECKey myKey); AuthResponseMessageV4 handleAuthResponseV4(ECKey myKey, byte[] initiatePacket, byte[] responsePacket); AuthInitiateMessage createAuthInitiate(@Nullable byte[] token, ECKey key); byte[] encryptAuthMessage(AuthInitiateMessage message); byte[] encryptAuthResponse(AuthResponseMessage message); AuthResponseMessage decryptAuthResponse(byte[] ciphertext, ECKey myKey); AuthInitiateMessage decryptAuthInitiate(byte[] ciphertext, ECKey myKey); AuthResponseMessage handleAuthResponse(ECKey myKey, byte[] initiatePacket, byte[] responsePacket); byte[] handleAuthInitiate(byte[] initiatePacket, ECKey key); static byte recIdFromSignatureV(int v); Secrets getSecrets(); ECPoint getRemotePublicKey(); boolean isInitiator(); static final int NONCE_SIZE; static final int MAC_SIZE; static final int SECRET_SIZE; }### Answer: @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); }
### Question: 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 getAddress(); String getAddressAsString(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object o); }### Answer: @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.assertTrue(address, matcher.matches()); node = new Node(NODE_ID_1, NODE_HOST_1, NODE_PORT_1); address = node.getAddressAsString(); Assert.assertTrue(StringUtils.isNotBlank(address)); Assert.assertTrue(address.startsWith(NODE_HOST_1)); }
### Question: 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()); foundNodes.stream().filter(n -> !nodeHandlerMap.containsKey(n.getHexId())).forEach(this::createNodeHandler); } for(NodeHandler handler : this.nodeHandlerMap.values()) { if(!nodesInUse.contains(handler.getNode().getHexId())) { handlers.add(handler); } } return handlers; } NodeManager(PeerExplorer peerExplorer, SystemProperties config); NodeStatistics getNodeStatistics(Node n); synchronized List<NodeHandler> getNodes(Set<String> nodesInUse); }### Answer: @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(activePeers); Mockito.when(peerExplorer.getNodes()).thenReturn(bootNodes); Mockito.when(config.isPeerDiscoveryEnabled()).thenReturn(false); NodeManager nodeManager = new NodeManager(peerExplorer, config); Set<String> nodesInUse = new HashSet<>(); List<NodeHandler> availableNodes = nodeManager.getNodes(nodesInUse); Assert.assertEquals(1, availableNodes.size()); Assert.assertEquals(NODE_ID_2, availableNodes.get(0).getNode().getHexId()); nodesInUse.add(NODE_ID_2); availableNodes = nodeManager.getNodes(nodesInUse); Assert.assertEquals(0, availableNodes.size()); } @Test public void getNodesPeerDiscoveryEnableNoPeersFound() { List<Node> activePeers = new ArrayList<>(); List<Node> bootNodes = new ArrayList<>(); Mockito.when(config.peerActive()).thenReturn(activePeers); Mockito.when(peerExplorer.getNodes()).thenReturn(bootNodes); Mockito.when(config.isPeerDiscoveryEnabled()).thenReturn(true); NodeManager nodeManager = new NodeManager(peerExplorer, config); Set<String> nodesInUse = new HashSet<>(); List<NodeHandler> availableNodes = nodeManager.getNodes(nodesInUse); Assert.assertEquals(0, availableNodes.size()); } @Test public void getNodesPeerDiscoveryEnable() { 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(activePeers); Mockito.when(peerExplorer.getNodes()).thenReturn(bootNodes); Mockito.when(config.isPeerDiscoveryEnabled()).thenReturn(true); NodeManager nodeManager = new NodeManager(peerExplorer, config); Set<String> nodesInUse = new HashSet<>(); List<NodeHandler> availableNodes = nodeManager.getNodes(nodesInUse); Assert.assertEquals(2, availableNodes.size()); }
### Question: 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); }### Answer: @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[32]; random.nextBytes(nodeId); Node node = new Node(nodeId, "127.0.0.1", 8080); keys.add(node.getHexId()); nodeManager.getNodeStatistics(node); } Map<String, NodeHandler> nodeHandlerMap = Whitebox.getInternalState(nodeManager, "nodeHandlerMap"); Assert.assertTrue(nodeHandlerMap.size() <= NodeManager.NODES_TRIM_THRESHOLD); }
### Question: Channel implements Peer { public void setInetSocketAddress(InetSocketAddress inetSocketAddress) { this.inetSocketAddress = inetSocketAddress; } Channel(MessageQueue msgQueue, MessageCodec messageCodec, NodeManager nodeManager, RskWireProtocol.Factory rskWireProtocolFactory, Eth62MessageFactory eth62MessageFactory, StaticMessages staticMessages, String remoteId); void sendHelloMessage(ChannelHandlerContext ctx, FrameCodec frameCodec, String nodeId, HelloMessage inboundHelloMessage); void activateEth(ChannelHandlerContext ctx, EthVersion version); void setInetSocketAddress(InetSocketAddress inetSocketAddress); NodeStatistics getNodeStatistics(); void setNode(byte[] nodeId); Node getNode(); void initMessageCodes(List<Capability> caps); boolean isProtocolsInitialized(); boolean isUsingNewProtocol(); void onDisconnect(); String getPeerId(); boolean isActive(); NodeID getNodeId(); void disconnect(ReasonCode reason); InetSocketAddress getInetSocketAddress(); PeerStatistics getPeerStats(); boolean hasEthStatusSucceeded(); BigInteger getTotalDifficulty(); SyncStatistics getSyncStats(); void dropConnection(); void sendMessage(Message message); @Override NodeID getPeerNodeID(); @Override InetAddress getAddress(); Stats getStats(); @Override boolean equals(Object o); @Override int hashCode(); @Override double score(long currentTime, MessageType type); @Override void imported(boolean best); @Override String toString(); }### Answer: @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.setInetSocketAddress(inetSocketAddress); assertEquals(target, otherChannel); } @Test public void equals_false() { InetSocketAddress inetSocketAddress = mock(InetSocketAddress.class); Channel otherChannel = new Channel( messageQueue, messageCodec, nodeManager, rskWireProtocolFactory, eth62MessageFactory, staticMessages, remoteId); target.setInetSocketAddress(inetSocketAddress); assertNotEquals(target, otherChannel); }
### Question: 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 start(); @Override void stop(); @VisibleForTesting void tryProcessNewPeers(); boolean isRecentlyDisconnected(InetAddress peerAddress); @Nonnull Set<NodeID> broadcastBlock(@Nonnull final Block block); @Nonnull Set<NodeID> broadcastBlockHash(@Nonnull final List<BlockIdentifier> identifiers, final Set<NodeID> targets); @Override int broadcastStatus(Status status); void add(Channel peer); void notifyDisconnect(Channel channel); Collection<Peer> getActivePeers(); boolean isAddressBlockAvailable(InetAddress inetAddress); @Nonnull Set<NodeID> broadcastTransaction(@Nonnull final Transaction transaction, @Nonnull final Set<NodeID> skip); @Override Set<NodeID> broadcastTransactions(@Nonnull final List<Transaction> transactions, @Nonnull final Set<NodeID> skip); @VisibleForTesting void setActivePeers(Map<NodeID, Channel> newActivePeers); }### Answer: @Test public void getNumberOfPeersToSendStatusTo() { ChannelManagerImpl channelManagerImpl = new ChannelManagerImpl(new TestSystemProperties(), null);; assertEquals(1, channelManagerImpl.getNumberOfPeersToSendStatusTo(1)); assertEquals(2, channelManagerImpl.getNumberOfPeersToSendStatusTo(2)); assertEquals(3, channelManagerImpl.getNumberOfPeersToSendStatusTo(3)); assertEquals(3, channelManagerImpl.getNumberOfPeersToSendStatusTo(5)); assertEquals(3, channelManagerImpl.getNumberOfPeersToSendStatusTo(9)); assertEquals(3, channelManagerImpl.getNumberOfPeersToSendStatusTo(12)); assertEquals(4, channelManagerImpl.getNumberOfPeersToSendStatusTo(20)); assertEquals(5, channelManagerImpl.getNumberOfPeersToSendStatusTo(25)); assertEquals(10, channelManagerImpl.getNumberOfPeersToSendStatusTo(1000)); }
### Question: 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)) .count() < maxConnectionsAllowed; } } ChannelManagerImpl(RskSystemProperties config, SyncPool syncPool); @Override void start(); @Override void stop(); @VisibleForTesting void tryProcessNewPeers(); boolean isRecentlyDisconnected(InetAddress peerAddress); @Nonnull Set<NodeID> broadcastBlock(@Nonnull final Block block); @Nonnull Set<NodeID> broadcastBlockHash(@Nonnull final List<BlockIdentifier> identifiers, final Set<NodeID> targets); @Override int broadcastStatus(Status status); void add(Channel peer); void notifyDisconnect(Channel channel); Collection<Peer> getActivePeers(); boolean isAddressBlockAvailable(InetAddress inetAddress); @Nonnull Set<NodeID> broadcastTransaction(@Nonnull final Transaction transaction, @Nonnull final Set<NodeID> skip); @Override Set<NodeID> broadcastTransactions(@Nonnull final List<Transaction> transactions, @Nonnull final Set<NodeID> skip); @VisibleForTesting void setActivePeers(Map<NodeID, Channel> newActivePeers); }### Answer: @Test public void blockAddressIsAvailable() throws UnknownHostException { ChannelManagerImpl channelManagerImpl = new ChannelManagerImpl(new TestSystemProperties(), null);; Assert.assertTrue(channelManagerImpl.isAddressBlockAvailable(InetAddress.getLocalHost())); }
### Question: 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(block); final Message newBlockHashes = new NewBlockHashesMessage(Arrays.asList(bi)); synchronized (activePeersLock) { activePeers.values().forEach(c -> logger.trace("RSK activePeers: {}", c)); List<Channel> peers = new ArrayList<>(activePeers.values()); Collections.shuffle(peers); int sqrt = (int) Math.floor(Math.sqrt(peers.size())); for (int i = 0; i < sqrt; i++) { Channel peer = peers.get(i); nodesIdsBroadcastedTo.add(peer.getNodeId()); logger.trace("RSK propagate: {}", peer); peer.sendMessage(newBlock); } for (int i = sqrt; i < peers.size(); i++) { Channel peer = peers.get(i); logger.trace("RSK announce: {}", peer); peer.sendMessage(newBlockHashes); } } return nodesIdsBroadcastedTo; } ChannelManagerImpl(RskSystemProperties config, SyncPool syncPool); @Override void start(); @Override void stop(); @VisibleForTesting void tryProcessNewPeers(); boolean isRecentlyDisconnected(InetAddress peerAddress); @Nonnull Set<NodeID> broadcastBlock(@Nonnull final Block block); @Nonnull Set<NodeID> broadcastBlockHash(@Nonnull final List<BlockIdentifier> identifiers, final Set<NodeID> targets); @Override int broadcastStatus(Status status); void add(Channel peer); void notifyDisconnect(Channel channel); Collection<Peer> getActivePeers(); boolean isAddressBlockAvailable(InetAddress inetAddress); @Nonnull Set<NodeID> broadcastTransaction(@Nonnull final Transaction transaction, @Nonnull final Set<NodeID> skip); @Override Set<NodeID> broadcastTransactions(@Nonnull final List<Transaction> transactions, @Nonnull final Set<NodeID> skip); @VisibleForTesting void setActivePeers(Map<NodeID, Channel> newActivePeers); }### Answer: @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()); }
### Question: 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, byte[] value); @Override void delete(byte[] key); @Override Set<byte[]> keys(); @Override void updateBatch(Map<ByteArrayWrapper, byte[]> rows, Set<ByteArrayWrapper> keysToRemove); @Override void flush(); String getName(); void init(); boolean isAlive(); void close(); }### Answer: @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)); }
### Question: 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().map(ByteArrayWrapper::new); committedKeys = committedCache.entrySet().stream() .filter(e -> e.getValue() != null) .map(Map.Entry::getKey); uncommittedKeys = uncommittedCache.entrySet().stream() .filter(e -> e.getValue() != null) .map(Map.Entry::getKey); uncommittedKeysToRemove = uncommittedCache.entrySet().stream() .filter(e -> e.getValue() == null) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } finally { this.lock.readLock().unlock(); } Set<ByteArrayWrapper> knownKeys = Stream.concat(Stream.concat(baseKeys, committedKeys), uncommittedKeys) .collect(Collectors.toSet()); knownKeys.removeAll(uncommittedKeysToRemove); return knownKeys.stream() .map(ByteArrayWrapper::getData) .collect(Collectors.toSet()); } DataSourceWithCache(KeyValueDataSource base, int cacheSize); @Override byte[] get(byte[] key); @Override byte[] put(byte[] key, byte[] value); @Override void delete(byte[] key); @Override Set<byte[]> keys(); @Override void updateBatch(Map<ByteArrayWrapper, byte[]> rows, Set<ByteArrayWrapper> keysToRemove); @Override void flush(); String getName(); void init(); boolean isAlive(); void close(); }### Answer: @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(dataSourceWithCache.keys(), is(initialKeys)); byte[] randomKey = TestUtils.randomBytes(20); dataSourceWithCache.get(randomKey); assertThat(dataSourceWithCache.keys(), not(hasItem(randomKey))); }
### Question: 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<byte[]> keys(); @Override void updateBatch(Map<ByteArrayWrapper, byte[]> rows, Set<ByteArrayWrapper> keysToRemove); @Override void flush(); String getName(); void init(); boolean isAlive(); void close(); }### Answer: @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())); }
### Question: 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(keysToRemove); this.lock.writeLock().lock(); try { rows.forEach(this::put); keysToRemove.forEach(this::delete); } finally { this.lock.writeLock().unlock(); } } DataSourceWithCache(KeyValueDataSource base, int cacheSize); @Override byte[] get(byte[] key); @Override byte[] put(byte[] key, byte[] value); @Override void delete(byte[] key); @Override Set<byte[]> keys(); @Override void updateBatch(Map<ByteArrayWrapper, byte[]> rows, Set<ByteArrayWrapper> keysToRemove); @Override void flush(); String getName(); void init(); boolean isAlive(); void close(); }### Answer: @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()); dataSourceWithCache.updateBatch(Collections.emptyMap(), keysToBatchRemove); dataSourceWithCache.flush(); for (ByteArrayWrapper removedKey : keysToBatchRemove) { assertThat(baseDataSource.get(removedKey.getData()), is(nullValue())); } }
### Question: TransactionSet { public List<Transaction> getTransactions() { return transactionsByHash.values().stream() .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } TransactionSet(); TransactionSet(TransactionSet transactionSet); TransactionSet(Map<Keccak256, Transaction> transactionsByHash, Map<RskAddress, List<Transaction>> transactionsByAddress); void addTransaction(Transaction transaction); boolean hasTransaction(Transaction transaction); void removeTransactionByHash(Keccak256 hash); List<Transaction> getTransactions(); List<Transaction> getTransactionsWithSender(RskAddress senderAddress); }### Answer: @Test public void getEmptyTransactionList() { TransactionSet txset = new TransactionSet(); List<Transaction> result = txset.getTransactions(); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); }
### Question: 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>> transactionsByAddress); void addTransaction(Transaction transaction); boolean hasTransaction(Transaction transaction); void removeTransactionByHash(Keccak256 hash); List<Transaction> getTransactions(); List<Transaction> getTransactionsWithSender(RskAddress senderAddress); }### Answer: @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); Assert.assertTrue(txset.hasTransaction(transaction1)); Assert.assertTrue(txset.hasTransaction(transaction2)); Assert.assertFalse(txset.hasTransaction(transaction3)); }
### Question: 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(Map<Keccak256, Transaction> transactionsByHash, Map<RskAddress, List<Transaction>> transactionsByAddress); void addTransaction(Transaction transaction); boolean hasTransaction(Transaction transaction); void removeTransactionByHash(Keccak256 hash); List<Transaction> getTransactions(); List<Transaction> getTransactionsWithSender(RskAddress senderAddress); }### Answer: @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()); }
### Question: 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, byte[] r, byte[] s, byte v); Transaction(long nonce, long gasPrice, long gas, String to, long value, byte[] data, byte chainId); Transaction(BigInteger nonce, BigInteger gasPrice, BigInteger gas, String to, BigInteger value, byte[] data, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String data, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, byte[] decodedData, byte chainId); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] valueRaw, byte[] data, byte chainId); Transaction toImmutableTransaction(); long transactionCost(Constants constants, ActivationConfig.ForBlock activations); void verify(); Keccak256 getHash(); Keccak256 getRawHash(); byte[] getNonce(); Coin getValue(); RskAddress getReceiveAddress(); Coin getGasPrice(); byte[] getGasLimit(); byte[] getData(); ECDSASignature getSignature(); boolean acceptTransactionSignature(byte currentChainId); void sign(byte[] privKeyBytes); void setSignature(ECDSASignature signature); void setSignature(ECKey.ECDSASignature signature); @Nullable RskAddress getContractAddress(); boolean isContractCreation(); ECKey getKey(); synchronized RskAddress getSender(); synchronized RskAddress getSender(SignatureCache signatureCache); byte getChainId(); @Override String toString(); byte[] getEncodedRaw(); byte[] getEncoded(); BigInteger getGasLimitAsInteger(); BigInteger getNonceAsInteger(); @Override int hashCode(); @Override boolean equals(Object obj); boolean isLocalCallTransaction(); void setLocalCallTransaction(boolean isLocalCall); boolean isRemascTransaction(int txPosition, int txsSize); static final int DATAWORD_LENGTH; }### Answer: @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 byte[0], gasPrice, gas, ecKey.getAddress(), value.toByteArray(),null); try { tx.verify(); } catch (Exception e) { fail(e.getMessage()); } }
### Question: 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=" + value + ", data=" + ByteUtil.toHexStringOrEmpty(data) + ", signatureV=" + (signature == null ? "" : signature.getV()) + ", signatureR=" + (signature == null ? "" : ByteUtil.toHexStringOrEmpty(BigIntegers.asUnsignedByteArray(signature.getR()))) + ", signatureS=" + (signature == null ? "" : ByteUtil.toHexStringOrEmpty(BigIntegers.asUnsignedByteArray(signature.getS()))) + "]"; } 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, byte[] r, byte[] s, byte v); Transaction(long nonce, long gasPrice, long gas, String to, long value, byte[] data, byte chainId); Transaction(BigInteger nonce, BigInteger gasPrice, BigInteger gas, String to, BigInteger value, byte[] data, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String data, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, byte[] decodedData, byte chainId); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] valueRaw, byte[] data, byte chainId); Transaction toImmutableTransaction(); long transactionCost(Constants constants, ActivationConfig.ForBlock activations); void verify(); Keccak256 getHash(); Keccak256 getRawHash(); byte[] getNonce(); Coin getValue(); RskAddress getReceiveAddress(); Coin getGasPrice(); byte[] getGasLimit(); byte[] getData(); ECDSASignature getSignature(); boolean acceptTransactionSignature(byte currentChainId); void sign(byte[] privKeyBytes); void setSignature(ECDSASignature signature); void setSignature(ECKey.ECDSASignature signature); @Nullable RskAddress getContractAddress(); boolean isContractCreation(); ECKey getKey(); synchronized RskAddress getSender(); synchronized RskAddress getSender(SignatureCache signatureCache); byte getChainId(); @Override String toString(); byte[] getEncodedRaw(); byte[] getEncoded(); BigInteger getGasLimitAsInteger(); BigInteger getNonceAsInteger(); @Override int hashCode(); @Override boolean equals(Object obj); boolean isLocalCallTransaction(); void setLocalCallTransaction(boolean isLocalCall); boolean isRemascTransaction(int txPosition, int txsSize); static final int DATAWORD_LENGTH; }### Answer: @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); Transaction tx = new ImmutableTransaction(rawData); try { tx.toString(); } catch (Exception e) { fail(e.getMessage()); } }
### Question: 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, astateFlags); } else { this.rlpEncoded = RLP.encodeList(anonce, abalance); } } return rlpEncoded; } AccountState(); AccountState(BigInteger nonce, Coin balance); AccountState(byte[] rlpData); BigInteger getNonce(); void setNonce(BigInteger nonce); void incrementNonce(); Coin getBalance(); Coin addToBalance(Coin value); byte[] getEncoded(); void setDeleted(boolean deleted); boolean isDeleted(); AccountState clone(); String toString(); int getStateFlags(); void setStateFlags(int s); Boolean isHibernated(); void hibernate(); void wakeUp(); }### Answer: @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())); }
### Question: 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("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } DifficultyRule(DifficultyCalculator difficultyCalculator); @Override boolean validate(BlockHeader header, BlockHeader parent); }### Answer: @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(10000); assertFalse(rule.validate(header, parent)); }
### Question: 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; } @Override boolean validate(BlockHeader header, BlockHeader parent); }### Answer: @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(rule.validate(header, parent)); } @Test public void parentNumberGreaterThanBlockNumber() { BlockHeader header = getHeader(100); BlockHeader parent = getHeader(101); assertFalse(rule.validate(header, parent)); }
### Question: 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(gasLimitBoundDivisor); if (headerGasLimit.compareTo(parentGasLimit.subtract(deltaLimit)) < 0 || headerGasLimit.compareTo(parentGasLimit.add(deltaLimit)) > 0) { logger.error(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } ParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean validate(BlockHeader header, BlockHeader parent); }### Answer: @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.validate(header, parent)); } @Test public void parentGasLimitGreaterThanGasLimit() { BlockHeader header = getHeader(10000); BlockHeader parent = getHeader(10001); assertTrue(rule.validate(header, parent)); } @Test public void parentGasLimitTooGreaterThanGasLimit() { BlockHeader header = getHeader(9); BlockHeader parent = getHeader(100); assertFalse(rule.validate(header, parent)); } @Test public void parentGasLimitOfBy1Tests() { BlockHeader parent = getHeader(2049); BlockHeader headerGGood = getHeader(2051); BlockHeader headerGBad = getHeader(2052); BlockHeader headerLGood = getHeader(2047); BlockHeader headerLBad = getHeader(2046); assertTrue(rule.validate(headerGGood, parent)); assertTrue(rule.validate(headerLGood, parent)); assertFalse(rule.validate(headerGBad, parent)); assertFalse(rule.validate(headerLBad, parent)); }
### Question: 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(BigInteger big); static long toGas(long number); static long add(long x, long y); static long multiply(long x, long y); static long subtract(long x, long y); static long calculateTotal(long baseCost, long unitCost, long units); static final long STEP; static final long SSTORE; static final long ZEROSTEP; static final long QUICKSTEP; static final long FASTESTSTEP; static final long FASTSTEP; static final long MIDSTEP; static final long SLOWSTEP; static final long EXTSTEP; static final long GENESISGASLIMIT; static final long MINGASLIMIT; static final long BALANCE; static final long SHA3; static final long SHA3_WORD; static final long SLOAD; static final long STOP; static final long SUICIDE; static final long CLEAR_SSTORE; static final long SET_SSTORE; static final long RESET_SSTORE; static final long REFUND_SSTORE; static final long CREATE; static final long JUMPDEST; static final long CREATE_DATA_BYTE; static final long CALL; static final long STIPEND_CALL; static final long VT_CALL; static final long NEW_ACCT_CALL; static final long MEMORY; static final long MEMORY_V1; static final long SUICIDE_REFUND; static final long QUAD_COEFF_DIV; static final long CREATE_DATA; static final long REPLACE_DATA; static final long TX_NO_ZERO_DATA; static final long TX_ZERO_DATA; static final long TRANSACTION; static final long TRANSACTION_DEFAULT; static final long TRANSACTION_CREATE_CONTRACT; static final long LOG_GAS; static final long LOG_DATA_GAS; static final long LOG_TOPIC_GAS; static final long COPY_GAS; static final long EXP_GAS; static final long EXP_BYTE_GAS; static final long IDENTITY; static final long IDENTITY_WORD; static final long RIPEMD160; static final long RIPEMD160_WORD; static final long SHA256; static final long SHA256_WORD; static final long EC_RECOVER; static final long EXT_CODE_SIZE; static final long EXT_CODE_COPY; static final long EXT_CODE_HASH; static final long CODEREPLACE; static final long NEW_ACCT_SUICIDE; static final long RETURN; static final long MAX_GAS; }### Answer: @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.assertEquals(Long.MAX_VALUE, GasCost.add(1, Long.MAX_VALUE)); Assert.assertEquals(Long.MAX_VALUE, GasCost.add(Long.MAX_VALUE, Long.MAX_VALUE)); } @Test(expected = GasCost.InvalidGasException.class) public void calculateAddGasCostWithSecondNegativeInputAndResult() throws GasCost.InvalidGasException { GasCost.add(0, -1); } @Test(expected = GasCost.InvalidGasException.class) public void calculateAddGasCostWithFirstNegativeInputAndResult() throws GasCost.InvalidGasException { GasCost.add(-1, 1); }
### Question: 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 add(long x, long y); static long multiply(long x, long y); static long subtract(long x, long y); static long calculateTotal(long baseCost, long unitCost, long units); static final long STEP; static final long SSTORE; static final long ZEROSTEP; static final long QUICKSTEP; static final long FASTESTSTEP; static final long FASTSTEP; static final long MIDSTEP; static final long SLOWSTEP; static final long EXTSTEP; static final long GENESISGASLIMIT; static final long MINGASLIMIT; static final long BALANCE; static final long SHA3; static final long SHA3_WORD; static final long SLOAD; static final long STOP; static final long SUICIDE; static final long CLEAR_SSTORE; static final long SET_SSTORE; static final long RESET_SSTORE; static final long REFUND_SSTORE; static final long CREATE; static final long JUMPDEST; static final long CREATE_DATA_BYTE; static final long CALL; static final long STIPEND_CALL; static final long VT_CALL; static final long NEW_ACCT_CALL; static final long MEMORY; static final long MEMORY_V1; static final long SUICIDE_REFUND; static final long QUAD_COEFF_DIV; static final long CREATE_DATA; static final long REPLACE_DATA; static final long TX_NO_ZERO_DATA; static final long TX_ZERO_DATA; static final long TRANSACTION; static final long TRANSACTION_DEFAULT; static final long TRANSACTION_CREATE_CONTRACT; static final long LOG_GAS; static final long LOG_DATA_GAS; static final long LOG_TOPIC_GAS; static final long COPY_GAS; static final long EXP_GAS; static final long EXP_BYTE_GAS; static final long IDENTITY; static final long IDENTITY_WORD; static final long RIPEMD160; static final long RIPEMD160_WORD; static final long SHA256; static final long SHA256_WORD; static final long EC_RECOVER; static final long EXT_CODE_SIZE; static final long EXT_CODE_COPY; static final long EXT_CODE_HASH; static final long CODEREPLACE; static final long NEW_ACCT_SUICIDE; static final long RETURN; static final long MAX_GAS; }### Answer: @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.InvalidGasException.class) public void calculateSubtractWithNegativeInput() throws GasCost.InvalidGasException { GasCost.subtract(1, -1); } @Test(expected = GasCost.InvalidGasException.class) public void calculateSubtractWithExtremelyNegativeResult() throws GasCost.InvalidGasException { GasCost.subtract(0, Long.MAX_VALUE); } @Test(expected = GasCost.InvalidGasException.class) public void calculateSubtractGasToInvalidSubtle() throws GasCost.InvalidGasException { GasCost.subtract(1, 2); } @Test(expected = GasCost.InvalidGasException.class) public void calculateSubtractGasToInvalidObvious() throws GasCost.InvalidGasException { GasCost.subtract(1, 159); }
### Question: 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(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; }### Answer: @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().length); }
### Question: 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[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; }### Answer: @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.getData(); DataWord y = DataWord.valueOf(two); byte[] ydata = y.getData(); DataWord result = y.mod(x); assertArrayEquals(xdata, x.getData()); assertArrayEquals(ydata, y.getData()); assertEquals(32, result.getData().length); assertEquals(expected, ByteUtil.toHexString(result.getData())); }
### Question: 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(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; }### Answer: @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()); assertArrayEquals(ydata, y.getData()); assertEquals(32, y.getData().length); assertEquals("0000000000000000000000010000000000000000000000000000000000000000", ByteUtil.toHexString(y.getData())); assertEquals(32, result.getData().length); assertEquals("0000000000000000000000010000000000000000000000000000000000000000", ByteUtil.toHexString(result.getData())); }
### Question: 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[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; }### Answer: @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.getData()); assertArrayEquals(ydata, y.getData()); assertEquals(32, result.getData().length); assertEquals("0000000000000000000000000000000000000000000000000000000000000014", ByteUtil.toHexString(result.getData())); }
### Question: 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(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; }### Answer: @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); }
### Question: 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 DataWord(newdata); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; }### Answer: @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); }
### Question: 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 intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; }### Answer: @Test public void testFromString() { DataWord parsed = DataWord.fromString("01234567890123456789012345678901"); assertEquals(new String(parsed.getData()),"01234567890123456789012345678901"); }
### Question: 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(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; }### Answer: @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); }
### Question: 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[] getGasPrice(); byte[] getGasLimit(); byte[] getToAddress(); byte[] getValue(); byte[] getData(); RskAddress getFromAddress(); }### Answer: @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.assertArrayEquals(expectedGasLimit, byteArrayArgs.getGasLimit()); } @Test public void getGasLimitWhenValueIsEmpty() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); args.gas = ""; CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); String maxGasLimit = "0x5AF3107A4000"; byte[] expectedGasLimit = TypeConverter.stringHexToByteArray(maxGasLimit); Assert.assertArrayEquals(expectedGasLimit, byteArrayArgs.getGasLimit()); }
### Question: EthSubscriptionNotificationEmitter implements EthSubscribeParamsVisitor { @Override public SubscriptionId visit(EthSubscribeNewHeadsParams params, Channel channel) { SubscriptionId subscriptionId = new SubscriptionId(); blockHeader.subscribe(subscriptionId, channel); return subscriptionId; } EthSubscriptionNotificationEmitter( BlockHeaderNotificationEmitter blockHeader, LogsNotificationEmitter logs); @Override SubscriptionId visit(EthSubscribeNewHeadsParams params, Channel channel); @Override SubscriptionId visit(EthSubscribeLogsParams params, Channel channel); boolean unsubscribe(SubscriptionId subscriptionId); void unsubscribe(Channel channel); }### Answer: @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); } @Test public void subscribeToLogs() { Channel channel = mock(Channel.class); EthSubscribeLogsParams params = mock(EthSubscribeLogsParams.class); SubscriptionId subscriptionId = emitter.visit(params, channel); assertThat(subscriptionId, notNullValue()); verify(logs).subscribe(subscriptionId, channel, params); }
### Question: EthSubscriptionNotificationEmitter implements EthSubscribeParamsVisitor { public boolean unsubscribe(SubscriptionId subscriptionId) { boolean unsubscribedBlockHeader = blockHeader.unsubscribe(subscriptionId); boolean unsubscribedLogs = logs.unsubscribe(subscriptionId); return unsubscribedBlockHeader || unsubscribedLogs; } EthSubscriptionNotificationEmitter( BlockHeaderNotificationEmitter blockHeader, LogsNotificationEmitter logs); @Override SubscriptionId visit(EthSubscribeNewHeadsParams params, Channel channel); @Override SubscriptionId visit(EthSubscribeLogsParams params, Channel channel); boolean unsubscribe(SubscriptionId subscriptionId); void unsubscribe(Channel channel); }### Answer: @Test public void unsubscribeUnsuccessfully() { SubscriptionId subscriptionId = mock(SubscriptionId.class); boolean unsubscribed = emitter.unsubscribe(subscriptionId); assertThat(unsubscribed, is(false)); verify(newHeads).unsubscribe(subscriptionId); verify(logs).unsubscribe(subscriptionId); } @Test public void unsubscribeSuccessfullyFromNewHeads() { SubscriptionId subscriptionId = mock(SubscriptionId.class); when(newHeads.unsubscribe(subscriptionId)).thenReturn(true); boolean unsubscribed = emitter.unsubscribe(subscriptionId); assertThat(unsubscribed, is(true)); verify(newHeads).unsubscribe(subscriptionId); verify(logs).unsubscribe(subscriptionId); } @Test public void unsubscribeSuccessfullyFromLogs() { SubscriptionId subscriptionId = mock(SubscriptionId.class); when(logs.unsubscribe(subscriptionId)).thenReturn(true); boolean unsubscribed = emitter.unsubscribe(subscriptionId); assertThat(unsubscribed, is(true)); verify(newHeads).unsubscribe(subscriptionId); verify(logs).unsubscribe(subscriptionId); } @Test public void unsubscribeChannel() { Channel channel = mock(Channel.class); emitter.unsubscribe(channel); verify(newHeads).unsubscribe(channel); verify(logs).unsubscribe(channel); }
### Question: TxPoolModuleImpl implements TxPoolModule { @Override public JsonNode status() { Map<String, JsonNode> txProps = new HashMap<>(); txProps.put(PENDING, jsonNodeFactory.numberNode(transactionPool.getPendingTransactions().size())); txProps.put(QUEUED, jsonNodeFactory.numberNode(transactionPool.getQueuedTransactions().size())); JsonNode node = jsonNodeFactory.objectNode().setAll(txProps); return node; } TxPoolModuleImpl(TransactionPool transactionPool); @Override JsonNode content(); @Override JsonNode inspect(); @Override JsonNode status(); static final String PENDING; static final String QUEUED; }### Answer: @Test public void txpool_status_basic() throws IOException { JsonNode node = txPoolModule.status(); checkFieldIsNumber(node,"pending"); checkFieldIsNumber(node,"queued"); } @Test public void txpool_status_oneTx() throws Exception { Transaction tx = createSampleTransaction(); when(transactionPool.getPendingTransactions()).thenReturn(Collections.singletonList(tx)); JsonNode node = txPoolModule.status(); JsonNode queuedNode = checkFieldIsNumber(node, "queued"); JsonNode pendingNode = checkFieldIsNumber(node, "pending"); Assert.assertEquals(0, queuedNode.asInt()); Assert.assertEquals(1, pendingNode.asInt()); } @Test public void txpool_status_manyPending() throws Exception { Transaction tx1 = createSampleTransaction(); Transaction tx2 = createSampleTransaction(); Transaction tx3 = createSampleTransaction(); List<Transaction> transactions = Arrays.asList(tx1, tx2, tx3); when(transactionPool.getPendingTransactions()).thenReturn(transactions); JsonNode node = txPoolModule.status(); JsonNode queuedNode = checkFieldIsNumber(node, "queued"); JsonNode pendingNode = checkFieldIsNumber(node, "pending"); Assert.assertEquals(0, queuedNode.asInt()); Assert.assertEquals(transactions.size(), pendingNode.asInt()); } @Test public void txpool_status_manyTxs() throws Exception { Transaction tx1 = createSampleTransaction(); Transaction tx2 = createSampleTransaction(); Transaction tx3 = createSampleTransaction(); Transaction tx4 = createSampleTransaction(); List<Transaction> transactions = Arrays.asList(tx1, tx2, tx3); List<Transaction> txs = Arrays.asList(tx1, tx4); when(transactionPool.getPendingTransactions()).thenReturn(transactions); when(transactionPool.getQueuedTransactions()).thenReturn(txs); JsonNode node = txPoolModule.status(); JsonNode queuedNode = checkFieldIsNumber(node, "queued"); JsonNode pendingNode = checkFieldIsNumber(node, "pending"); Assert.assertEquals(txs.size(), queuedNode.asInt()); Assert.assertEquals(transactions.size(), pendingNode.asInt()); }
### Question: CallArgumentsToByteArray { public byte[] getToAddress() { byte[] toAddress = null; if (args.to != null) { toAddress = stringHexToByteArray(args.to); } return toAddress; } CallArgumentsToByteArray(Web3.CallArguments args); byte[] getGasPrice(); byte[] getGasLimit(); byte[] getToAddress(); byte[] getValue(); byte[] getData(); RskAddress getFromAddress(); }### Answer: @Test public void getToAddressWhenValueIsNull() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertNull(byteArrayArgs.getToAddress()); }
### Question: DebugModuleImpl implements DebugModule { @Override public String wireProtocolQueueSize() { long n = messageHandler.getMessageQueueSize(); return TypeConverter.toQuantityJsonHex(n); } DebugModuleImpl( BlockStore blockStore, ReceiptStore receiptStore, MessageHandler messageHandler, BlockExecutor blockExecutor); @Override String wireProtocolQueueSize(); @Override JsonNode traceTransaction(String transactionHash, Map<String, String> traceOptions); }### Answer: @Test public void debug_wireProtocolQueueSize_basic() throws IOException { String result = debugModule.wireProtocolQueueSize(); try { TypeConverter.JSonHexToLong(result); } catch (NumberFormatException e) { Assert.fail("This method is not returning a 0x Long"); } } @Test public void debug_wireProtocolQueueSize_value() throws IOException { when(messageHandler.getMessageQueueSize()).thenReturn(5L); String result = debugModule.wireProtocolQueueSize(); try { long value = TypeConverter.JSonHexToLong(result); Assert.assertEquals(5L, value); } catch (NumberFormatException e) { Assert.fail("This method is not returning a 0x Long"); } }
### Question: EthModule implements EthModuleWallet, EthModuleTransaction { public String call(Web3.CallArguments args, String bnOrId) { String s = null; try { BlockResult blockResult = executionBlockRetriever.getExecutionBlock_workaround(bnOrId); ProgramResult res; if (blockResult.getFinalState() != null) { res = callConstant_workaround(args, blockResult); } else { res = callConstant(args, blockResult.getBlock()); } if (res.isRevert()) { throw RskJsonRpcRequestException.transactionRevertedExecutionError(); } return s = toJsonHex(res.getHReturn()); } finally { LOGGER.debug("eth_call(): {}", s); } } EthModule( BridgeConstants bridgeConstants, byte chainId, Blockchain blockchain, TransactionPool transactionPool, ReversibleTransactionExecutor reversibleTransactionExecutor, ExecutionBlockRetriever executionBlockRetriever, RepositoryLocator repositoryLocator, EthModuleWallet ethModuleWallet, EthModuleTransaction ethModuleTransaction, BridgeSupportFactory bridgeSupportFactory); @Override String[] accounts(); Map<String, Object> bridgeState(); String call(Web3.CallArguments args, String bnOrId); String estimateGas(Web3.CallArguments args); @Override String sendTransaction(Web3.CallArguments args); @Override String sendRawTransaction(String rawData); @Override String sign(String addr, String data); String chainId(); String getCode(String address, String blockId); }### Answer: @Test public void callSmokeTest() { Web3.CallArguments args = new Web3.CallArguments(); BlockResult blockResult = mock(BlockResult.class); Block block = mock(Block.class); ExecutionBlockRetriever retriever = mock(ExecutionBlockRetriever.class); when(retriever.getExecutionBlock_workaround("latest")) .thenReturn(blockResult); when(blockResult.getBlock()).thenReturn(block); byte[] hreturn = TypeConverter.stringToByteArray("hello"); ProgramResult executorResult = mock(ProgramResult.class); when(executorResult.getHReturn()) .thenReturn(hreturn); ReversibleTransactionExecutor executor = mock(ReversibleTransactionExecutor.class); when(executor.executeTransaction(eq(blockResult.getBlock()), any(), any(), any(), any(), any(), any(), any())) .thenReturn(executorResult); EthModule eth = new EthModule( null, anyByte(), null, null, executor, retriever, null, null, null, new BridgeSupportFactory( null, null, null)); String result = eth.call(args, "latest"); assertThat(result, is(TypeConverter.toJsonHex(hreturn))); }
### Question: EthModule implements EthModuleWallet, EthModuleTransaction { public String getCode(String address, String blockId) { if (blockId == null) { throw new NullPointerException(); } String s = null; try { RskAddress addr = new RskAddress(address); AccountInformationProvider accountInformationProvider = getAccountInformationProvider(blockId); if(accountInformationProvider != null) { byte[] code = accountInformationProvider.getCode(addr); if (code == null) { code = new byte[0]; } s = TypeConverter.toJsonHex(code); } return s; } finally { if (LOGGER.isDebugEnabled()) { LOGGER.debug("eth_getCode({}, {}): {}", address, blockId, s); } } } EthModule( BridgeConstants bridgeConstants, byte chainId, Blockchain blockchain, TransactionPool transactionPool, ReversibleTransactionExecutor reversibleTransactionExecutor, ExecutionBlockRetriever executionBlockRetriever, RepositoryLocator repositoryLocator, EthModuleWallet ethModuleWallet, EthModuleTransaction ethModuleTransaction, BridgeSupportFactory bridgeSupportFactory); @Override String[] accounts(); Map<String, Object> bridgeState(); String call(Web3.CallArguments args, String bnOrId); String estimateGas(Web3.CallArguments args); @Override String sendTransaction(Web3.CallArguments args); @Override String sendRawTransaction(String rawData); @Override String sign(String addr, String data); String chainId(); String getCode(String address, String blockId); }### Answer: @Test public void getCode() { byte[] expectedCode = new byte[] {1, 2, 3}; TransactionPool mockTransactionPool = mock(TransactionPool.class); PendingState mockPendingState = mock(PendingState.class); doReturn(expectedCode).when(mockPendingState).getCode(any(RskAddress.class)); doReturn(mockPendingState).when(mockTransactionPool).getPendingState(); EthModule eth = new EthModule( null, (byte) 0, null, mockTransactionPool, null, null, null, null, null, new BridgeSupportFactory( null, null, null ) ); String addr = eth.getCode(TestUtils.randomAddress().toHexString(), "pending"); Assert.assertThat(Hex.decode(addr.substring("0x".length())), is(expectedCode)); }
### Question: EthModule implements EthModuleWallet, EthModuleTransaction { public String chainId() { return TypeConverter.toJsonHex(new byte[] { chainId }); } EthModule( BridgeConstants bridgeConstants, byte chainId, Blockchain blockchain, TransactionPool transactionPool, ReversibleTransactionExecutor reversibleTransactionExecutor, ExecutionBlockRetriever executionBlockRetriever, RepositoryLocator repositoryLocator, EthModuleWallet ethModuleWallet, EthModuleTransaction ethModuleTransaction, BridgeSupportFactory bridgeSupportFactory); @Override String[] accounts(); Map<String, Object> bridgeState(); String call(Web3.CallArguments args, String bnOrId); String estimateGas(Web3.CallArguments args); @Override String sendTransaction(Web3.CallArguments args); @Override String sendRawTransaction(String rawData); @Override String sign(String addr, String data); String chainId(); String getCode(String address, String blockId); }### Answer: @Test public void chainId() { EthModule eth = new EthModule( mock(BridgeConstants.class), (byte) 33, mock(Blockchain.class), mock(TransactionPool.class), mock(ReversibleTransactionExecutor.class), mock(ExecutionBlockRetriever.class), mock(RepositoryLocator.class), mock(EthModuleWallet.class), mock(EthModuleTransaction.class), mock(BridgeSupportFactory.class) ); assertThat(eth.chainId(), is("0x21")); }
### Question: EthUnsubscribeRequest extends RskJsonRpcRequest { @JsonInclude(JsonInclude.Include.NON_NULL) public EthUnsubscribeParams getParams() { return params; } @JsonCreator EthUnsubscribeRequest( @JsonProperty("jsonrpc") JsonRpcVersion version, @JsonProperty("method") RskJsonRpcMethod method, @JsonProperty("id") int id, @JsonProperty("params") EthUnsubscribeParams params); @JsonInclude(JsonInclude.Include.NON_NULL) EthUnsubscribeParams getParams(); @Override JsonRpcResultOrError accept(RskJsonRpcRequestVisitor visitor, ChannelHandlerContext ctx); }### Answer: @Test public void deserializeUnsubscribe() throws IOException { String message = "{\"jsonrpc\":\"2.0\",\"id\":100,\"method\":\"eth_unsubscribe\",\"params\":[\"0x0204\"]}"; RskJsonRpcRequest request = serializer.deserializeRequest( new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)) ); assertThat(request, instanceOf(EthUnsubscribeRequest.class)); EthUnsubscribeRequest unsubscribeRequest = (EthUnsubscribeRequest) request; assertThat(unsubscribeRequest.getParams().getSubscriptionId(), is(new SubscriptionId("0x0204"))); }
### Question: LogsNotification implements EthSubscriptionNotificationDTO { public String getLogIndex() { if (lazyLogIndex == null) { lazyLogIndex = toQuantityJsonHex(logInfoIndex); } return lazyLogIndex; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); }### Answer: @Test public void getLogIndex() { assertThat(logsNotification.getLogIndex(), is(QUANTITY_JSON_HEX)); }
### Question: LogsNotification implements EthSubscriptionNotificationDTO { public String getBlockNumber() { if (lazyBlockNumber == null) { lazyBlockNumber = toQuantityJsonHex(block.getNumber()); } return lazyBlockNumber; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); }### Answer: @Test public void getBlockNumber() { doReturn(42L).when(block).getNumber(); assertThat(logsNotification.getBlockNumber(), is(QUANTITY_JSON_HEX)); }
### Question: LogsNotification implements EthSubscriptionNotificationDTO { public String getBlockHash() { if (lazyBlockHash == null) { lazyBlockHash = block.getHashJsonString(); } return lazyBlockHash; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); }### Answer: @Test public void getBlockHash() { Keccak256 blockHash = TestUtils.randomHash(); doReturn(blockHash).when(block).getHash(); doCallRealMethod().when(block).getHashJsonString(); assertThat(logsNotification.getBlockHash(), is(toUnformattedJsonHex(blockHash.getBytes()))); }
### Question: LogsNotification implements EthSubscriptionNotificationDTO { public String getTransactionHash() { if (lazyTransactionHash == null) { lazyTransactionHash = transaction.getHash().toJsonString(); } return lazyTransactionHash; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); }### Answer: @Test public void getTransactionHash() { Keccak256 transactionHash = TestUtils.randomHash(); doReturn(transactionHash).when(transaction).getHash(); assertThat(logsNotification.getTransactionHash(), is(toUnformattedJsonHex(transactionHash.getBytes()))); }
### Question: LogsNotification implements EthSubscriptionNotificationDTO { public String getTransactionIndex() { if (lazyTransactionIndex == null) { lazyTransactionIndex = toQuantityJsonHex(transactionIndex); } return lazyTransactionIndex; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); }### Answer: @Test public void getTransactionIndex() { assertThat(logsNotification.getTransactionIndex(), is(QUANTITY_JSON_HEX)); }
### Question: LogsNotification implements EthSubscriptionNotificationDTO { public String getAddress() { if (lazyAddress == null) { lazyAddress = toJsonHex(logInfo.getAddress()); } return lazyAddress; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); }### Answer: @Test public void getAddress() { byte[] logSender = TestUtils.randomAddress().getBytes(); doReturn(logSender).when(logInfo).getAddress(); assertThat(logsNotification.getAddress(), is(toJsonHex(logSender))); }
### Question: LogsNotification implements EthSubscriptionNotificationDTO { public String getData() { if (lazyData == null) { lazyData = toJsonHex(logInfo.getData()); } return lazyData; } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); }### Answer: @Test public void getData() { byte[] logData = TestUtils.randomBytes(random.nextInt(1024)); doReturn(logData).when(logInfo).getData(); assertThat(logsNotification.getData(), is(toJsonHex(logData))); }
### Question: LogsNotification implements EthSubscriptionNotificationDTO { public List<String> getTopics() { if (lazyTopics == null) { lazyTopics = logInfo.getTopics().stream() .map(t -> toJsonHex(t.getData())) .collect(Collectors.toList()); } return Collections.unmodifiableList(lazyTopics); } LogsNotification(LogInfo logInfo, Block b, int txIndex, Transaction tx, int logIdx, boolean r); String getLogIndex(); String getBlockNumber(); String getBlockHash(); String getTransactionHash(); String getTransactionIndex(); String getAddress(); String getData(); List<String> getTopics(); @JsonInclude(JsonInclude.Include.NON_EMPTY) boolean getRemoved(); @JsonIgnore LogInfo getLogInfo(); }### Answer: @Test public void getTopics() { List<DataWord> logTopics = IntStream.range(0, random.nextInt(1024)).mapToObj(i -> TestUtils.randomDataWord()).collect(Collectors.toList()); doReturn(logTopics).when(logInfo).getTopics(); for (int i = 0; i < logTopics.size(); i++) { assertThat(logsNotification.getTopics().get(i), is(toJsonHex(logTopics.get(i).getData()))); } }
### Question: BlockHeaderNotificationEmitter { public void subscribe(SubscriptionId subscriptionId, Channel channel) { subscriptions.put(subscriptionId, channel); } BlockHeaderNotificationEmitter(Ethereum ethereum, JsonRpcSerializer jsonRpcSerializer); void subscribe(SubscriptionId subscriptionId, Channel channel); boolean unsubscribe(SubscriptionId subscriptionId); void unsubscribe(Channel channel); }### Answer: @Test public void ethereumOnBlockEventTriggersMessageToChannel() throws JsonProcessingException { SubscriptionId subscriptionId = mock(SubscriptionId.class); Channel channel = mock(Channel.class); emitter.subscribe(subscriptionId, channel); when(serializer.serializeMessage(any())) .thenReturn("serialized"); listener.onBlock(TEST_BLOCK, null); verify(channel).writeAndFlush(new TextWebSocketFrame("serialized")); }
### Question: TraceAddress { @JsonValue public int[] toAddress() { if (this.parent == null) { return EMPTY_ADDRESS; } int[] parentAddress = this.parent.toAddress(); int[] address = Arrays.copyOf(parentAddress, parentAddress.length + 1); address[address.length - 1] = this.index; return address; } TraceAddress(); TraceAddress(TraceAddress parent, int index); @JsonValue int[] toAddress(); }### Answer: @Test public void getTopAddress() { TraceAddress address = new TraceAddress(); Assert.assertArrayEquals(new int[0], address.toAddress()); } @Test public void getChildAddress() { TraceAddress parent = new TraceAddress(); TraceAddress address = new TraceAddress(parent, 1); Assert.assertArrayEquals(new int[] { 1 }, address.toAddress()); } @Test public void getGrandChildAddress() { TraceAddress grandparent = new TraceAddress(); TraceAddress parent = new TraceAddress(grandparent, 1); TraceAddress address = new TraceAddress(parent, 2); Assert.assertArrayEquals(new int[] { 1, 2 }, address.toAddress()); }
### Question: TraceModuleImpl implements TraceModule { @Override public JsonNode traceBlock(String blockArgument) throws Exception { logger.trace("trace_block({})", blockArgument); Block block = this.getByJsonArgument(blockArgument); if (block == null) { logger.trace("No block for {}", blockArgument); return null; } Block parent = this.blockchain.getBlockByHash(block.getParentHash().getBytes()); List<TransactionTrace> blockTraces = new ArrayList<>(); if (block.getNumber() != 0) { ProgramTraceProcessor programTraceProcessor = new ProgramTraceProcessor(); this.blockExecutor.traceBlock(programTraceProcessor, VmConfig.LIGHT_TRACE, block, parent.getHeader(), false, false); for (Transaction tx : block.getTransactionsList()) { TransactionInfo txInfo = receiptStore.getInMainChain(tx.getHash().getBytes(), this.blockStore); txInfo.setTransaction(tx); SummarizedProgramTrace programTrace = (SummarizedProgramTrace) programTraceProcessor.getProgramTrace(tx.getHash()); if (programTrace == null) { return null; } List<TransactionTrace> traces = TraceTransformer.toTraces(programTrace, txInfo, block.getNumber()); blockTraces.addAll(traces); } } ObjectMapper mapper = Serializers.createMapper(true); return mapper.valueToTree(blockTraces); } TraceModuleImpl( Blockchain blockchain, BlockStore blockStore, ReceiptStore receiptStore, BlockExecutor blockExecutor); @Override JsonNode traceTransaction(String transactionHash); @Override JsonNode traceBlock(String blockArgument); }### Answer: @Test public void retrieveUnknownBlockAsNull() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); TraceModuleImpl traceModule = new TraceModuleImpl(world.getBlockChain(), world.getBlockStore(), receiptStore, world.getBlockExecutor()); JsonNode result = traceModule.traceBlock("0x0001020300010203000102030001020300010203000102030001020300010203"); Assert.assertNull(result); }
### Question: RskJsonRpcHandler extends SimpleChannelInboundHandler<ByteBufHolder> implements RskJsonRpcRequestVisitor { @Override public JsonRpcResultOrError visit(EthUnsubscribeRequest request, ChannelHandlerContext ctx) { boolean unsubscribed = emitter.unsubscribe(request.getParams().getSubscriptionId()); return new JsonRpcBooleanResult(unsubscribed); } RskJsonRpcHandler(EthSubscriptionNotificationEmitter emitter, JsonRpcSerializer serializer); @Override void channelInactive(ChannelHandlerContext ctx); @Override JsonRpcResultOrError visit(EthUnsubscribeRequest request, ChannelHandlerContext ctx); @Override JsonRpcResultOrError visit(EthSubscribeRequest request, ChannelHandlerContext ctx); }### Answer: @Test public void visitUnsubscribe() { EthUnsubscribeRequest unsubscribe = new EthUnsubscribeRequest( JsonRpcVersion.V2_0, RskJsonRpcMethod.ETH_UNSUBSCRIBE, 35, new EthUnsubscribeParams(SAMPLE_SUBSCRIPTION_ID) ); when(emitter.unsubscribe(SAMPLE_SUBSCRIPTION_ID)) .thenReturn(true); assertThat( handler.visit(unsubscribe, null), is(new JsonRpcBooleanResult(true)) ); } @Test public void visitSubscribe() { Channel channel = mock(Channel.class); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); when(ctx.channel()) .thenReturn(channel); when(emitter.visit(any(EthSubscribeNewHeadsParams.class), eq(channel))) .thenReturn(SAMPLE_SUBSCRIPTION_ID); assertThat( handler.visit(SAMPLE_SUBSCRIBE_REQUEST, ctx), is(SAMPLE_SUBSCRIPTION_ID) ); } @Test public void handlerDeserializesAndHandlesRequest() throws Exception { Channel channel = mock(Channel.class); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); when(ctx.channel()) .thenReturn(channel); when(serializer.deserializeRequest(any())) .thenReturn(SAMPLE_SUBSCRIBE_REQUEST); when(emitter.visit(any(EthSubscribeNewHeadsParams.class), eq(channel))) .thenReturn(SAMPLE_SUBSCRIPTION_ID); when(serializer.serializeMessage(any())) .thenReturn("serialized"); DefaultByteBufHolder msg = new DefaultByteBufHolder(Unpooled.copiedBuffer("raw".getBytes())); handler.channelRead(ctx, msg); verify(ctx, times(1)).writeAndFlush(new TextWebSocketFrame("serialized")); verify(ctx, never()).fireChannelRead(any()); }
### Question: Web3RskImpl extends Web3Impl { public void ext_dumpState() { Block bestBlcock = blockStore.getBestBlock(); logger.info("Dumping state for block hash {}, block number {}", bestBlcock.getHash(), bestBlcock.getNumber()); networkStateExporter.exportStatus(System.getProperty("user.dir") + "/" + "rskdump.json"); } Web3RskImpl( Ethereum eth, Blockchain blockchain, RskSystemProperties properties, MinerClient minerClient, MinerServer minerServer, PersonalModule personalModule, EthModule ethModule, EvmModule evmModule, TxPoolModule txPoolModule, MnrModule mnrModule, DebugModule debugModule, TraceModule traceModule, RskModule rskModule, ChannelManager channelManager, PeerScoringManager peerScoringManager, NetworkStateExporter networkStateExporter, BlockStore blockStore, ReceiptStore receiptStore, PeerServer peerServer, BlockProcessor nodeBlockProcessor, HashRateCalculator hashRateCalculator, ConfigCapabilities configCapabilities, BuildInfo buildInfo, BlocksBloomStore blocksBloomStore, Web3InformationRetriever retriever); void ext_dumpState(); void ext_dumpBlockchain(long numberOfBlocks, boolean includeUncles); }### Answer: @Test public void web3_ext_dumpState() { Ethereum rsk = mock(Ethereum.class); Blockchain blockchain = mock(Blockchain.class); MiningMainchainView mainchainView = mock(MiningMainchainView.class); NetworkStateExporter networkStateExporter = mock(NetworkStateExporter.class); Mockito.when(networkStateExporter.exportStatus(Mockito.anyString())).thenReturn(true); Block block = mock(Block.class); Mockito.when(block.getHash()).thenReturn(PegTestUtils.createHash3()); Mockito.when(block.getNumber()).thenReturn(1L); BlockStore blockStore = mock(BlockStore.class); Mockito.when(blockStore.getBestBlock()).thenReturn(block); Mockito.when(networkStateExporter.exportStatus(Mockito.anyString())).thenReturn(true); Mockito.when(blockchain.getBestBlock()).thenReturn(block); Wallet wallet = WalletFactory.createWallet(); TestSystemProperties config = new TestSystemProperties(); PersonalModule pm = new PersonalModuleWalletEnabled(config, rsk, wallet, null); EthModule em = new EthModule( config.getNetworkConstants().getBridgeConstants(), config.getNetworkConstants().getChainId(), blockchain, null, null, new ExecutionBlockRetriever(mainchainView, blockchain, null, null), null, new EthModuleWalletEnabled(wallet), null, new BridgeSupportFactory( null, config.getNetworkConstants().getBridgeConstants(), config.getActivationConfig()) ); TxPoolModule tpm = new TxPoolModuleImpl(Web3Mocks.getMockTransactionPool()); DebugModule dm = new DebugModuleImpl(null, null, Web3Mocks.getMockMessageHandler(), null); Web3RskImpl web3 = new Web3RskImpl( rsk, blockchain, config, Web3Mocks.getMockMinerClient(), Web3Mocks.getMockMinerServer(), pm, em, null, tpm, null, dm, null, null, Web3Mocks.getMockChannelManager(), null, networkStateExporter, blockStore, null, null, null, null, null, null, null, null); web3.ext_dumpState(); }
### Question: Web3InformationRetriever { public Optional<Block> getBlock(String identifier) { if (PENDING.equals(identifier)) { throw unimplemented("This method doesn't support 'pending' as a parameter"); } Block block; if (LATEST.equals(identifier)) { block = blockchain.getBestBlock(); } else if (EARLIEST.equals(identifier)) { block = blockchain.getBlockByNumber(0); } else { block = this.blockchain.getBlockByNumber(getBlockNumber(identifier)); } return Optional.ofNullable(block); } Web3InformationRetriever(TransactionPool transactionPool, Blockchain blockchain, RepositoryLocator locator); Optional<Block> getBlock(String identifier); AccountInformationProvider getInformationProvider(String identifier); List<Transaction> getTransactions(String identifier); }### Answer: @Test public void getBlock_pending() { RskJsonRpcRequestException e = TestUtils .assertThrows(RskJsonRpcRequestException.class, () -> target.getBlock("pending")); assertEquals(UNIMPLEMENTED_ERROR_CODE, (int) e.getCode()); } @Test public void getBlock_invalidIdentifier() { RskJsonRpcRequestException e = TestUtils .assertThrows(RskJsonRpcRequestException.class, () -> target.getBlock("pending2")); assertEquals(INVALID_PARAM_ERROR_CODE, (int) e.getCode()); } @Test public void getBlock_latest() { Block bestBlock = mock(Block.class); when(blockchain.getBestBlock()).thenReturn(bestBlock); Optional<Block> result = target.getBlock("latest"); assertTrue(result.isPresent()); assertEquals(bestBlock, result.get()); } @Test public void getBlock_earliest() { Block earliestBlock = mock(Block.class); when(blockchain.getBlockByNumber(0)).thenReturn(earliestBlock); Optional<Block> result = target.getBlock("earliest"); assertTrue(result.isPresent()); assertEquals(earliestBlock, result.get()); } @Test public void getBlock_number() { Block secondBlock = mock(Block.class); when(blockchain.getBlockByNumber(2)).thenReturn(secondBlock); Optional<Block> result = target.getBlock("0x2"); assertTrue(result.isPresent()); assertEquals(secondBlock, result.get()); } @Test public void getBlock_notFound() { Optional<Block> result = target.getBlock("0x2"); assertFalse(result.isPresent()); }
### Question: Web3InformationRetriever { public List<Transaction> getTransactions(String identifier) { if (PENDING.equals(identifier)) { return transactionPool.getPendingTransactions(); } Optional<Block> block = getBlock(identifier); return block.map(Block::getTransactionsList) .orElseThrow(() -> blockNotFound(String.format("Block %s not found", identifier))); } Web3InformationRetriever(TransactionPool transactionPool, Blockchain blockchain, RepositoryLocator locator); Optional<Block> getBlock(String identifier); AccountInformationProvider getInformationProvider(String identifier); List<Transaction> getTransactions(String identifier); }### Answer: @Test public void getTransactions_pending() { List<Transaction> txs = new LinkedList<>(); txs.add(mock(Transaction.class)); txs.add(mock(Transaction.class)); when(txPool.getPendingTransactions()).thenReturn(txs); List<Transaction> result = target.getTransactions("pending"); assertEquals(txs, result); } @Test public void getTransactions_earliest() { List<Transaction> txs = new LinkedList<>(); txs.add(mock(Transaction.class)); txs.add(mock(Transaction.class)); Block block = mock(Block.class); when(block.getTransactionsList()).thenReturn(txs); when(blockchain.getBlockByNumber(0)).thenReturn(block); List<Transaction> result = target.getTransactions("earliest"); assertEquals(txs, result); } @Test public void getTransactions_latest() { List<Transaction> txs = new LinkedList<>(); txs.add(mock(Transaction.class)); txs.add(mock(Transaction.class)); Block block = mock(Block.class); when(block.getTransactionsList()).thenReturn(txs); when(blockchain.getBestBlock()).thenReturn(block); List<Transaction> result = target.getTransactions("latest"); assertEquals(txs, result); } @Test public void getTransactions_number() { List<Transaction> txs = new LinkedList<>(); txs.add(mock(Transaction.class)); txs.add(mock(Transaction.class)); Block block = mock(Block.class); when(block.getTransactionsList()).thenReturn(txs); when(blockchain.getBlockByNumber(3)).thenReturn(block); List<Transaction> result = target.getTransactions("0x3"); assertEquals(txs, result); } @Test public void getTransactions_blockNotFound() { RskJsonRpcRequestException e = TestUtils .assertThrows(RskJsonRpcRequestException.class, () -> target.getTransactions("0x3")); assertEquals(-32600, (int) e.getCode()); }
### Question: Web3InformationRetriever { public AccountInformationProvider getInformationProvider(String identifier) { if (PENDING.equals(identifier)) { return transactionPool.getPendingState(); } Optional<Block> optBlock = getBlock(identifier); if (!optBlock.isPresent()) { throw blockNotFound(String.format("Block %s not found", identifier)); } Block block = optBlock.get(); return locator.findSnapshotAt(block.getHeader()).orElseThrow(() -> RskJsonRpcRequestException .stateNotFound(String.format("State not found for block with hash %s", block.getHash()))); } Web3InformationRetriever(TransactionPool transactionPool, Blockchain blockchain, RepositoryLocator locator); Optional<Block> getBlock(String identifier); AccountInformationProvider getInformationProvider(String identifier); List<Transaction> getTransactions(String identifier); }### Answer: @Test public void getState_pending() { PendingState aip = mock(PendingState.class); when(txPool.getPendingState()).thenReturn(aip); AccountInformationProvider result = target.getInformationProvider("pending"); assertEquals(aip, result); } @Test public void getState_earliest() { Block block = mock(Block.class); BlockHeader header = mock(BlockHeader.class); when(block.getHeader()).thenReturn(header); when(blockchain.getBlockByNumber(0)).thenReturn(block); RepositorySnapshot snapshot = mock(RepositorySnapshot.class); when(locator.findSnapshotAt(eq(header))).thenReturn(Optional.of(snapshot)); AccountInformationProvider result = target.getInformationProvider("earliest"); assertEquals(snapshot, result); } @Test public void getState_latest() { Block block = mock(Block.class); BlockHeader header = mock(BlockHeader.class); when(block.getHeader()).thenReturn(header); when(blockchain.getBestBlock()).thenReturn(block); RepositorySnapshot snapshot = mock(RepositorySnapshot.class); when(locator.findSnapshotAt(eq(header))).thenReturn(Optional.of(snapshot)); AccountInformationProvider result = target.getInformationProvider("latest"); assertEquals(snapshot, result); } @Test public void getState_number() { Block block = mock(Block.class); BlockHeader header = mock(BlockHeader.class); when(block.getHeader()).thenReturn(header); when(blockchain.getBlockByNumber(4)).thenReturn(block); RepositorySnapshot snapshot = mock(RepositorySnapshot.class); when(locator.findSnapshotAt(eq(header))).thenReturn(Optional.of(snapshot)); AccountInformationProvider result = target.getInformationProvider("0x4"); assertEquals(snapshot, result); } @Test public void getState_blockNotFound() { RskJsonRpcRequestException e = TestUtils .assertThrows(RskJsonRpcRequestException.class, () -> target.getInformationProvider("0x4")); assertEquals("Block 0x4 not found", e.getMessage()); } @Test public void getTransactions_stateNotFound() { Block block = mock(Block.class); BlockHeader header = mock(BlockHeader.class); when(block.getHeader()).thenReturn(header); Keccak256 blockHash = new Keccak256(new byte[32]); when(block.getHash()).thenReturn(blockHash); when(blockchain.getBlockByNumber(4)).thenReturn(block); RskJsonRpcRequestException e = TestUtils .assertThrows(RskJsonRpcRequestException.class, () -> target.getInformationProvider("0x4")); assertEquals("State not found for block with hash " + blockHash.toString(), e.getMessage()); }
### Question: JsonRpcMethodFilter implements RequestInterceptor { @Override public void interceptRequest(JsonNode node) throws IOException { if (node.hasNonNull(JsonRpcBasicServer.METHOD)) { checkMethod(node.get(JsonRpcBasicServer.METHOD).asText()); } } JsonRpcMethodFilter(List<ModuleDescription> modules); @Override void interceptRequest(JsonNode node); }### Answer: @Test public void checkModuleNames() throws Throwable { RequestInterceptor jsonRpcMethodFilter = new JsonRpcMethodFilter(getModules()); jsonRpcMethodFilter.interceptRequest(getMethodInvocation("evm_snapshot")); jsonRpcMethodFilter.interceptRequest(getMethodInvocation("evm_revert")); try { jsonRpcMethodFilter.interceptRequest(getMethodInvocation("evm_reset")); Assert.fail("evm_reset is enabled AND disabled, disabled take precedence"); } catch (IOException ex) { } try { jsonRpcMethodFilter.interceptRequest(getMethodInvocation("evm_increaseTime")); Assert.fail("evm_increaseTime is disabled"); } catch (IOException ex) { } try { jsonRpcMethodFilter.interceptRequest(getMethodInvocation("eth_getBlock")); Assert.fail("The whole eth namespace is disabled"); } catch (IOException ex) { } }
### Question: OriginValidator { public boolean isValidReferer(String referer) { if (this.allowAllOrigins) { return true; } URL refererUrl = null; try { refererUrl = new URL(referer); } catch (MalformedURLException e) { return false; } String refererProtocol = refererUrl.getProtocol(); if (refererProtocol == null) { return false; } String refererHost = refererUrl.getHost(); if (refererHost == null) { return false; } int refererPort = refererUrl.getPort(); for (int k = 0; k < origins.length; k++) { if (refererProtocol.equals(origins[k].getScheme()) && refererHost.equals(origins[k].getHost()) && refererPort == origins[k].getPort()) { return true; } } return false; } OriginValidator(); OriginValidator(String uriList); boolean isValidOrigin(String origin); boolean isValidReferer(String referer); }### Answer: @Test public void invalidRefererWithDifferentProtocol() throws URISyntaxException { OriginValidator validator = new OriginValidator("http: Assert.assertFalse(validator.isValidReferer("https: } @Test public void invalidRefererWithDifferentHost() throws URISyntaxException { OriginValidator validator = new OriginValidator("http: Assert.assertFalse(validator.isValidReferer("http: } @Test public void invalidRefererWithDifferentPort() throws URISyntaxException { OriginValidator validator = new OriginValidator("http: Assert.assertFalse(validator.isValidReferer("http: }
### Question: ModuleDescription { public boolean methodIsInModule(String methodName) { if (methodName == null) { return false; } if (!methodName.startsWith(this.name)) { return false; } if (methodName.length() == this.name.length()) { return false; } if (methodName.charAt(this.name.length()) != '_') { return false; } return true; } ModuleDescription(String name, String version, boolean enabled, List<String> enabledMethods, List<String> disabledMethods); String getName(); String getVersion(); boolean isEnabled(); List<String> getEnabledMethods(); List<String> getDisabledMethods(); boolean methodIsInModule(String methodName); boolean methodIsEnable(String methodName); }### Answer: @Test public void methodIsInModule() { ModuleDescription description = new ModuleDescription("evm", "1.0", true, null, null); Assert.assertTrue(description.methodIsInModule("evm_snapshot")); Assert.assertTrue(description.methodIsInModule("evm_do")); Assert.assertFalse(description.methodIsInModule("eth_getBlock")); Assert.assertFalse(description.methodIsInModule("eth")); Assert.assertFalse(description.methodIsInModule("evm")); Assert.assertFalse(description.methodIsInModule("evm2")); Assert.assertFalse(description.methodIsInModule("evmsnapshot")); Assert.assertFalse(description.methodIsInModule(null)); }
### Question: EncryptedData { public EncryptedData(byte[] initialisationVector, byte[] encryptedBytes) { this.initialisationVector = Arrays.copyOf(initialisationVector, initialisationVector.length); this.encryptedBytes = Arrays.copyOf(encryptedBytes, encryptedBytes.length); } EncryptedData(byte[] initialisationVector, byte[] encryptedBytes); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); final byte[] initialisationVector; final byte[] encryptedBytes; }### Answer: @Test public void testEncryptedData() { EncryptedData ed = new EncryptedData(new byte[]{1,2,3}, new byte[]{4,5,6}); EncryptedData ed2 = new EncryptedData(new byte[]{1,2,3}, new byte[]{4,5,6}); EncryptedData ed3 = new EncryptedData(new byte[]{1,2,3}, new byte[]{4,5,7}); Assert.assertEquals(ed.toString(), ed2.toString()); Assert.assertEquals(ed.hashCode(), ed2.hashCode()); Assert.assertEquals(ed, ed); Assert.assertEquals(ed, ed2); Assert.assertFalse(ed.equals(null)); Assert.assertFalse(ed.equals("aa")); Assert.assertFalse(ed.equals(ed3)); }
### Question: MinerManager { public void mineBlock(MinerClient minerClient, MinerServer minerServer) { minerServer.buildBlockToMine(false); minerClient.mineBlock(); } void mineBlock(MinerClient minerClient, MinerServer minerServer); }### Answer: @Test public void refreshWorkRunOnce() { Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); MinerServerImpl minerServer = getMinerServer(); MinerClientImpl minerClient = getMinerClient(minerServer); MinerClientImpl.RefreshWork refreshWork = minerClient.createRefreshWork(); Assert.assertNotNull(refreshWork); try { minerServer.buildBlockToMine(false); refreshWork.run(); Assert.assertTrue(minerClient.mineBlock()); Assert.assertEquals(1, blockchain.getBestBlock().getNumber()); } finally { refreshWork.cancel(); } } @Test public void refreshWorkRunTwice() { Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); MinerServerImpl minerServer = getMinerServer(); MinerClientImpl minerClient = getMinerClient(minerServer); MinerClientImpl.RefreshWork refreshWork = minerClient.createRefreshWork(); Assert.assertNotNull(refreshWork); try { minerServer.buildBlockToMine( false); refreshWork.run(); Assert.assertTrue(minerClient.mineBlock()); miningMainchainView.addBest(blockchain.getBestBlock().getHeader()); minerServer.buildBlockToMine( false); refreshWork.run(); Assert.assertTrue(minerClient.mineBlock()); Assert.assertEquals(2, blockchain.getBestBlock().getNumber()); } finally { refreshWork.cancel(); } } @Test public void mineBlockTwiceReusingTheSameWork() { Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); MinerServerImpl minerServer = getMinerServer(); MinerClientImpl minerClient = getMinerClient(minerServer); minerServer.buildBlockToMine( false); MinerWork minerWork = minerServer.getWork(); Assert.assertNotNull(minerWork); Assert.assertTrue(minerClient.mineBlock()); Block bestBlock = blockchain.getBestBlock(); Assert.assertNotNull(bestBlock); Assert.assertEquals(1, bestBlock.getNumber()); Assert.assertNotNull(minerServer.getWork()); Assert.assertTrue(minerClient.mineBlock()); List<Block> blocks = blockchain.getBlocksByNumber(1); Assert.assertNotNull(blocks); Assert.assertEquals(2, blocks.size()); Assert.assertFalse(blocks.get(0).getHash().equals(blocks.get(1).getHash())); } @Test public void mineBlockWhileSyncingBlocks() { Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); NodeBlockProcessor nodeBlockProcessor = mock(NodeBlockProcessor.class); when(nodeBlockProcessor.hasBetterBlockToSync()).thenReturn(true); MinerServerImpl minerServer = getMinerServer(); MinerClientImpl minerClient = getMinerClient(nodeBlockProcessor, minerServer); minerServer.buildBlockToMine( false); Assert.assertFalse(minerClient.mineBlock()); Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); } @Test public void mineBlock() { Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); MinerManager manager = new MinerManager(); MinerServerImpl minerServer = getMinerServer(); MinerClientImpl minerClient = getMinerClient(minerServer); manager.mineBlock(minerClient, minerServer); Assert.assertEquals(1, blockchain.getBestBlock().getNumber()); Assert.assertFalse(blockchain.getBestBlock().getTransactionsList().isEmpty()); SnapshotManager snapshotManager = new SnapshotManager(blockchain, blockStore, transactionPool, minerServer); snapshotManager.resetSnapshots(); Assert.assertEquals(0, blockchain.getBestBlock().getNumber()); manager.mineBlock(minerClient, minerServer); miningMainchainView.addBest(blockchain.getBestBlock().getHeader()); manager.mineBlock(minerClient, minerServer); Assert.assertEquals(2, blockchain.getBestBlock().getNumber()); snapshotManager.resetSnapshots(); Assert.assertTrue(transactionPool.getPendingTransactions().isEmpty()); manager.mineBlock(minerClient, minerServer); Assert.assertTrue(transactionPool.getPendingTransactions().isEmpty()); }
### Question: AutoMinerClient implements MinerClient { @Override public boolean isMining() { return this.isMining; } AutoMinerClient(MinerServer minerServer); @Override void start(); @Override boolean isMining(); @Override boolean mineBlock(); @Override void stop(); }### Answer: @Test public void byDefaultIsDisabled() { assertThat(autoMinerClient.isMining(), is(false)); }
### Question: LogFilter extends Filter { @Override public void newBlockReceived(Block b) { if (this.fromLatestBlock) { this.clearEvents(); onBlock(b); } else if (this.toLatestBlock) { onBlock(b); } } LogFilter(AddressesTopicsFilter addressesTopicsFilter, Blockchain blockchain, boolean fromLatestBlock, boolean toLatestBlock); @Override void newBlockReceived(Block b); @Override void newPendingTx(Transaction tx); static LogFilter fromFilterRequest(Web3.FilterRequest fr, Blockchain blockchain, BlocksBloomStore blocksBloomStore); }### Answer: @Test public void noEventsAfterEmptyBlock() { LogFilter filter = new LogFilter(null, null, false, false); Block block = new BlockGenerator().getBlock(1); filter.newBlockReceived(block); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(0, result.length); } @Test public void eventAfterBlockWithEvent() { RskTestFactory factory = new RskTestFactory(); Blockchain blockchain = factory.getBlockchain(); BlockStore blockStore = factory.getBlockStore(); RepositoryLocator repositoryLocator = factory.getRepositoryLocator(); Web3ImplLogsTest.addEmptyBlockToBlockchain(blockchain, blockStore, repositoryLocator, factory.getTrieStore()); Block block = blockchain.getBestBlock(); AddressesTopicsFilter atfilter = new AddressesTopicsFilter(new RskAddress[0], null); LogFilter filter = new LogFilter(atfilter, blockchain, false, true); filter.newBlockReceived(block); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(1, result.length); } @Test public void twoEventsAfterTwoBlocksWithEventAndToLatestBlock() { RskTestFactory factory = new RskTestFactory(); Blockchain blockchain = factory.getBlockchain(); BlockStore blockStore = factory.getBlockStore(); RepositoryLocator repositoryLocator = factory.getRepositoryLocator(); Web3ImplLogsTest.addEmptyBlockToBlockchain(blockchain, blockStore, repositoryLocator, factory.getTrieStore()); Block block = blockchain.getBestBlock(); AddressesTopicsFilter atfilter = new AddressesTopicsFilter(new RskAddress[0], null); LogFilter filter = new LogFilter(atfilter, blockchain, false, true); filter.newBlockReceived(block); filter.newBlockReceived(block); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(2, result.length); } @Test public void onlyOneEventAfterTwoBlocksWithEventAndFromLatestBlock() { RskTestFactory factory = new RskTestFactory(); Blockchain blockchain = factory.getBlockchain(); BlockStore blockStore = factory.getBlockStore(); RepositoryLocator repositoryLocator = factory.getRepositoryLocator(); Web3ImplLogsTest.addEmptyBlockToBlockchain(blockchain, blockStore, repositoryLocator, factory.getTrieStore()); Block block = blockchain.getBestBlock(); AddressesTopicsFilter atfilter = new AddressesTopicsFilter(new RskAddress[0], null); LogFilter filter = new LogFilter(atfilter, blockchain, true, true); filter.newBlockReceived(block); filter.newBlockReceived(block); Object[] result = filter.getEvents(); Assert.assertNotNull(result); Assert.assertEquals(1, result.length); }
### Question: 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(); }### Answer: @Test public void getValueWhenValueIsNull() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertArrayEquals(new byte[] {0}, byteArrayArgs.getValue()); } @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()); }
### Question: MinerClock { public long calculateTimestampForChild(BlockHeader parentHeader) { long previousTimestamp = parentHeader.getTimestamp(); if (isFixedClock) { return previousTimestamp + timeAdjustment; } long ret = clock.instant().plusSeconds(timeAdjustment).getEpochSecond(); return Long.max(ret, previousTimestamp + 1); } MinerClock(boolean isFixedClock, Clock clock); long calculateTimestampForChild(BlockHeader parentHeader); long increaseTime(long seconds); void clearIncreaseTime(); }### Answer: @Test public void timestampForChildIsParentTimestampIfRegtest() { MinerClock minerClock = new MinerClock(true, clock); BlockHeader parent = mockBlockHeaderWithTimestamp(54L); assertEquals( 54L, minerClock.calculateTimestampForChild(parent) ); } @Test public void timestampForChildIsClockTimeIfNotRegtest() { MinerClock minerClock = new MinerClock(false, clock); BlockHeader parent = mockBlockHeaderWithTimestamp(54L); assertEquals( clock.instant().getEpochSecond(), minerClock.calculateTimestampForChild(parent) ); } @Test public void timestampForChildIsTimestampPlusOneIfNotRegtest() { MinerClock minerClock = new MinerClock(false, clock); BlockHeader parent = mockBlockHeaderWithTimestamp(clock.instant().getEpochSecond()); assertEquals( clock.instant().getEpochSecond() + 1, minerClock.calculateTimestampForChild(parent) ); }
### Question: MinimumGasPriceCalculator { public Coin calculate(Coin previousMGP) { BlockGasPriceRange priceRange = new BlockGasPriceRange(previousMGP); if (priceRange.inRange(targetMGP)) { return targetMGP; } if (previousMGP.compareTo(targetMGP) < 0) { return priceRange.getUpperLimit(); } return priceRange.getLowerLimit(); } MinimumGasPriceCalculator(Coin targetMGP); Coin calculate(Coin previousMGP); }### Answer: @Test public void increaseMgp() { Coin target = Coin.valueOf(2000L); Coin prev = Coin.valueOf(1000L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(prev); Assert.assertEquals(Coin.valueOf(1010), mgp); } @Test public void decreaseMGP() { Coin prev = Coin.valueOf(1000L); Coin target = Coin.valueOf(900L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(prev); Assert.assertEquals(Coin.valueOf(990), mgp); } @Test public void mgpOnRage() { Coin prev = Coin.valueOf(1000L); Coin target = Coin.valueOf(995L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(prev); Assert.assertEquals(target, mgp); } @Test public void previousMgpEqualsTarget() { Coin prev = Coin.valueOf(1000L); Coin target = Coin.valueOf(1000L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(prev); Assert.assertEquals(target, mgp); } @Test public void previousValueIsZero() { Coin target = Coin.valueOf(1000L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(Coin.ZERO); Assert.assertEquals(Coin.valueOf(1L), mgp); } @Test public void previousValueIsSmallTargetIsZero() { Coin target = Coin.ZERO; MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); Coin mgp = mgpCalculator.calculate(Coin.valueOf(1L)); Assert.assertEquals(Coin.ZERO, mgp); } @Test public void cantGetMGPtoBeNegative() { Coin previous = Coin.ZERO; Coin target = Coin.valueOf(-100L); MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(target); previous = mgpCalculator.calculate(previous); Assert.assertTrue(previous.compareTo(Coin.valueOf(-1)) > 0); }
### Question: HashRateCalculator { public abstract BigInteger calculateNodeHashRate(Duration duration); HashRateCalculator(BlockStore blockStore, RskCustomCache<Keccak256, BlockHeaderElement> headerCache); void start(); void stop(); abstract BigInteger calculateNodeHashRate(Duration duration); BigInteger calculateNetHashRate(Duration period); }### Answer: @Test public void calculateNodeHashRate() { long ts = System.currentTimeMillis() / 1000L; Mockito.when(blockHeader.getTimestamp()).thenReturn(ts); Mockito.when(blockHeader.getCoinbase()) .thenReturn(NOT_MY_COINBASE) .thenReturn(FAKE_COINBASE) .thenReturn(FAKE_COINBASE) .thenReturn(NOT_MY_COINBASE); Mockito.when(block.getCumulativeDifficulty()).thenReturn(TEST_DIFFICULTY); HashRateCalculator hashRateCalculator = new HashRateCalculatorMining(blockStore, new RskCustomCache<>(1000L), FAKE_COINBASE); BigInteger hashRate = hashRateCalculator.calculateNodeHashRate(Duration.ofHours(1)); Assert.assertEquals(new BigInteger("+2"), hashRate); } @Test public void calculateNodeHashRateWithMiningDisabled() { long ts = System.currentTimeMillis() / 1000L; Mockito.when(blockHeader.getTimestamp()).thenReturn(ts); Mockito.when(blockHeader.getCoinbase()) .thenReturn(NOT_MY_COINBASE) .thenReturn(FAKE_COINBASE) .thenReturn(FAKE_COINBASE) .thenReturn(NOT_MY_COINBASE); Mockito.when(block.getCumulativeDifficulty()).thenReturn(TEST_DIFFICULTY); HashRateCalculator hashRateCalculator = new HashRateCalculatorNonMining(blockStore, new RskCustomCache<>(1000L)); BigInteger hashRate = hashRateCalculator.calculateNodeHashRate(Duration.ofHours(1)); Assert.assertEquals(BigInteger.ZERO, hashRate); } @Test public void calculateNodeHashRateOldBlock() { long ts = System.currentTimeMillis() / 1000L; Mockito.when(blockHeader.getTimestamp()) .thenReturn(ts - 10000L); Mockito.when(blockHeader.getCoinbase()).thenReturn(FAKE_COINBASE); Mockito.when(block.getCumulativeDifficulty()).thenReturn(TEST_DIFFICULTY); HashRateCalculator hashRateCalculator = new HashRateCalculatorMining(blockStore, new RskCustomCache<>(1000L), FAKE_COINBASE); BigInteger hashRate = hashRateCalculator.calculateNodeHashRate(Duration.ofHours(1)); Assert.assertEquals(hashRate, BigInteger.ZERO); }
### Question: HashRateCalculator { public BigInteger calculateNetHashRate(Duration period) { return calculateHashRate(b -> true, period); } HashRateCalculator(BlockStore blockStore, RskCustomCache<Keccak256, BlockHeaderElement> headerCache); void start(); void stop(); abstract BigInteger calculateNodeHashRate(Duration duration); BigInteger calculateNetHashRate(Duration period); }### Answer: @Test public void calculateNetHashRate() { long ts = System.currentTimeMillis() / 1000L; Mockito.when(blockHeader.getTimestamp()).thenReturn(ts); Mockito.when(blockHeader.getCoinbase()) .thenReturn(NOT_MY_COINBASE) .thenReturn(FAKE_COINBASE) .thenReturn(FAKE_COINBASE) .thenReturn(NOT_MY_COINBASE); Mockito.when(block.getCumulativeDifficulty()).thenReturn(TEST_DIFFICULTY); HashRateCalculator hashRateCalculator = new HashRateCalculatorMining(blockStore, new RskCustomCache<>(1000L), FAKE_COINBASE); BigInteger hashRate = hashRateCalculator.calculateNetHashRate(Duration.ofHours(1)); Assert.assertEquals(hashRate, new BigInteger("+4")); } @Test public void calculateNetHashRateOldBlock() { long ts = System.currentTimeMillis() / 1000L; Mockito.when(blockHeader.getTimestamp()) .thenReturn(ts - 10000L); Mockito.when(blockHeader.getCoinbase()).thenReturn(FAKE_COINBASE); Mockito.when(block.getCumulativeDifficulty()).thenReturn(TEST_DIFFICULTY); HashRateCalculator hashRateCalculator = new HashRateCalculatorMining(blockStore, new RskCustomCache<>(1000L), FAKE_COINBASE); BigInteger hashRate = hashRateCalculator.calculateNetHashRate(Duration.ofHours(1)); Assert.assertEquals(hashRate, BigInteger.ZERO); }
### Question: ListArrayUtil { public static List<Byte> asByteList(byte[] primitiveByteArray) { Byte[] arrayObj = convertTo(primitiveByteArray); return Arrays.asList(arrayObj); } private ListArrayUtil(); static List<Byte> asByteList(byte[] primitiveByteArray); static boolean isEmpty(@Nullable byte[] array); static int getLength(@Nullable byte[] array); static byte[] nullToEmpty(@Nullable byte[] array); static int lastIndexOfSubList(byte[] source, byte[] target); }### Answer: @Test public void testAsByteList() { byte[] array = new byte[]{'a','b','c','d'}; List<Byte> result = ListArrayUtil.asByteList(array); for(int i = 0; i < array.length; i++) { Assert.assertEquals(array[i], result.get(i).byteValue()); } }
### Question: ListArrayUtil { public static boolean isEmpty(@Nullable byte[] array) { return array == null || array.length == 0; } private ListArrayUtil(); static List<Byte> asByteList(byte[] primitiveByteArray); static boolean isEmpty(@Nullable byte[] array); static int getLength(@Nullable byte[] array); static byte[] nullToEmpty(@Nullable byte[] array); static int lastIndexOfSubList(byte[] source, byte[] target); }### Answer: @Test public void testNullIsEmpty() { Assert.assertTrue(ListArrayUtil.isEmpty(null)); } @Test public void testEmptyIsEmpty() { Assert.assertTrue(ListArrayUtil.isEmpty(new byte[]{})); } @Test public void testNotEmptyIsEmpty() { Assert.assertFalse(ListArrayUtil.isEmpty(new byte[]{'a'})); }
### Question: ListArrayUtil { public static byte[] nullToEmpty(@Nullable byte[] array) { if (array == null) { return new byte[0]; } return array; } private ListArrayUtil(); static List<Byte> asByteList(byte[] primitiveByteArray); static boolean isEmpty(@Nullable byte[] array); static int getLength(@Nullable byte[] array); static byte[] nullToEmpty(@Nullable byte[] array); static int lastIndexOfSubList(byte[] source, byte[] target); }### Answer: @Test public void testNullToEmpty() { Assert.assertNotNull(ListArrayUtil.nullToEmpty(null)); } @Test public void testNonNullToEmpty() { byte[] array = new byte[1]; Assert.assertSame(array, ListArrayUtil.nullToEmpty(array)); }
### Question: ListArrayUtil { public static int getLength(@Nullable byte[] array) { if (array == null) { return 0; } return array.length; } private ListArrayUtil(); static List<Byte> asByteList(byte[] primitiveByteArray); static boolean isEmpty(@Nullable byte[] array); static int getLength(@Nullable byte[] array); static byte[] nullToEmpty(@Nullable byte[] array); static int lastIndexOfSubList(byte[] source, byte[] target); }### Answer: @Test public void testNullGetLength() { Assert.assertEquals(0, ListArrayUtil.getLength(null)); } @Test public void testNonNullGetLength() { byte[] array = new byte[1]; Assert.assertEquals(1, ListArrayUtil.getLength(array)); }
### Question: Topic { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } Topic otherTopic = (Topic) other; return Arrays.equals(bytes, otherTopic.bytes); } Topic(String topic); Topic(byte[] bytes); byte[] getBytes(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); }### Answer: @Test public void testEquals() { Topic topicA = new Topic("0000000000000000000000000000000000000000000000000000000000000001"); Topic topicB = new Topic("0000000000000000000000000000000000000000000000000000000000000001"); Topic topicC = new Topic("0000000000000000000000000000000000000000000000000000000000000002"); Topic topicD = new Topic("0x0000000000000000000000000000000000000000000000000000000000000003"); Assert.assertEquals(topicA, topicB); Assert.assertNotEquals(topicA, topicC); Assert.assertNotEquals(topicA, topicD); }
### Question: 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); }### Answer: @Test public void parseIPv6() { InetSocketAddress result = IpUtils.parseAddress(IPV6_WITH_PORT); Assert.assertNotNull(result); } @Test public void parseIPv6NoPort() { InetSocketAddress result = IpUtils.parseAddress(IPV6_NO_PORT); Assert.assertNull(result); } @Test public void parseIPv6InvalidFormat() { InetSocketAddress result = IpUtils.parseAddress(IPV6_INVALID); Assert.assertNull(result); } @Test public void parseIPv4() { InetSocketAddress result = IpUtils.parseAddress(IPV4_WITH_PORT); Assert.assertNotNull(result); } @Test public void parseIPv4NoPort() { InetSocketAddress result = IpUtils.parseAddress(IPV4_NO_PORT); Assert.assertNull(result); } @Test public void parseHostnameWithPort() { InetSocketAddress result = IpUtils.parseAddress(HOSTNAME_WITH_PORT); Assert.assertNotNull(result); }
### Question: PendingTransactionFilter extends Filter { @Override public void newPendingTx(Transaction tx) { add(new PendingTransactionFilterEvent(tx)); } @Override void newPendingTx(Transaction tx); }### Answer: @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]); } @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]); }
### Question: 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); }### Answer: @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()); }
### Question: FormatUtils { public static String formatNanosecondsToSeconds(long nanoseconds) { return String.format("%.6f", nanoseconds / 1_000_000_000.0); } private FormatUtils(); static String formatNanosecondsToSeconds(long nanoseconds); }### Answer: @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)); }
### Question: 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(); }### Answer: @Test public void callingRunStartsInternalServices() { runner.run(); for (InternalService internalService : internalServices) { verify(internalService).start(); } }
### Question: 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(); }### Answer: @Test public void callingStopStopsInternalServices() { runner.stop(); for (InternalService internalService : internalServices) { verify(internalService).stop(); } }