method2testcases
stringlengths 118
3.08k
|
---|
### Question:
Uint8 { public byte asByte() { return (byte) intValue; } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }### Answer:
@Test public void asByteReturnsByteValue() { Uint8 fortyTwo = new Uint8(42); assertThat(fortyTwo.asByte(), is((byte)42)); } |
### Question:
Uint8 { public int intValue() { return intValue; } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }### Answer:
@Test(expected = IllegalArgumentException.class) public void instantiateMaxPlusOne() { new Uint8((Uint8.MAX_VALUE.intValue() + 1)); } |
### Question:
Uint8 { public static Uint8 decode(byte[] bytes, int offset) { int intValue = bytes[offset] & 0xFF; return new Uint8(intValue); } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }### Answer:
@Test public void decodeOffsettedValue() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf3, (byte) 0xf4, 0x04, 0x55}; Uint8 decoded = Uint8.decode(bytes, 2); assertThat(decoded, is(new Uint8(243))); }
@Test(expected = ArrayIndexOutOfBoundsException.class) public void decodeSmallArray() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2}; Uint8.decode(bytes, 3); } |
### Question:
RskAddress { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } RskAddress otherSender = (RskAddress) other; return Arrays.equals(bytes, otherSender.bytes); } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); static RskAddress nullAddress(); byte[] getBytes(); String toHexString(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); static final int LENGTH_IN_BYTES; static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR; }### Answer:
@Test public void testEquals() { RskAddress senderA = new RskAddress("0000000000000000000000000000000001000006"); RskAddress senderB = new RskAddress("0000000000000000000000000000000001000006"); RskAddress senderC = new RskAddress("0000000000000000000000000000000001000008"); RskAddress senderD = RskAddress.nullAddress(); RskAddress senderE = new RskAddress("0x00002000f000000a000000330000000001000006"); Assert.assertEquals(senderA, senderB); Assert.assertNotEquals(senderA, senderC); Assert.assertNotEquals(senderA, senderD); Assert.assertNotEquals(senderA, senderE); } |
### Question:
RskAddress { public static RskAddress nullAddress() { return NULL_ADDRESS; } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); static RskAddress nullAddress(); byte[] getBytes(); String toHexString(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); static final int LENGTH_IN_BYTES; static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR; }### Answer:
@Test public void zeroAddress() { RskAddress senderA = new RskAddress("0000000000000000000000000000000000000000"); RskAddress senderB = new RskAddress("0x0000000000000000000000000000000000000000"); RskAddress senderC = new RskAddress(new byte[20]); Assert.assertEquals(senderA, senderB); Assert.assertEquals(senderB, senderC); Assert.assertNotEquals(RskAddress.nullAddress(), senderC); }
@Test public void nullAddress() { Assert.assertArrayEquals(RskAddress.nullAddress().getBytes(), new byte[0]); } |
### Question:
RskAddress { public String toJsonString() { if (NULL_ADDRESS.equals(this)) { return null; } return TypeConverter.toUnformattedJsonHex(this.getBytes()); } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); static RskAddress nullAddress(); byte[] getBytes(); String toHexString(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); static final int LENGTH_IN_BYTES; static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR; }### Answer:
@Test public void jsonString_otherAddress() { String address = "0x0000000000000000000000000000000000000001"; RskAddress rskAddress = new RskAddress(address); Assert.assertEquals(address, rskAddress.toJsonString()); } |
### Question:
Coin implements Comparable<Coin> { public byte[] getBytes() { return value.toByteArray(); } Coin(byte[] value); Coin(BigInteger value); byte[] getBytes(); BigInteger asBigInteger(); Coin negate(); Coin add(Coin val); Coin subtract(Coin val); Coin multiply(BigInteger val); Coin divide(BigInteger val); Coin[] divideAndRemainder(BigInteger val); co.rsk.bitcoinj.core.Coin toBitcoin(); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(@Nonnull Coin other); @Override String toString(); static Coin valueOf(long val); static Coin fromBitcoin(co.rsk.bitcoinj.core.Coin val); static final Coin ZERO; }### Answer:
@Test public void zeroGetBytes() { assertThat(Coin.ZERO.getBytes(), is(new byte[]{0})); } |
### Question:
TrieKeySlice { public TrieKeySlice leftPad(int paddingLength) { if (paddingLength == 0) { return this; } int currentLength = length(); byte[] paddedExpandedKey = new byte[currentLength + paddingLength]; System.arraycopy(expandedKey, offset, paddedExpandedKey, paddingLength, currentLength); return new TrieKeySlice(paddedExpandedKey, 0, paddedExpandedKey.length); } private TrieKeySlice(byte[] expandedKey, int offset, int limit); int length(); byte get(int i); byte[] encode(); TrieKeySlice slice(int from, int to); TrieKeySlice commonPath(TrieKeySlice other); TrieKeySlice rebuildSharedPath(byte implicitByte, TrieKeySlice childSharedPath); TrieKeySlice leftPad(int paddingLength); static TrieKeySlice fromKey(byte[] key); static TrieKeySlice fromEncoded(byte[] src, int offset, int keyLength, int encodedLength); static TrieKeySlice empty(); }### Answer:
@Test public void leftPad() { int paddedLength = 8; TrieKeySlice initialKey = TrieKeySlice.fromKey(new byte[]{(byte) 0xff}); TrieKeySlice leftPaddedKey = initialKey.leftPad(paddedLength); Assert.assertThat(leftPaddedKey.length(), is(initialKey.length() + paddedLength)); Assert.assertArrayEquals( PathEncoder.encode(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }), leftPaddedKey.encode() ); } |
### Question:
TrieStoreImpl implements TrieStore { @Override public Optional<Trie> retrieve(byte[] hash) { byte[] message = this.store.get(hash); if (message == null) { return Optional.empty(); } Trie trie = Trie.fromMessage(message, this); savedTries.add(trie); return Optional.of(trie); } TrieStoreImpl(KeyValueDataSource store); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] hash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); }### Answer:
@Test public void retrieveTrieNotFound() { Assert.assertFalse(store.retrieve(new byte[] { 0x01, 0x02, 0x03, 0x04 }).isPresent()); } |
### Question:
PathEncoder { @Nonnull public static byte[] encode(byte[] path) { if (path == null) { throw new IllegalArgumentException("path"); } return encodeBinaryPath(path); } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }### Answer:
@Test public void encodeNullBinaryPath() { try { PathEncoder.encode(null); Assert.fail(); } catch (Exception ex) { Assert.assertTrue(ex instanceof IllegalArgumentException); } }
@Test public void encodeBinaryPathOneByte() { byte[] path = new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x6d }, encoded); }
@Test public void encodeBinaryPathNineBits() { byte[] path = new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x6d, (byte)0x80 }, encoded); }
@Test public void encodeBinaryPathOneAndHalfByte() { byte[] path = new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x6d, 0x50 }, encoded); } |
### Question:
PathEncoder { @Nonnull private static byte[] encodeBinaryPath(byte[] path) { int lpath = path.length; int lencoded = calculateEncodedLength(lpath); byte[] encoded = new byte[lencoded]; int nbyte = 0; for (int k = 0; k < lpath; k++) { int offset = k % 8; if (k > 0 && offset == 0) { nbyte++; } if (path[k] == 0) { continue; } encoded[nbyte] |= 0x80 >> offset; } return encoded; } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }### Answer:
@Test public void encodeBinaryPath() { byte[] path = new byte[] { 0x00, 0x01, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x60 }, encoded); } |
### Question:
PathEncoder { @Nonnull private static byte[] decodeBinaryPath(byte[] encoded, int bitlength) { byte[] path = new byte[bitlength]; for (int k = 0; k < bitlength; k++) { int nbyte = k / 8; int offset = k % 8; if (((encoded[nbyte] >> (7 - offset)) & 0x01) != 0) { path[k] = 1; } } return path; } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }### Answer:
@Test public void decodeBinaryPath() { byte[] encoded = new byte[] { 0x60 }; byte[] path = PathEncoder.decode(encoded, 3); Assert.assertNotNull(path); Assert.assertArrayEquals(new byte[] { 0x00, 0x01, 0x01 }, path); } |
### Question:
MultiTrieStore implements TrieStore { @Override public void save(Trie trie) { getCurrentStore().save(trie); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }### Answer:
@Test public void callsSaveOnlyOnNewestStore() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); Trie trie = mock(Trie.class); store.save(trie); verify(store1, never()).save(trie); verify(store2, never()).save(trie); verify(store3).save(trie); } |
### Question:
MultiTrieStore implements TrieStore { @Override public void flush() { epochs.forEach(TrieStore::flush); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }### Answer:
@Test public void callsFlushOnAllStores() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); store.flush(); verify(store1).flush(); verify(store2).flush(); verify(store3).flush(); } |
### Question:
MultiTrieStore implements TrieStore { @Override public void dispose() { epochs.forEach(TrieStore::dispose); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }### Answer:
@Test public void callsDisposeOnAllStores() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); store.dispose(); verify(store1).dispose(); verify(store2).dispose(); verify(store3).dispose(); } |
### Question:
MultiTrieStore implements TrieStore { @Override public byte[] retrieveValue(byte[] hash) { for (TrieStore epochTrieStore : epochs) { byte[] value = epochTrieStore.retrieveValue(hash); if (value != null) { return value; } } return null; } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }### Answer:
@Test public void retrievesValueFromNewestStoreWithValue() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); byte[] testValue = new byte[] {0x32, 0x42}; byte[] hashToRetrieve = new byte[] {0x2, 0x4}; when(store2.retrieveValue(hashToRetrieve)).thenReturn(testValue); byte[] retrievedValue = store.retrieveValue(hashToRetrieve); assertArrayEquals(testValue, retrievedValue); verify(store1, never()).retrieveValue(hashToRetrieve); verify(store2).retrieveValue(hashToRetrieve); verify(store3).retrieveValue(hashToRetrieve); } |
### Question:
BitSet { public boolean get(int position) { if (position < 0 || position >= this.size) { throw new IndexOutOfBoundsException(String.format("Index: %s, Size: %s", position, this.size)); } int offset = position / 8; int bitoffset = position % 8; return (this.bytes[offset] & 0xff & (1 << bitoffset)) != 0; } BitSet(int size); void set(int position); boolean get(int position); int size(); }### Answer:
@Test public void exceptionIfGetWithNegativePosition() { BitSet set = new BitSet(17); try { set.get(-1); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: -1, Size: 17", ex.getMessage()); } }
@Test public void exceptionIfGetWithOutOfBoundPosition() { BitSet set = new BitSet(17); try { set.get(17); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: 17, Size: 17", ex.getMessage()); } } |
### Question:
BitSet { public void set(int position) { if (position < 0 || position >= this.size) { throw new IndexOutOfBoundsException(String.format("Index: %s, Size: %s", position, this.size)); } int offset = position / 8; int bitoffset = position % 8; this.bytes[offset] |= 1 << bitoffset; } BitSet(int size); void set(int position); boolean get(int position); int size(); }### Answer:
@Test public void exceptionIfSetWithNegativePosition() { BitSet set = new BitSet(17); try { set.set(-1); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: -1, Size: 17", ex.getMessage()); } }
@Test public void exceptionIfSetWithOutOfBoundPosition() { BitSet set = new BitSet(17); try { set.set(17); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: 17, Size: 17", ex.getMessage()); } } |
### Question:
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("extractPublicKeyFromExtendedPublicKey", fn.name); Assert.assertEquals(1, fn.inputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("bytes").getName(), fn.outputs[0].type.getName()); } |
### Question:
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public boolean isEnabled() { return true; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); } |
### Question:
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); } |
### Question:
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 11_300L; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void gasIsCorrect() { Assert.assertEquals(11_300, method.getGas(new Object[]{ "xpub661MyMwAqRbcFMGNG2YcHvj3x63bAZN9U5cKikaiQ4zu2D1cvpnZYyXNR9nH62sGp4RR39Ui7SVQSq1PY4JbPuEuu5prVJJC3d5Pogft712" }, new byte[]{})); } |
### Question:
GetMultisigScriptHash extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }### Answer:
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("getMultisigScriptHash", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("int256").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getType("bytes[]").getName(), fn.inputs[1].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("bytes").getName(), fn.outputs[0].type.getName()); } |
### Question:
GetMultisigScriptHash extends NativeMethod { @Override public boolean isEnabled() { return true; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }### Answer:
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); } |
### Question:
GetMultisigScriptHash extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }### Answer:
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); } |
### Question:
GetMultisigScriptHash extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { Object[] keys = ((Object[]) parsedArguments[1]); if (keys == null || keys.length < 2) { return BASE_COST; } return BASE_COST + (keys.length - 2) * COST_PER_EXTRA_KEY; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }### Answer:
@Test public void gasIsBaseIfLessThanOrEqualstoTwoKeysPassed() { Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), null }, new byte[]{})); Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), new Object[]{ } }, new byte[]{})); Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), new Object[]{ Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7") } }, new byte[]{})); Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), new Object[]{ Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7"), Hex.decode("aabbcc") } }, new byte[]{})); } |
### Question:
DeriveExtendedPublicKey extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("deriveExtendedPublicKey", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[1].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.outputs[0].type.getName()); } |
### Question:
DeriveExtendedPublicKey extends NativeMethod { @Override public boolean isEnabled() { return true; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); } |
### Question:
DeriveExtendedPublicKey extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); } |
### Question:
DeriveExtendedPublicKey extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 107_000L; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void gasIsCorrect() { Assert.assertEquals(107_000, method.getGas(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "2/3/4" }, new byte[]{})); } |
### Question:
HDWalletUtilsHelper { public NetworkParameters validateAndExtractNetworkFromExtendedPublicKey(String xpub) { if (xpub == null) { throw new NativeContractIllegalArgumentException(String.format("Invalid extended public key '%s'", xpub)); } if (xpub.startsWith("xpub")) { return NetworkParameters.fromID(NetworkParameters.ID_MAINNET); } else if (xpub.startsWith("tpub")) { return NetworkParameters.fromID(NetworkParameters.ID_TESTNET); } else { throw new NativeContractIllegalArgumentException(String.format("Invalid extended public key '%s'", xpub)); } } NetworkParameters validateAndExtractNetworkFromExtendedPublicKey(String xpub); }### Answer:
@Test public void validateAndExtractNetworkFromExtendedPublicKeyMainnet() { Assert.assertEquals( NetworkParameters.fromID(NetworkParameters.ID_MAINNET), helper.validateAndExtractNetworkFromExtendedPublicKey("xpubSomethingSomething") ); }
@Test public void validateAndExtractNetworkFromExtendedPublicKeyTestnet() { Assert.assertEquals( NetworkParameters.fromID(NetworkParameters.ID_TESTNET), helper.validateAndExtractNetworkFromExtendedPublicKey("tpubSomethingSomething") ); }
@Test(expected = NativeContractIllegalArgumentException.class) public void validateAndExtractNetworkFromExtendedPublicKeyInvalid() { helper.validateAndExtractNetworkFromExtendedPublicKey("completelyInvalidStuff"); } |
### Question:
ToBase58Check extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("toBase58Check", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("bytes").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getType("int256").getName(), fn.inputs[1].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.outputs[0].type.getName()); } |
### Question:
ToBase58Check extends NativeMethod { @Override public boolean isEnabled() { return true; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); } |
### Question:
ToBase58Check extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); } |
### Question:
ToBase58Check extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 13_000L; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }### Answer:
@Test public void gasIsCorrect() { Assert.assertEquals(13_000, method.getGas(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(111L) }, new byte[]{})); } |
### Question:
HDWalletUtils extends NativeContract { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.empty(); } HDWalletUtils(ActivationConfig config, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }### Answer:
@Test public void hasNoDefaultMethod() { Assert.assertFalse(contract.getDefaultMethod().isPresent()); } |
### Question:
HDWalletUtils extends NativeContract { @Override public List<NativeMethod> getMethods() { return Arrays.asList( new ToBase58Check(getExecutionEnvironment()), new DeriveExtendedPublicKey(getExecutionEnvironment(), helper), new ExtractPublicKeyFromExtendedPublicKey(getExecutionEnvironment(), helper), new GetMultisigScriptHash(getExecutionEnvironment()) ); } HDWalletUtils(ActivationConfig config, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }### Answer:
@Test public void hasFourMethods() { Assert.assertEquals(4, contract.getMethods().size()); } |
### Question:
BlockHeaderContract extends NativeContract { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.empty(); } BlockHeaderContract(ActivationConfig activationConfig, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }### Answer:
@Test public void hasNoDefaultMethod() { Assert.assertFalse(contract.getDefaultMethod().isPresent()); } |
### Question:
BlockHeaderContract extends NativeContract { @Override public List<NativeMethod> getMethods() { return Arrays.asList( new GetCoinbaseAddress(getExecutionEnvironment(), this.blockAccessor), new GetBlockHash(getExecutionEnvironment(), this.blockAccessor), new GetMergedMiningTags(getExecutionEnvironment(), this.blockAccessor), new GetMinimumGasPrice(getExecutionEnvironment(), this.blockAccessor), new GetGasLimit(getExecutionEnvironment(), this.blockAccessor), new GetGasUsed(getExecutionEnvironment(), this.blockAccessor), new GetDifficulty(getExecutionEnvironment(), this.blockAccessor), new GetBitcoinHeader(getExecutionEnvironment(), this.blockAccessor), new GetUncleCoinbaseAddress(getExecutionEnvironment(), this.blockAccessor) ); } BlockHeaderContract(ActivationConfig activationConfig, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }### Answer:
@Test public void hasNineMethods() { Assert.assertEquals(9, contract.getMethods().size()); } |
### Question:
NativeMethod { public ExecutionEnvironment getExecutionEnvironment() { return executionEnvironment; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }### Answer:
@Test public void executionEnvironmentGetter() { Assert.assertEquals(executionEnvironment, method.getExecutionEnvironment()); } |
### Question:
NativeMethod { public long getGas(Object[] parsedArguments, byte[] originalData) { return originalData == null ? 0 : originalData.length * 2; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }### Answer:
@Test public void getGasWithNullData() { Assert.assertEquals(0L, method.getGas(null, null)); }
@Test public void getGasWithNonNullData() { Assert.assertEquals(6L, method.getGas(null, Hex.decode("aabbcc"))); Assert.assertEquals(10L, method.getGas(null, Hex.decode("aabbccddee"))); }
@Test public void withArgumentsGetsGas() { Assert.assertEquals(6L, withArguments.getGas()); } |
### Question:
NativeMethod { public String getName() { return getFunction().name; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }### Answer:
@Test public void getName() { function.name = "a-method-name"; Assert.assertEquals("a-method-name", method.getName()); } |
### Question:
NativeMethod { public abstract Object execute(Object[] arguments); NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }### Answer:
@Test public void withArgumentsExecutesMethod() { Assert.assertEquals("execution-result", withArguments.execute()); } |
### Question:
NativeContract extends PrecompiledContracts.PrecompiledContract { public ExecutionEnvironment getExecutionEnvironment() { return executionEnvironment; } NativeContract(ActivationConfig activationConfig, RskAddress contractAddress); ExecutionEnvironment getExecutionEnvironment(); abstract List<NativeMethod> getMethods(); abstract Optional<NativeMethod> getDefaultMethod(); void before(); void after(); @Override void init(Transaction tx, Block executionBlock, Repository repository, BlockStore blockStore, ReceiptStore receiptStore, List<LogInfo> logs); @Override long getGasForData(byte[] data); @Override byte[] execute(byte[] data); }### Answer:
@Test public void createsExecutionEnvironmentUponInit() { Assert.assertNull(contract.getExecutionEnvironment()); doInit(); ExecutionEnvironment executionEnvironment = contract.getExecutionEnvironment(); Assert.assertNotNull(executionEnvironment); Assert.assertEquals(tx, executionEnvironment.getTransaction()); Assert.assertEquals(block, executionEnvironment.getBlock()); Assert.assertEquals(repository, executionEnvironment.getRepository()); Assert.assertEquals(blockStore, executionEnvironment.getBlockStore()); Assert.assertEquals(receiptStore, executionEnvironment.getReceiptStore()); Assert.assertEquals(logs, executionEnvironment.getLogs()); } |
### Question:
Migrator { public String migrateConfiguration() throws IOException { return migrateConfiguration( Files.newBufferedReader(configuration.getSourceConfiguration(), StandardCharsets.UTF_8), configuration.getMigrationConfiguration() ); } Migrator(MigratorConfiguration configuration); String migrateConfiguration(); static String migrateConfiguration(Reader sourceReader, Properties migrationConfiguration); }### Answer:
@Test public void migrateConfiguration() { Reader initialConfiguration = new StringReader("inline.config.name=\"value\"\n" + "nested {\n" + " nested = {\n" + " #test comment\n" + " config = 13\n" + " }\n" + "}\n" + "flat.config = \"0.0.0.0\"\n" + "another.config=\"don't change\""); Properties migrationProperties = new Properties(); migrationProperties.put("inline.config.name", "inline.config.new.name"); migrationProperties.put("flat.config", "flat_config"); migrationProperties.put("nested.nested.config", "nested.nested.new.config"); migrationProperties.put("unknown.config", "none"); migrationProperties.put("[new]new.key", "new value"); migrationProperties.put("[new] other.new.key", "12"); String migratedConfiguration = Migrator.migrateConfiguration(initialConfiguration, migrationProperties); Config config = ConfigFactory.parseString(migratedConfiguration); assertThat(config.hasPath("inline.config.name"), is(false)); assertThat(config.getString("inline.config.new.name"), is("value")); assertThat(config.hasPath("flat.config"), is(false)); assertThat(config.hasPath("flat_config"), is(true)); assertThat(config.getString("flat_config"), is("0.0.0.0")); assertThat(config.hasPath("nested.nested.config"), is(false)); assertThat(config.getInt("nested.nested.new.config"), is(13)); assertThat(config.hasPath("unknown.config"), is(false)); assertThat(config.getString("another.config"), is("don't change")); assertThat(config.getString("new.key"), is("new value")); assertThat(config.getInt("other.new.key"), is(12)); } |
### Question:
PeerScoringManager { public boolean hasGoodReputation(NodeID id) { synchronized (accessLock) { return this.getPeerScoring(id).hasGoodReputation(); } } PeerScoringManager(
PeerScoring.Factory peerScoringFactory,
int nodePeersSize,
PunishmentParameters nodeParameters,
PunishmentParameters ipParameters); void recordEvent(NodeID id, InetAddress address, EventType event); boolean hasGoodReputation(NodeID id); boolean hasGoodReputation(InetAddress address); void banAddress(InetAddress address); void banAddress(String address); void unbanAddress(InetAddress address); void unbanAddress(String address); void banAddressBlock(InetAddressBlock addressBlock); void unbanAddressBlock(InetAddressBlock addressBlock); List<PeerScoringInformation> getPeersInformation(); List<String> getBannedAddresses(); @VisibleForTesting boolean isEmpty(); @VisibleForTesting PeerScoring getPeerScoring(NodeID id); @VisibleForTesting PeerScoring getPeerScoring(InetAddress address); }### Answer:
@Test public void newNodeHasGoodReputation() { NodeID id = generateNodeID(); PeerScoringManager manager = createPeerScoringManager(); Assert.assertTrue(manager.hasGoodReputation(id)); }
@Test public void newAddressHasGoodReputation() throws UnknownHostException { InetAddress address = generateIPAddressV4(); PeerScoringManager manager = createPeerScoringManager(); Assert.assertTrue(manager.hasGoodReputation(address)); } |
### Question:
PeerScoring { public boolean hasGoodReputation() { try { rwlock.writeLock().lock(); if (this.goodReputation) { return true; } if (this.punishmentTime > 0 && this.timeLostGoodReputation > 0 && this.punishmentTime + this.timeLostGoodReputation <= System.currentTimeMillis()) { this.endPunishment(); } return this.goodReputation; } finally { rwlock.writeLock().unlock(); } } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); }### Answer:
@Test public void newStatusHasGoodReputation() { PeerScoring scoring = new PeerScoring(); Assert.assertTrue(scoring.hasGoodReputation()); } |
### Question:
PeerScoring { public int getScore() { try { rwlock.readLock().lock(); return score; } finally { rwlock.readLock().unlock(); } } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); }### Answer:
@Test public void getInformationFromNewScoring() { PeerScoring scoring = new PeerScoring(); PeerScoringInformation info = new PeerScoringInformation(scoring, "nodeid", "node"); Assert.assertTrue(info.getGoodReputation()); Assert.assertEquals(0, info.getValidBlocks()); Assert.assertEquals(0, info.getInvalidBlocks()); Assert.assertEquals(0, info.getValidTransactions()); Assert.assertEquals(0, info.getInvalidTransactions()); Assert.assertEquals(0, info.getScore()); Assert.assertEquals(0, info.getSuccessfulHandshakes()); Assert.assertEquals(0, info.getFailedHandshakes()); Assert.assertEquals(0, info.getRepeatedMessages()); Assert.assertEquals(0, info.getInvalidNetworks()); Assert.assertEquals("nodeid", info.getId()); Assert.assertEquals("node", info.getType()); }
@Test public void getZeroScoreWhenEmpty() { PeerScoring scoring = new PeerScoring(); Assert.assertEquals(0, scoring.getScore()); } |
### Question:
PeerScoring { @VisibleForTesting public long getTimeLostGoodReputation() { return this.timeLostGoodReputation; } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); }### Answer:
@Test public void newStatusHasNoTimeLostGoodReputation() { PeerScoring scoring = new PeerScoring(); Assert.assertEquals(0, scoring.getTimeLostGoodReputation()); } |
### Question:
PeerScoring { public void recordEvent(EventType evt) { try { rwlock.writeLock().lock(); counters[evt.ordinal()]++; switch (evt) { case INVALID_NETWORK: case INVALID_BLOCK: case INVALID_TRANSACTION: case INVALID_MESSAGE: case INVALID_HEADER: if (score > 0) { score = 0; } score--; break; case UNEXPECTED_MESSAGE: case FAILED_HANDSHAKE: case SUCCESSFUL_HANDSHAKE: case REPEATED_MESSAGE: break; default: if (score >= 0) { score++; } break; } } finally { rwlock.writeLock().unlock(); } } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); }### Answer:
@Test public void recordEvent() { PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.INVALID_BLOCK); Assert.assertEquals(1, scoring.getEventCounter(EventType.INVALID_BLOCK)); Assert.assertEquals(0, scoring.getEventCounter(EventType.INVALID_TRANSACTION)); Assert.assertEquals(1, scoring.getTotalEventCounter()); } |
### Question:
PeerScoring { @VisibleForTesting public void startPunishment(long expirationTime) { if (!punishmentEnabled) { return; } try { rwlock.writeLock().lock(); this.goodReputation = false; this.punishmentTime = expirationTime; this.punishmentCounter++; this.timeLostGoodReputation = System.currentTimeMillis(); } finally { rwlock.writeLock().unlock(); } } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); }### Answer:
@Test public void startPunishment() throws InterruptedException { PeerScoring scoring = new PeerScoring(); Assert.assertEquals(0, scoring.getPunishmentTime()); Assert.assertEquals(0, scoring.getPunishmentCounter()); scoring.startPunishment(1000); Assert.assertEquals(1, scoring.getPunishmentCounter()); Assert.assertFalse(scoring.hasGoodReputation()); Assert.assertEquals(1000, scoring.getPunishmentTime()); TimeUnit.MILLISECONDS.sleep(10); Assert.assertFalse(scoring.hasGoodReputation()); TimeUnit.MILLISECONDS.sleep(2000); Assert.assertTrue(scoring.hasGoodReputation()); Assert.assertEquals(1, scoring.getPunishmentCounter()); } |
### Question:
InetAddressBlock { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof InetAddressBlock)) { return false; } InetAddressBlock block = (InetAddressBlock)obj; return block.mask == this.mask && Arrays.equals(block.bytes, this.bytes); } InetAddressBlock(InetAddress address, int bits); boolean contains(InetAddress address); String getDescription(); @Override int hashCode(); @Override boolean equals(Object obj); @VisibleForTesting byte[] getBytes(); @VisibleForTesting byte getMask(); }### Answer:
@Test public void equals() throws UnknownHostException { InetAddress address1 = generateIPAddressV4(); InetAddress address2 = alterByte(address1, 0); InetAddress address3 = generateIPAddressV6(); InetAddressBlock block1 = new InetAddressBlock(address1, 8); InetAddressBlock block2 = new InetAddressBlock(address2, 9); InetAddressBlock block3 = new InetAddressBlock(address1, 1); InetAddressBlock block4 = new InetAddressBlock(address1, 8); InetAddressBlock block5 = new InetAddressBlock(address3, 8); Assert.assertTrue(block1.equals(block1)); Assert.assertTrue(block2.equals(block2)); Assert.assertTrue(block3.equals(block3)); Assert.assertTrue(block4.equals(block4)); Assert.assertTrue(block5.equals(block5)); Assert.assertTrue(block1.equals(block4)); Assert.assertTrue(block4.equals(block1)); Assert.assertFalse(block1.equals(block2)); Assert.assertFalse(block1.equals(block3)); Assert.assertFalse(block1.equals(block5)); Assert.assertFalse(block1.equals(null)); Assert.assertFalse(block1.equals("block")); Assert.assertEquals(block1.hashCode(), block4.hashCode()); } |
### Question:
InetAddressTable { public boolean contains(InetAddress address) { if (this.addresses.contains(address)) { return true; } if (this.blocks.isEmpty()) { return false; } InetAddressBlock[] bs = this.blocks.toArray(new InetAddressBlock[0]); for (InetAddressBlock mask : bs) { if (mask.contains(address)) { return true; } } return false; } void addAddress(InetAddress address); void removeAddress(InetAddress address); void addAddressBlock(InetAddressBlock addressBlock); void removeAddressBlock(InetAddressBlock addressBlock); boolean contains(InetAddress address); List<InetAddress> getAddressList(); List<InetAddressBlock> getAddressBlockList(); }### Answer:
@Test public void doesNotContainsNewIPV4Address() throws UnknownHostException { InetAddressTable table = new InetAddressTable(); Assert.assertFalse(table.contains(generateIPAddressV4())); }
@Test public void doesNotContainsNewIPV6Address() throws UnknownHostException { InetAddressTable table = new InetAddressTable(); Assert.assertFalse(table.contains(generateIPAddressV6())); } |
### Question:
InetAddressUtils { public static boolean hasMask(String text) { if (text == null) { return false; } String[] parts = text.split("/"); return parts.length == 2 && parts[0].length() != 0 && parts[1].length() != 0; } private InetAddressUtils(); static boolean hasMask(String text); static InetAddress getAddressForBan(@CheckForNull String hostname); static InetAddressBlock parse(String text); }### Answer:
@Test public void hasMask() { Assert.assertFalse(InetAddressUtils.hasMask(null)); Assert.assertFalse(InetAddressUtils.hasMask("/")); Assert.assertFalse(InetAddressUtils.hasMask("1234/")); Assert.assertFalse(InetAddressUtils.hasMask("/1234")); Assert.assertFalse(InetAddressUtils.hasMask("1234/1234/1234")); Assert.assertFalse(InetAddressUtils.hasMask("1234 Assert.assertTrue(InetAddressUtils.hasMask("1234/1234")); } |
### Question:
ScoringCalculator { public boolean hasGoodReputation(PeerScoring scoring) { return scoring.getEventCounter(EventType.INVALID_BLOCK) < 1 && scoring.getEventCounter(EventType.INVALID_MESSAGE) < 1 && scoring.getEventCounter(EventType.INVALID_HEADER) < 1; } boolean hasGoodReputation(PeerScoring scoring); }### Answer:
@Test public void emptyScoringHasGoodReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); Assert.assertTrue(calculator.hasGoodReputation(scoring)); }
@Test public void scoringWithOneValidBlockHasGoodReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.VALID_BLOCK); Assert.assertTrue(calculator.hasGoodReputation(scoring)); }
@Test public void scoringWithOneValidTransactionHasGoodReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.VALID_TRANSACTION); Assert.assertTrue(calculator.hasGoodReputation(scoring)); }
@Test public void scoringWithOneInvalidBlockHasBadReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.INVALID_BLOCK); Assert.assertFalse(calculator.hasGoodReputation(scoring)); }
@Test public void scoringWithOneInvalidTransactionHasNoBadReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); scoring.recordEvent(EventType.INVALID_TRANSACTION); Assert.assertTrue(calculator.hasGoodReputation(scoring)); } |
### 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:
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:
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 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:
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:
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 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:
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:
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:
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 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:
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:
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:
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:
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)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.