src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
NativeContract extends PrecompiledContracts.PrecompiledContract { public ExecutionEnvironment getExecutionEnvironment() { return executionEnvironment; } NativeContract(ActivationConfig activationConfig, RskAddress contractAddress); ExecutionEnvironment getExecutionEnvironment(); abstract List<NativeMethod> getMethods(); 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); } | @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()); } |
NativeContract extends PrecompiledContracts.PrecompiledContract { @Override public long getGasForData(byte[] data) { if (executionEnvironment == null) { throw new RuntimeException("Execution environment is null"); } Optional<NativeMethod.WithArguments> methodWithArguments = parseData(data); if (!methodWithArguments.isPresent()) { return 0L; } return methodWithArguments.get().getGas(); } 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); } | @Test public void getGasForDataFailsWhenNoInit() { assertFails(() -> contract.getGasForData(Hex.decode("aabb"))); }
@Test public void getGasForDataZeroWhenNullData() { doInit(); Assert.assertEquals(0L, contract.getGasForData(null)); }
@Test public void getGasForDataZeroWhenEmptyData() { doInit(); Assert.assertEquals(0L, contract.getGasForData(null)); }
@Test public void getGasForNullDataAndDefaultMethod() { NativeMethod method = mock(NativeMethod.class); when(method.getGas(any(), any())).thenReturn(10L); contract = new EmptyNativeContract(activationConfig) { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.of(method); } }; doInit(); Assert.assertEquals(10L, contract.getGasForData(null)); }
@Test public void getGasForEmptyDataAndDefaultMethod() { NativeMethod method = mock(NativeMethod.class); when(method.getGas(any(), any())).thenReturn(10L); contract = new EmptyNativeContract(activationConfig) { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.of(method); } }; doInit(); Assert.assertEquals(10L, contract.getGasForData(new byte[]{})); }
@Test public void getGasForDataZeroWhenInvalidSignature() { doInit(); Assert.assertEquals(0L, contract.getGasForData(Hex.decode("aabb"))); }
@Test public void getGasForDataZeroWhenNoMappedMethod() { doInit(); Assert.assertEquals(0L, contract.getGasForData(Hex.decode("aabbccdd"))); } |
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); } | @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)); } |
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); } | @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)); } |
ByteUtil { @Nonnull public static String toHexStringOrEmpty(@Nullable byte[] data) { return data == null ? "" : toHexString(data); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void testToHexStringOrEmpty_EmptyStringForNull() { assertEquals("", ByteUtil.toHexStringOrEmpty(null)); } |
PunishmentCalculator { public long calculate(int punishmentCounter, int score) { long result = this.parameters.getDuration(); long rate = 100L + this.parameters.getIncrementRate(); int counter = punishmentCounter; long maxDuration = this.parameters.getMaximumDuration(); while (counter-- > 0) { result = multiplyExact(result, rate) / 100; if (maxDuration > 0 && result > maxDuration) { return maxDuration; } } if (score < 0) { result *= -score; } return maxDuration > 0 ? Math.min(maxDuration, result) : result; } PunishmentCalculator(PunishmentParameters parameters); long calculate(int punishmentCounter, int score); } | @Test public void calculatePunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(100, calculator.calculate(0, 0)); }
@Test public void calculatePunishmentTimeWithNegativeScore() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(200, calculator.calculate(0, -2)); }
@Test public void calculateSecondPunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(110, calculator.calculate(1, 0)); }
@Test public void calculateThirdPunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(121, calculator.calculate(2, 0)); }
@Test public void calculateThirdPunishmentTimeAndNegativeScore() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 1000)); Assert.assertEquals(242, calculator.calculate(2, -2)); }
@Test public void calculateUsingMaxPunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 120)); Assert.assertEquals(120, calculator.calculate(2, 0)); }
@Test public void calculateUsingNoMaxPunishmentTime() { PunishmentCalculator calculator = new PunishmentCalculator(new PunishmentParameters(100, 10, 0)); Assert.assertEquals(121, calculator.calculate(2, 0)); } |
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(); } | @Test public void newStatusHasGoodReputation() { PeerScoring scoring = new PeerScoring(); Assert.assertTrue(scoring.hasGoodReputation()); } |
PeerScoring { public int getScore() { try { rwlock.readLock().lock(); return score; } finally { rwlock.readLock().unlock(); } } PeerScoring(); PeerScoring(boolean punishmentEnabled); void recordEvent(EventType evt); int getScore(); int getEventCounter(EventType evt); int getTotalEventCounter(); boolean isEmpty(); boolean hasGoodReputation(); @VisibleForTesting void startPunishment(long expirationTime); @VisibleForTesting long getPunishmentTime(); int getPunishmentCounter(); @VisibleForTesting long getTimeLostGoodReputation(); } | @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()); } |
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(); } | @Test public void newStatusHasNoTimeLostGoodReputation() { PeerScoring scoring = new PeerScoring(); Assert.assertEquals(0, scoring.getTimeLostGoodReputation()); } |
ByteUtil { public static byte[] calcPacketLength(byte[] msg) { int msgLen = msg.length; return new byte[]{ (byte) ((msgLen >> 24) & 0xFF), (byte) ((msgLen >> 16) & 0xFF), (byte) ((msgLen >> 8) & 0xFF), (byte) ((msgLen) & 0xFF)}; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void testCalcPacketLength() { byte[] test = new byte[]{0x0f, 0x10, 0x43}; byte[] expected = new byte[]{0x00, 0x00, 0x00, 0x03}; assertArrayEquals(expected, ByteUtil.calcPacketLength(test)); } |
Web3Impl implements Web3 { @Override public String web3_sha3(String data) throws Exception { String s = null; try { byte[] result = HashUtil.keccak256(data.getBytes(StandardCharsets.UTF_8)); return s = TypeConverter.toJsonHex(result); } finally { if (logger.isDebugEnabled()) { logger.debug("web3_sha3({}): {}", data, s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void web3_sha3() throws Exception { String toHash = "RSK"; Web3 web3 = createWeb3(); String result = web3.web3_sha3(toHash); assertTrue("hash does not match", result.compareTo("0x80553b6b348ae45ab8e8bf75e77064818c0a772f13cf8d3a175d3815aec59b56") == 0); } |
PeerScoring { public void recordEvent(EventType evt) { try { rwlock.writeLock().lock(); counters[evt.ordinal()]++; switch (evt) { case INVALID_NETWORK: case INVALID_BLOCK: case INVALID_TRANSACTION: case INVALID_MESSAGE: case INVALID_HEADER: if (score > 0) { score = 0; } score--; break; case UNEXPECTED_MESSAGE: case 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(); } | @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()); } |
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(); } | @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()); } |
InetAddressBlock { public boolean contains(InetAddress address) { byte[] addressBytes = address.getAddress(); if (addressBytes.length != this.bytes.length) { return false; } int k; for (k = 0; k < this.nbytes; k++) { if (addressBytes[k] != this.bytes[k]) { return false; } } if (this.mask != (byte)0xff) { return (addressBytes[k] & this.mask) == (this.bytes[k] & this.mask); } return true; } 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(); } | @Test public void recognizeIPV4AddressMask8Bits() throws UnknownHostException { InetAddress address = generateIPAddressV4(); InetAddressBlock mask = new InetAddressBlock(address, 8); Assert.assertTrue(mask.contains(address)); }
@Test public void containsIPV4() throws UnknownHostException { InetAddress address = generateIPAddressV4(); InetAddress address2 = alterByte(address, 3); InetAddressBlock mask = new InetAddressBlock(address, 8); Assert.assertTrue(mask.contains(address2)); }
@Test public void doesNotContainIPV4WithAlteredByte() throws UnknownHostException { InetAddress address = generateIPAddressV4(); InetAddress address2 = alterByte(address, 2); InetAddressBlock mask = new InetAddressBlock(address, 8); Assert.assertFalse(mask.contains(address2)); }
@Test public void doesNotContainIPV6() throws UnknownHostException { InetAddress address = generateIPAddressV4(); InetAddress address2 = generateIPAddressV6(); InetAddressBlock mask = new InetAddressBlock(address, 8); Assert.assertFalse(mask.contains(address2)); }
@Test public void using16BitsMask() throws UnknownHostException { InetAddress address = generateIPAddressV4(); InetAddress address2 = alterByte(address, 2); InetAddressBlock mask = new InetAddressBlock(address, 16); Assert.assertTrue(mask.contains(address2)); }
@Test public void usingIPV4With9BitsMask() throws UnknownHostException { InetAddress address = generateIPAddressV4(); byte[] bytes = address.getAddress(); bytes[2] ^= 1; InetAddress address2 = InetAddress.getByAddress(bytes); bytes[2] ^= 2; InetAddress address3 = InetAddress.getByAddress(bytes); InetAddressBlock mask = new InetAddressBlock(address, 9); Assert.assertTrue(mask.contains(address2)); Assert.assertFalse(mask.contains(address3)); }
@Test public void usingIPV6With9BitsMask() throws UnknownHostException { InetAddress address = generateIPAddressV6(); byte[] bytes = address.getAddress(); bytes[14] ^= 1; InetAddress address2 = InetAddress.getByAddress(bytes); bytes[14] ^= 2; InetAddress address3 = InetAddress.getByAddress(bytes); InetAddressBlock mask = new InetAddressBlock(address, 9); Assert.assertTrue(mask.contains(address2)); Assert.assertFalse(mask.contains(address3)); }
@Test public void usingIPV4With18BitsMask() throws UnknownHostException { InetAddress address = generateIPAddressV4(); byte[] bytes = address.getAddress(); bytes[1] ^= 2; InetAddress address2 = InetAddress.getByAddress(bytes); bytes[1] ^= 4; InetAddress address3 = InetAddress.getByAddress(bytes); InetAddressBlock mask = new InetAddressBlock(address, 18); Assert.assertTrue(mask.contains(address2)); Assert.assertFalse(mask.contains(address3)); }
@Test public void usingIPV6With18BitsMask() throws UnknownHostException { InetAddress address = generateIPAddressV6(); byte[] bytes = address.getAddress(); bytes[13] ^= 2; InetAddress address2 = InetAddress.getByAddress(bytes); bytes[13] ^= 4; InetAddress address3 = InetAddress.getByAddress(bytes); InetAddressBlock mask = new InetAddressBlock(address, 18); Assert.assertTrue(mask.contains(address2)); Assert.assertFalse(mask.contains(address3)); }
@Test public void doesNotContainIPV4() throws UnknownHostException { InetAddress address = generateIPAddressV6(); InetAddress address2 = generateIPAddressV4(); InetAddressBlock mask = new InetAddressBlock(address, 8); Assert.assertFalse(mask.contains(address2)); } |
ByteUtil { public static long byteArrayToLong(byte[] b) { if (b == null || b.length == 0) { return 0; } if (b.length > 8) { throw new IllegalArgumentException("byte array can't have more than 8 bytes if it is to be cast to long"); } long result = 0; for (int i = 0; i < b.length; i++) { result <<= 8; result |= (b[i] & 0xFF); } return result; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void testByteArrayToLong() { assertEquals(Long.MAX_VALUE, ByteUtil.byteArrayToLong(new byte[]{ (byte)127, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, } )); assertEquals(0, ByteUtil.byteArrayToLong(new byte[]{ } )); }
@Test(expected = IllegalArgumentException.class) public void testByteArrayToLongThrowsWhenOverflow() { assertEquals(Long.MAX_VALUE, ByteUtil.byteArrayToLong(new byte[]{ (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)123, } )); } |
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(); } | @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()); } |
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(); } | @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())); } |
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); } | @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")); } |
InetAddressUtils { public static InetAddress getAddressForBan(@CheckForNull String hostname) throws InvalidInetAddressException { if (hostname == null) { throw new InvalidInetAddressException("null address", null); } String name = hostname.trim(); if (name.length() == 0) { throw new InvalidInetAddressException("empty address", null); } try { InetAddress address = InetAddress.getByName(name); if (address.isLoopbackAddress() || address.isAnyLocalAddress()) { throw new InvalidInetAddressException("local address: '" + name + "'", null); } return address; } catch (UnknownHostException ex) { throw new InvalidInetAddressException("unknown host: '" + name + "'", ex); } } private InetAddressUtils(); static boolean hasMask(String text); static InetAddress getAddressForBan(@CheckForNull String hostname); static InetAddressBlock parse(String text); } | @Test public void getAddressFromIPV4() throws InvalidInetAddressException { InetAddress address = InetAddressUtils.getAddressForBan("192.168.56.1"); Assert.assertNotNull(address); byte[] bytes = address.getAddress(); Assert.assertNotNull(bytes); Assert.assertEquals(4, bytes.length); Assert.assertArrayEquals(new byte[] { (byte)192, (byte)168, (byte)56, (byte)1}, bytes); }
@Test public void getAddressFromIPV6() throws InvalidInetAddressException, UnknownHostException { InetAddress address = InetAddressUtils.getAddressForBan("fe80::498a:7f0e:e63d:6b98"); InetAddress expected = InetAddress.getByName("fe80::498a:7f0e:e63d:6b98"); Assert.assertNotNull(address); byte[] bytes = address.getAddress(); Assert.assertNotNull(bytes); Assert.assertEquals(16, bytes.length); Assert.assertArrayEquals(expected.getAddress(), bytes); }
@Test public void getAddressFromNull() { try { InetAddressUtils.getAddressForBan(null); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("null address", ex.getMessage()); } }
@Test public void getAddressFromEmptyString() { try { InetAddressUtils.getAddressForBan(""); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("empty address", ex.getMessage()); } }
@Test public void getAddressFromBlankString() { try { InetAddressUtils.getAddressForBan(" "); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("empty address", ex.getMessage()); } }
@Test public void getLocalAddress() { try { InetAddressUtils.getAddressForBan("127.0.0.1"); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("local address: '127.0.0.1'", ex.getMessage()); } }
@Test public void getLocalHost() { try { InetAddressUtils.getAddressForBan("localhost"); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("local address: 'localhost'", ex.getMessage()); } }
@Test public void getAnyLocalAddress() { try { InetAddressUtils.getAddressForBan("0.0.0.0"); Assert.fail(); } catch (InvalidInetAddressException ex) { Assert.assertEquals("local address: '0.0.0.0'", ex.getMessage()); } } |
InetAddressUtils { public static InetAddressBlock parse(String text) throws InvalidInetAddressException { String[] parts = text.split("/"); InetAddress address; address = InetAddressUtils.getAddressForBan(parts[0]); int nbits; try { nbits = Integer.parseInt(parts[1]); } catch (NumberFormatException ex) { throw new InvalidInetAddressBlockException("Invalid mask", ex); } if (nbits <= 0 || nbits > address.getAddress().length * 8) { throw new InvalidInetAddressBlockException("Invalid mask", null); } return new InetAddressBlock(address, nbits); } private InetAddressUtils(); static boolean hasMask(String text); static InetAddress getAddressForBan(@CheckForNull String hostname); static InetAddressBlock parse(String text); } | @Test public void parseAddressBlock() throws InvalidInetAddressException, InvalidInetAddressBlockException, UnknownHostException { InetAddressBlock result = InetAddressUtils.parse("192.162.12.0/8"); Assert.assertNotNull(result); Assert.assertArrayEquals(InetAddress.getByName("192.162.12.0").getAddress(), result.getBytes()); Assert.assertEquals((byte)0xff, result.getMask()); }
@Test public void parseAddressBlockWithNonNumericBits() throws InvalidInetAddressException { try { InetAddressUtils.parse("192.162.12.0/a"); Assert.fail(); } catch (InvalidInetAddressBlockException ex) { Assert.assertEquals("Invalid mask", ex.getMessage()); } }
@Test public void parseAddressBlockWithNegativeNumberOfBits() throws UnknownHostException, InvalidInetAddressException { try { InetAddressUtils.parse("192.162.12.0/-10"); Assert.fail(); } catch (InvalidInetAddressBlockException ex) { Assert.assertEquals("Invalid mask", ex.getMessage()); } }
@Test public void parseAddressBlockWithZeroBits() throws InvalidInetAddressException { try { InetAddressUtils.parse("192.162.12.0/0"); Assert.fail(); } catch (InvalidInetAddressBlockException ex) { Assert.assertEquals("Invalid mask", ex.getMessage()); } }
@Test public void parseAddressBlockWithTooBigNumberOfBits() throws InvalidInetAddressException { try { InetAddressUtils.parse("192.162.12.0/1000"); Assert.fail(); } catch (InvalidInetAddressBlockException ex) { Assert.assertEquals("Invalid mask", ex.getMessage()); } } |
ByteUtil { public static int byteArrayToInt(byte[] b) { if (b == null || b.length == 0) { return 0; } return new BigInteger(1, b).intValue(); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void testByteArrayToInt() { assertEquals(0, ByteUtil.byteArrayToInt(null)); assertEquals(0, ByteUtil.byteArrayToInt(new byte[0])); } |
ScoringCalculator { public boolean hasGoodReputation(PeerScoring scoring) { return scoring.getEventCounter(EventType.INVALID_BLOCK) < 1 && scoring.getEventCounter(EventType.INVALID_MESSAGE) < 1 && scoring.getEventCounter(EventType.INVALID_HEADER) < 1; } boolean hasGoodReputation(PeerScoring scoring); } | @Test public void emptyScoringHasGoodReputation() { ScoringCalculator calculator = new ScoringCalculator(); PeerScoring scoring = new PeerScoring(); Assert.assertTrue(calculator.hasGoodReputation(scoring)); }
@Test public void scoringWithOneValidBlockHasGoodReputation() { ScoringCalculator calculator = new 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)); } |
ByteUtil { public static int numBytes(String val) { return new BigInteger(val).bitLength() / 8 + 1; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void testNumBytes() { String test1 = "0"; String test2 = "1"; String test3 = "1000000000"; int expected1 = 1; int expected2 = 1; int expected3 = 4; assertEquals(expected1, ByteUtil.numBytes(test1)); assertEquals(expected2, ByteUtil.numBytes(test2)); assertEquals(expected3, ByteUtil.numBytes(test3)); } |
ByteUtil { public static byte[] stripLeadingZeroes(byte[] data) { return stripLeadingZeroes(data, ZERO_BYTE_ARRAY); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void testStripLeadingZeroes() { byte[] test1 = null; byte[] test2 = new byte[]{}; byte[] test3 = new byte[]{0x00}; byte[] test4 = new byte[]{0x00, 0x01}; byte[] test5 = new byte[]{0x00, 0x00, 0x01}; byte[] expected1 = null; byte[] expected2 = new byte[]{0}; byte[] expected3 = new byte[]{0}; byte[] expected4 = new byte[]{0x01}; byte[] expected5 = new byte[]{0x01}; assertArrayEquals(expected1, ByteUtil.stripLeadingZeroes(test1)); assertArrayEquals(expected2, ByteUtil.stripLeadingZeroes(test2)); assertArrayEquals(expected3, ByteUtil.stripLeadingZeroes(test3)); assertArrayEquals(expected4, ByteUtil.stripLeadingZeroes(test4)); assertArrayEquals(expected5, ByteUtil.stripLeadingZeroes(test5)); } |
ByteUtil { public static int matchingNibbleLength(byte[] a, byte[] b) { int i = 0; int length = a.length < b.length ? a.length : b.length; while (i < length) { if (a[i] != b[i]) { return i; } i++; } return i; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void testMatchingNibbleLength1() { byte[] a = new byte[]{0x00, 0x01}; byte[] b = new byte[]{0x00}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(1, result); }
@Test public void testMatchingNibbleLength2() { byte[] a = new byte[]{0x00}; byte[] b = new byte[]{0x00, 0x01}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(1, result); }
@Test public void testMatchingNibbleLength3() { byte[] a = new byte[]{0x00}; byte[] b = new byte[]{0x00}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(1, result); }
@Test public void testMatchingNibbleLength4() { byte[] a = new byte[]{0x01}; byte[] b = new byte[]{0x00}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(0, result); }
@Test(expected = NullPointerException.class) public void testMatchingNibbleLength5() { byte[] a = null; byte[] b = new byte[]{0x00}; ByteUtil.matchingNibbleLength(a, b); }
@Test(expected = NullPointerException.class) public void testMatchingNibbleLength6() { byte[] a = new byte[]{0x00}; byte[] b = null; ByteUtil.matchingNibbleLength(a, b); }
@Test public void testMatchingNibbleLength7() { byte[] a = new byte[0]; byte[] b = new byte[]{0x00}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(0, result); } |
ByteUtil { public static String nibblesToPrettyString(byte[] nibbles) { StringBuilder builder = new StringBuilder(); for (byte nibble : nibbles) { final String nibbleString = oneByteToHexString(nibble); builder.append("\\x").append(nibbleString); } return builder.toString(); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void testNiceNiblesOutput_1() { byte[] test = {7, 0, 7, 5, 7, 0, 7, 0, 7, 9}; String result = "\\x07\\x00\\x07\\x05\\x07\\x00\\x07\\x00\\x07\\x09"; assertEquals(result, ByteUtil.nibblesToPrettyString(test)); }
@Test public void testNiceNiblesOutput_2() { byte[] test = {7, 0, 7, 0xf, 7, 0, 0xa, 0, 7, 9}; String result = "\\x07\\x00\\x07\\x0f\\x07\\x00\\x0a\\x00\\x07\\x09"; assertEquals(result, ByteUtil.nibblesToPrettyString(test)); } |
Web3Impl implements Web3 { @Override public Object eth_syncing() { long currentBlock = this.blockchain.getBestBlock().getNumber(); long highestBlock = this.nodeBlockProcessor.getLastKnownBlockNumber(); if (highestBlock <= currentBlock){ return false; } SyncingResult s = new SyncingResult(); try { s.startingBlock = TypeConverter.toQuantityJsonHex(initialBlockNumber); s.currentBlock = TypeConverter.toQuantityJsonHex(currentBlock); s.highestBlock = toQuantityJsonHex(highestBlock); return s; } finally { logger.debug("eth_syncing(): starting {}, current {}, highest {} ", s.startingBlock, s.currentBlock, s.highestBlock); } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void eth_syncing_returnFalseWhenNotSyncing() { World world = new World(); SimpleBlockProcessor nodeProcessor = new SimpleBlockProcessor(); nodeProcessor.lastKnownBlockNumber = 0; Web3Impl web3 = createWeb3(world, nodeProcessor, null); Object result = web3.eth_syncing(); assertTrue("Node is not syncing, must return false", !(boolean)result); }
@Test public void eth_syncing_returnSyncingResultWhenSyncing() { World world = new World(); SimpleBlockProcessor nodeProcessor = new SimpleBlockProcessor(); nodeProcessor.lastKnownBlockNumber = 5; Web3Impl web3 = createWeb3(world, nodeProcessor, null); Object result = web3.eth_syncing(); assertTrue("Node is syncing, must return sync manager", result instanceof Web3.SyncingResult); assertTrue("Highest block is 5", ((Web3.SyncingResult)result).highestBlock.compareTo("0x5") == 0); assertTrue("Simple blockchain starts from genesis block", ((Web3.SyncingResult)result).currentBlock.compareTo("0x0") == 0); } |
ByteUtil { public static int firstNonZeroByte(byte[] data) { for (int i = 0; i < data.length; ++i) { if (data[i] != 0) { return i; } } return -1; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void firstNonZeroByte_1() { byte[] data = Hex.decode("0000000000000000000000000000000000000000000000000000000000000000"); int result = ByteUtil.firstNonZeroByte(data); assertEquals(-1, result); }
@Test public void firstNonZeroByte_2() { byte[] data = Hex.decode("0000000000000000000000000000000000000000000000000000000000332211"); int result = ByteUtil.firstNonZeroByte(data); assertEquals(29, result); }
@Test public void firstNonZeroByte_3() { byte[] data = Hex.decode("2211009988776655443322110099887766554433221100998877665544332211"); int result = ByteUtil.firstNonZeroByte(data); assertEquals(0, result); } |
ByteUtil { public static byte[] setBit(byte[] data, int pos, int val) { if ((data.length * 8) - 1 < pos) { throw new Error("outside byte array limit, pos: " + pos); } int posByte = data.length - 1 - (pos) / 8; int posBit = (pos) % 8; byte setter = (byte) (1 << (posBit)); byte toBeSet = data[posByte]; byte result; if (val == 1) { result = (byte) (toBeSet | setter); } else { result = (byte) (toBeSet & ~setter); } data[posByte] = result; return data; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void setBitTest() { byte[] data = ByteBuffer.allocate(4).putInt(0).array(); int posBit = 24; int expected = 16777216; int result = -1; byte[] ret = ByteUtil.setBit(data, posBit, 1); result = ByteUtil.byteArrayToInt(ret); assertTrue(expected == result); posBit = 25; expected = 50331648; ret = ByteUtil.setBit(data, posBit, 1); result = ByteUtil.byteArrayToInt(ret); assertTrue(expected == result); posBit = 2; expected = 50331652; ret = ByteUtil.setBit(data, posBit, 1); result = ByteUtil.byteArrayToInt(ret); assertTrue(expected == result); posBit = 24; expected = 33554436; ret = ByteUtil.setBit(data, posBit, 0); result = ByteUtil.byteArrayToInt(ret); assertTrue(expected == result); posBit = 25; expected = 4; ret = ByteUtil.setBit(data, posBit, 0); result = ByteUtil.byteArrayToInt(ret); assertTrue(expected == result); posBit = 2; expected = 0; ret = ByteUtil.setBit(data, posBit, 0); result = ByteUtil.byteArrayToInt(ret); assertTrue(expected == result); } |
ByteUtil { public static int getBit(byte[] data, int pos) { if ((data.length * 8) - 1 < pos) { throw new Error("outside byte array limit, pos: " + pos); } int posByte = data.length - 1 - pos / 8; int posBit = pos % 8; byte dataByte = data[posByte]; return Math.min(1, (dataByte & 0xff & (1 << (posBit)))); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void getBitTest() { byte[] data = ByteBuffer.allocate(4).putInt(0).array(); ByteUtil.setBit(data, 24, 1); ByteUtil.setBit(data, 25, 1); ByteUtil.setBit(data, 2, 1); List<Integer> found = new ArrayList<>(); for (int i = 0; i < (data.length * 8); i++) { int res = ByteUtil.getBit(data, i); if (res == 1) if (i != 24 && i != 25 && i != 2) assertTrue(false); else found.add(i); else { if (i == 24 || i == 25 || i == 2) assertTrue(false); } } if (found.size() != 3) assertTrue(false); assertTrue(found.get(0) == 2); assertTrue(found.get(1) == 24); assertTrue(found.get(2) == 25); } |
ByteUtil { public static int numberOfLeadingZeros(byte[] bytes) { int i = firstNonZeroByte(bytes); if (i == -1) { return bytes.length * 8; } else { int byteLeadingZeros = Integer.numberOfLeadingZeros((int)bytes[i] & 0xff) - 24; return i * 8 + byteLeadingZeros; } } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void testNumberOfLeadingZeros() { int n0 = ByteUtil.numberOfLeadingZeros(new byte[0]); assertEquals(0, n0); int n1 = ByteUtil.numberOfLeadingZeros(Hex.decode("05")); assertEquals(5, n1); int n2 = ByteUtil.numberOfLeadingZeros(Hex.decode("01")); assertEquals(7, n2); int n3 = ByteUtil.numberOfLeadingZeros(Hex.decode("00")); assertEquals(8, n3); int n4 = ByteUtil.numberOfLeadingZeros(Hex.decode("ff")); assertEquals(0, n4); byte[] v1 = Hex.decode("1040"); int n5 = ByteUtil.numberOfLeadingZeros(v1); assertEquals(3, n5); byte[] v2 = new byte[4]; System.arraycopy(v1, 0, v2, 2, v1.length); int n6 = ByteUtil.numberOfLeadingZeros(v2); assertEquals(19, n6); byte[] v3 = new byte[8]; int n7 = ByteUtil.numberOfLeadingZeros(v3); assertEquals(64, n7); } |
ByteUtil { public static byte[] parseBytes(byte[] input, int offset, int len) { if (offset >= input.length || len == 0) { return EMPTY_BYTE_ARRAY; } byte[] bytes = new byte[len]; System.arraycopy(input, offset, bytes, 0, Math.min(input.length - offset, len)); return bytes; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static byte[] parseBytes(byte[] input, int offset, int len); static byte[] parseWord(byte[] input, int idx); static byte[] parseWord(byte[] input, int offset, int idx); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static byte[] longToBytesNoLeadZeroes(long val); static byte[] intToBytes(int val); static byte[] intToBytesNoLeadZeroes(int val); @Nonnull static String toHexStringOrEmpty(@Nullable byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data); @Nonnull static String toHexString(@Nonnull byte[] data, int off, int length); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static long byteArrayToLong(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static int firstNonZeroByte(byte[] data); static byte[] stripLeadingZeroes(byte[] data); static byte[] stripLeadingZeroes(byte[] data, byte[] valueForZero); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static ByteArrayWrapper wrap(byte[] data); static byte[] setBit(byte[] data, int pos, int val); static int getBit(byte[] data, int pos); static byte[] and(byte[] b1, byte[] b2); static byte[] or(byte[] b1, byte[] b2); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftLeft(byte[] byteArray, int shiftBitCount); @java.lang.SuppressWarnings("squid:S3034") static byte[] shiftRight(byte[] byteArray, int shiftBitCount); static byte[] merge(byte[]... arrays); static boolean isSingleZero(byte[] array); static boolean isAllZeroes(byte[] array); static Set<T> difference(Set<T> setA, Set<T> setB); static int length(byte[]... bytes); static short bigEndianToShort(byte[] bs); static short bigEndianToShort(byte[] bs, int off); static byte[] shortToBytes(short n); static int numberOfLeadingZeros(byte[] bytes); static byte[] leftPadBytes(@Nonnull byte[] original, int newLength); static boolean fastEquals(byte[] left, byte[] right); static final byte[] EMPTY_BYTE_ARRAY; } | @Test public void testParseBytes() { byte[] shortByteArray = new byte[]{0,1}; byte[] normalByteArray = new byte[]{0,1,2,3,4,5}; byte[] normalByteArrayOffset3LeadingZeroes = new byte[]{3,4,5,0,0,0}; byte[] b1 = ByteUtil.parseBytes(shortByteArray, shortByteArray.length+1, 10); assertEquals(b1,ByteUtil.EMPTY_BYTE_ARRAY); byte[] b2 = ByteUtil.parseBytes(shortByteArray, shortByteArray.length-1, 0); assertEquals(b1,ByteUtil.EMPTY_BYTE_ARRAY); byte[] b3 = ByteUtil.parseBytes(normalByteArray, normalByteArray.length -3, normalByteArrayOffset3LeadingZeroes.length); for (int i=0; i < b3.length; i++) { assertEquals(b3[i],normalByteArrayOffset3LeadingZeroes[i]); } } |
Web3Impl implements Web3 { @Override public String eth_getBalance(String address, String block) { AccountInformationProvider accountInformationProvider = web3InformationRetriever.getInformationProvider(block); RskAddress addr = new RskAddress(address); Coin balance = accountInformationProvider.getBalance(addr); return toQuantityJsonHex(balance.asBigInteger()); } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getBalanceWithAccount() throws Exception { World world = new World(); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(10000)).build(); Web3Impl web3 = createWeb3(world); org.junit.Assert.assertEquals("0x" + ByteUtil.toHexString(BigInteger.valueOf(10000).toByteArray()), web3.eth_getBalance(ByteUtil.toHexString(acc1.getAddress().getBytes()))); }
@Test public void getBalanceWithAccountAndLatestBlock() throws Exception { World world = new World(); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(10000)).build(); Web3Impl web3 = createWeb3(world); org.junit.Assert.assertEquals("0x" + ByteUtil.toHexString(BigInteger.valueOf(10000).toByteArray()), web3.eth_getBalance(ByteUtil.toHexString(acc1.getAddress().getBytes()), "latest")); }
@Test public void getBalanceWithAccountAndGenesisBlock() throws Exception { World world = new World(); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(10000)).build(); Web3Impl web3 = createWeb3(world); String accountAddress = ByteUtil.toHexString(acc1.getAddress().getBytes()); String balanceString = "0x" + ByteUtil.toHexString(BigInteger.valueOf(10000).toByteArray()); org.junit.Assert.assertEquals(balanceString, web3.eth_getBalance(accountAddress, "0x0")); }
@Test public void getBalanceWithAccountAndBlock() throws Exception { World world = new World(); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(10000)).build(); Block genesis = world.getBlockByName("g00"); Block block1 = new BlockBuilder(null, null, null).parent(genesis).build(); world.getBlockChain().tryToConnect(block1); Web3Impl web3 = createWeb3(world); String accountAddress = ByteUtil.toHexString(acc1.getAddress().getBytes()); String balanceString = "0x" + ByteUtil.toHexString(BigInteger.valueOf(10000).toByteArray()); org.junit.Assert.assertEquals(balanceString, web3.eth_getBalance(accountAddress, "0x1")); }
@Test public void getBalanceWithAccountAndBlockWithTransaction() throws Exception { World world = new World(); BlockChainImpl blockChain = world.getBlockChain(); TransactionPool transactionPool = world.getTransactionPool(); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(10000000)).build(); Account acc2 = new AccountBuilder(world).name("acc2").build(); Block genesis = world.getBlockByName("g00"); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(10000)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).transactions(txs).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block1)); Web3Impl web3 = createWeb3(world, transactionPool, null); String accountAddress = ByteUtil.toHexString(acc2.getAddress().getBytes()); String balanceString = "0x" + ByteUtil.toHexString(BigInteger.valueOf(10000).toByteArray()); org.junit.Assert.assertEquals("0x0", web3.eth_getBalance(accountAddress, "0x0")); org.junit.Assert.assertEquals(balanceString, web3.eth_getBalance(accountAddress, "0x1")); org.junit.Assert.assertEquals(balanceString, web3.eth_getBalance(accountAddress, "pending")); } |
Utils { public static String getValueShortString(BigInteger number) { BigInteger result = number; int pow = 0; while (result.compareTo(_1000_) == 1 || result.compareTo(_1000_) == 0) { result = result.divide(_1000_); pow += 3; } return result.toString() + "·(" + "10^" + pow + ")"; } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; } | @Test public void testGetValueShortString1() { String expected = "123·(10^24)"; String result = Utils.getValueShortString(new BigInteger("123456789123445654363653463")); assertEquals(expected, result); }
@Test public void testGetValueShortString2() { String expected = "123·(10^3)"; String result = Utils.getValueShortString(new BigInteger("123456")); assertEquals(expected, result); }
@Test public void testGetValueShortString3() { String expected = "1·(10^3)"; String result = Utils.getValueShortString(new BigInteger("1234")); assertEquals(expected, result); }
@Test public void testGetValueShortString4() { String expected = "123·(10^0)"; String result = Utils.getValueShortString(new BigInteger("123")); assertEquals(expected, result); }
@Test public void testGetValueShortString5() { byte[] decimal = Hex.decode("3913517ebd3c0c65000000"); String expected = "69·(10^24)"; String result = Utils.getValueShortString(new BigInteger(decimal)); assertEquals(expected, result); } |
Utils { public static byte[] addressStringToBytes(String hex) { final byte[] addr; try { addr = Hex.decode(hex); } catch (DecoderException addressIsNotValid) { return null; } if (isValidAddress(addr)) { return addr; } return null; } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; } | @Test public void testAddressStringToBytes() { String HexStr = "6c386a4b26f73c802f34673f7248bb118f97424a"; byte[] expected = Hex.decode(HexStr); byte[] result = Utils.addressStringToBytes(HexStr); assertEquals(Arrays.areEqual(expected, result), true); HexStr = "6c386a4b26f73c802f34673f7248bb118f97424"; expected = null; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); HexStr = new String(Hex.encode("I am longer than 20 bytes, i promise".getBytes())); expected = null; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); HexStr = new String(Hex.encode("I am short".getBytes())); expected = null; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); } |
Utils { public static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize) { if (data.length < Math.addExact(allegedSize, offset)) { throw new IllegalArgumentException("The specified size exceeds the size of the payload"); } } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; } | @Test public void TestValidateArrayWithOffset() { byte[] data = new byte[10]; Utils.validateArrayAllegedSize(data, 1, 0); Utils.validateArrayAllegedSize(data, 8, 1); Utils.validateArrayAllegedSize(data, 0, 10); Utils.validateArrayAllegedSize(data, 8, 2); Utils.validateArrayAllegedSize(data, 11, -1); Utils.validateArrayAllegedSize(data, -2, 12); try { Utils.validateArrayAllegedSize(data, 0, 11); fail("should have failed"); } catch (IllegalArgumentException e) { } try { Utils.validateArrayAllegedSize(data, 2, 9); fail("should have failed"); } catch (IllegalArgumentException e) { } try { Utils.validateArrayAllegedSize(new byte[0], 1, 0); fail("should have failed"); } catch (IllegalArgumentException e) { } byte[] noData = null; try { Utils.validateArrayAllegedSize(noData, 1, 1); fail("should have failed"); } catch (NullPointerException e) { } } |
Utils { public static byte[] safeCopyOfRange(byte[] data, int from, int size) { validateArrayAllegedSize(data, from, size); return Arrays.copyOfRange(data, from, from + size); } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; } | @Test public void TestSafeCopyOfRangeWithValidArrays() { Utils.safeCopyOfRange(new byte[2], 0, 1); Utils.safeCopyOfRange(new byte[100], 97, 3); Utils.safeCopyOfRange(new byte[0], 0, 0); }
@Test public void TestSafeCopyOfRangeWithInvalidArrays() { try { Utils.safeCopyOfRange(new byte[2], 1, 2); fail("should have failed"); } catch (IllegalArgumentException e){ } try { Utils.safeCopyOfRange(new byte[100], 98, 3); fail("should have failed"); } catch (IllegalArgumentException e){ } try { Utils.safeCopyOfRange(new byte[0], 0, 1); fail("should have failed"); } catch (IllegalArgumentException e){ } try { Utils.safeCopyOfRange(new byte[0], 1, 0); fail("should have failed"); } catch (IllegalArgumentException e){ } } |
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; } | @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))); } |
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; } | @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))); } |
Utils { public static long decimalStringToLong(String s) { try { return Long.parseLong(s, 10); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("Invalid decimal number: %s", s), e); } } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; } | @Test public void decimalStringToLong() { Object[] cases = new Object[] { "1", 1L, "123", 123L, "045670", 45670L, "220", 220L, "0", 0L, "01", 1L }; for (int i = 0; i < cases.length/2; i++) { String s = (String) cases[i*2]; long expected = (long) cases[i*2+1]; Assert.assertEquals(expected, Utils.decimalStringToLong(s)); } }
@Test(expected = IllegalArgumentException.class) public void decimalStringToLongFail() { Utils.decimalStringToLong("zzz"); } |
Utils { public static long hexadecimalStringToLong(String s) { if (!s.startsWith("0x")) { throw new IllegalArgumentException(String.format("Invalid hexadecimal number: %s", s)); } try { return Long.parseLong(s.substring(2), 16); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("Invalid hexadecimal number: %s", s), e); } } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; } | @Test public void hexadecimalStringToLong() { Object[] cases = new Object[] { "0x1", 1L, "0xaaa", 2730L, "0xAAA", 2730L, "0xAFe1", 45025L, "0x10", 16L, "0xA12", 2578L }; for (int i = 0; i < cases.length/2; i++) { String s = (String) cases[i*2]; long expected = (long) cases[i*2+1]; Assert.assertEquals(expected, Utils.hexadecimalStringToLong(s)); } }
@Test(expected = IllegalArgumentException.class) public void hexadecimalStringToLongFail() { Utils.hexadecimalStringToLong("abcd"); }
@Test(expected = IllegalArgumentException.class) public void hexadecimalStringToLongFailBis() { Utils.hexadecimalStringToLong("zzz"); } |
Utils { public static int significantBitCount(int number) { int result = 0; while (number > 0) { result++; number >>= 1; } return result; } static BigInteger unifiedNumericToBigInteger(String number); static String longToDateTime(long timestamp); static String getValueShortString(BigInteger number); static byte[] addressStringToBytes(String hex); static boolean isValidAddress(byte[] addr); static String getAddressShortString(byte[] addr); static SecureRandom getRandom(); static String getHashListShort(List<byte[]> blockHashes); static long toUnixTime(long javaTime); static long fromUnixTime(long unixTime); static T[] mergeArrays(T[] ... arr); static String align(String s, char fillChar, int targetLen, boolean alignRight); static String repeat(String s, int n); static boolean contains(List<byte[]> list, byte[] valueToFind); static void validateArrayAllegedSize(byte[] data, int offset, int allegedSize); static byte[] safeCopyOfRange(byte[] data, int from, int size); static boolean isDecimalString(String s); static boolean isHexadecimalString(String s); static long decimalStringToLong(String s); static long hexadecimalStringToLong(String s); static int significantBitCount(int number); static final double JAVA_VERSION; } | @Test public void significantBitCount() { Assert.assertEquals(0, Utils.significantBitCount(0b0)); Assert.assertEquals(1, Utils.significantBitCount(0b1)); Assert.assertEquals(2, Utils.significantBitCount(0b10)); Assert.assertEquals(2, Utils.significantBitCount(0b11)); Assert.assertEquals(3, Utils.significantBitCount(0b111)); Assert.assertEquals(3, Utils.significantBitCount(0b100)); Assert.assertEquals(3, Utils.significantBitCount(0b101)); Assert.assertEquals(13, Utils.significantBitCount(0b1000111000101)); Assert.assertEquals(9, Utils.significantBitCount(0b000111000101)); } |
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); } | @Test public void testEqualsObject() { assertTrue(wrapper1.equals(wrapper2)); assertFalse(wrapper1.equals(wrapper3)); assertFalse(wrapper1.equals(wrapper4)); assertFalse(wrapper1.equals(null)); assertFalse(wrapper2.equals(wrapper3)); } |
ByteArrayWrapper implements Comparable<ByteArrayWrapper>, Serializable { @Override public int compareTo(ByteArrayWrapper o) { return FastByteComparisons.compareTo( data, 0, data.length, o.data, 0, o.data.length); } ByteArrayWrapper(byte[] data); boolean equals(Object other); @Override int hashCode(); @Override int compareTo(ByteArrayWrapper o); byte[] getData(); @Override String toString(); boolean equalsToByteArray(byte[] otherData); } | @Test public void testCompareTo() { assertTrue(wrapper1.compareTo(wrapper2) == 0); assertTrue(wrapper1.compareTo(wrapper3) > 1); assertTrue(wrapper1.compareTo(wrapper4) > 1); assertTrue(wrapper2.compareTo(wrapper3) > 1); } |
ReceiptStoreImpl implements ReceiptStore { @Override public TransactionInfo get(byte[] transactionHash){ List<TransactionInfo> txs = getAll(transactionHash); if (txs.isEmpty()) { return null; } return txs.get(txs.size() - 1); } ReceiptStoreImpl(KeyValueDataSource receiptsDS); @Override void add(byte[] blockHash, int 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(); } | @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()); } |
IndexedBlockStore implements BlockStore { public void rewind(long blockNumber) { if (index.isEmpty()) { return; } long maxNumber = getMaxNumber(); for (long i = maxNumber; i > blockNumber; i--) { List<BlockInfo> blockInfos = index.removeLast(); for (BlockInfo blockInfo : blockInfos) { this.blocks.delete(blockInfo.getHash().getBytes()); } } flush(); } IndexedBlockStore(
BlockFactory blockFactory,
KeyValueDataSource blocks,
BlocksIndex index); @Override synchronized void removeBlock(Block block); @Override synchronized Block getBestBlock(); @Override byte[] getBlockHashByNumber(long blockNumber, byte[] branchBlockHash); @Override // This method is an optimized way to traverse a branch in search for a block at a given depth. Starting at a given // block (by hash) it tries to find the first block that is part of the best chain, when it finds one we now that // we can jump to the block that is at the remaining depth. If not block is found then it continues traversing the // branch from parent to parent. The search is limited by the maximum depth received as parameter. // This method either needs to traverse the parent chain or if a block in the parent chain is part of the best chain // then it can skip the traversal by going directly to the block at the remaining depth. Block getBlockAtDepthStartingAt(long depth, byte[] hash); boolean isBlockInMainChain(long blockNumber, Keccak256 blockHash); @Override synchronized void flush(); void close(); @Override synchronized void saveBlock(Block block, BlockDifficulty cummDifficulty, boolean mainChain); @Override synchronized List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean isEmpty(); @Override synchronized Block getChainBlockByNumber(long number); @Override synchronized Block getBlockByHash(byte[] hash); @Override synchronized Map<Long, List<Sibling>> getSiblingsFromBlockByHash(Keccak256 hash); @Override synchronized boolean isBlockExist(byte[] hash); @Override synchronized BlockDifficulty getTotalDifficultyForHash(byte[] hash); @Override long getMaxNumber(); @Override long getMinNumber(); @Override synchronized List<byte[]> getListHashesEndWith(byte[] hash, long number); @Override synchronized void reBranch(Block forkBlock); @VisibleForTesting synchronized List<byte[]> getListHashesStartWith(long number, long maxBlocks); @Override synchronized List<Block> getChainBlocksByNumber(long number); void rewind(long blockNumber); static final Serializer<List<BlockInfo>> BLOCK_INFO_SERIALIZER; } | @Test public void rewind() { IndexedBlockStore indexedBlockStore = new IndexedBlockStore( mock(BlockFactory.class), mock(KeyValueDataSource.class), new HashMapBlocksIndex()); long blocksToGenerate = 14; for (long i = 0; i < blocksToGenerate; i++) { Block block = mock(Block.class); Keccak256 blockHash = randomHash(); when(block.getHash()).thenReturn(blockHash); when(block.getNumber()).thenReturn(i); indexedBlockStore.saveBlock(block, ZERO, true); } Block bestBlock = indexedBlockStore.getBestBlock(); assertThat(bestBlock.getNumber(), is(blocksToGenerate - 1)); long blockToRewind = blocksToGenerate / 2; indexedBlockStore.rewind(blockToRewind); bestBlock = indexedBlockStore.getBestBlock(); assertThat(bestBlock.getNumber(), is(blockToRewind)); } |
Constants { public static Constants devnetWithFederation(List<BtcECKey> federationPublicKeys) { return new Constants( DEVNET_CHAIN_ID, false, 14, new BlockDifficulty(BigInteger.valueOf(131072)), new BlockDifficulty(BigInteger.valueOf((long) 14E15)), BigInteger.valueOf(50), 540, new BridgeDevNetConstants(federationPublicKeys) ); } Constants(
byte chainId,
boolean seedCowAccounts,
int durationLimit,
BlockDifficulty minimumDifficulty,
BlockDifficulty fallbackMiningDifficulty,
BigInteger difficultyBoundDivisor,
int newBlockMaxSecondsInTheFuture,
BridgeConstants bridgeConstants); boolean seedCowAccounts(); int getDurationLimit(); BlockDifficulty getMinimumDifficulty(); BlockDifficulty getFallbackMiningDifficulty(); BigInteger getDifficultyBoundDivisor(ActivationConfig.ForBlock activationConfig); byte getChainId(); int getNewBlockMaxSecondsInTheFuture(); BridgeConstants getBridgeConstants(); BigInteger getInitialNonce(); byte[] getFallbackMiningPubKey0(); byte[] getFallbackMiningPubKey1(); int getMaximumExtraDataSize(); int getMinGasLimit(); int getGasLimitBoundDivisor(); int getExpDifficultyPeriod(); int getUncleGenerationLimit(); int getUncleListLimit(); int getBestNumberDiffLimit(); BigInteger getMinimumPayableGas(); BigInteger getFederatorMinimumPayableGas(); static BigInteger getSECP256K1N(); static BigInteger getTransactionGasCap(); static int getMaxContractSize(); static int getMaxAddressByteLength(); static Constants mainnet(); static Constants devnetWithFederation(List<BtcECKey> federationPublicKeys); static Constants testnet(); static Constants regtest(); static Constants regtestWithFederation(List<BtcECKey> genesisFederationPublicKeys); static final byte MAINNET_CHAIN_ID; static final byte TESTNET_CHAIN_ID; static final byte DEVNET_CHAIN_ID; static final byte REGTEST_CHAIN_ID; final BridgeConstants bridgeConstants; } | @Test public void devnetWithFederationTest() { Constants constants = Constants.devnetWithFederation(TEST_FED_KEYS.subList(0, 3)); assertThat(constants.getBridgeConstants().getGenesisFederation().hasBtcPublicKey(TEST_FED_KEYS.get(0)), is(true)); assertThat(constants.getBridgeConstants().getGenesisFederation().hasBtcPublicKey(TEST_FED_KEYS.get(1)), is(true)); assertThat(constants.getBridgeConstants().getGenesisFederation().hasBtcPublicKey(TEST_FED_KEYS.get(2)), is(true)); assertThat(constants.getBridgeConstants().getGenesisFederation().hasBtcPublicKey(TEST_FED_KEYS.get(3)), is(false)); } |
ActivationConfig { public static ActivationConfig read(Config config) { Map<NetworkUpgrade, Long> networkUpgrades = new EnumMap<>(NetworkUpgrade.class); Config networkUpgradesConfig = config.getConfig(PROPERTY_ACTIVATION_HEIGHTS); for (Map.Entry<String, ConfigValue> e : networkUpgradesConfig.entrySet()) { NetworkUpgrade networkUpgrade = NetworkUpgrade.named(e.getKey()); long activationHeight = networkUpgradesConfig.getLong(networkUpgrade.getName()); networkUpgrades.put(networkUpgrade, activationHeight); } Map<ConsensusRule, Long> activationHeights = new EnumMap<>(ConsensusRule.class); Config consensusRulesConfig = config.getConfig(PROPERTY_CONSENSUS_RULES); for (Map.Entry<String, ConfigValue> e : consensusRulesConfig.entrySet()) { ConsensusRule consensusRule = ConsensusRule.fromConfigKey(e.getKey()); long activationHeight = parseActivationHeight(networkUpgrades, consensusRulesConfig, consensusRule); activationHeights.put(consensusRule, activationHeight); } return new ActivationConfig(activationHeights); } ActivationConfig(Map<ConsensusRule, Long> activationHeights); boolean isActive(ConsensusRule consensusRule, long blockNumber); ForBlock forBlock(long blockNumber); static ActivationConfig read(Config config); } | @Test(expected = IllegalArgumentException.class) public void failsReadingWithMissingNetworkUpgrade() { ActivationConfig.read(BASE_CONFIG .withoutPath("consensusRules.rskip85") ); }
@Test(expected = IllegalArgumentException.class) public void failsReadingWithMissingHardFork() { ActivationConfig.read(BASE_CONFIG .withoutPath("hardforkActivationHeights.orchid") ); }
@Test(expected = IllegalArgumentException.class) public void failsReadingWithUnknownForkConfiguration() { ActivationConfig.read(BASE_CONFIG .withValue("hardforkActivationHeights.orkid", ConfigValueFactory.fromAnyRef(200)) ); }
@Test(expected = IllegalArgumentException.class) public void failsReadingWithUnknownUpgradeConfiguration() { ActivationConfig.read(BASE_CONFIG .withValue("consensusRules.rskip420", ConfigValueFactory.fromAnyRef("orchid")) ); } |
EncryptionHandshake { public AuthInitiateMessage createAuthInitiate(@Nullable byte[] token, ECKey key) { AuthInitiateMessage message = new AuthInitiateMessage(); boolean isToken; if (token == null) { isToken = false; BigInteger secretScalar = remotePublicKey.multiply(key.getPrivKey()).normalize().getXCoord().toBigInteger(); token = ByteUtil.bigIntegerToBytes(secretScalar, NONCE_SIZE); } else { isToken = true; } byte[] nonce = initiatorNonce; byte[] signed = xor(token, nonce); message.setSignature(ECDSASignature.fromSignature(ephemeralKey.sign(signed))); message.isTokenUsed = isToken; message.ephemeralPublicHash = keccak256(ephemeralKey.getPubKeyPoint().getEncoded(false), 1, 64); message.publicKey = key.getPubKeyPoint(); message.nonce = initiatorNonce; return message; } EncryptionHandshake(ECPoint remotePublicKey); EncryptionHandshake(ECPoint remotePublicKey, ECKey ephemeralKey, byte[] initiatorNonce, byte[] responderNonce, boolean isInitiator); EncryptionHandshake(); AuthInitiateMessageV4 createAuthInitiateV4(ECKey key); byte[] encryptAuthInitiateV4(AuthInitiateMessageV4 message); AuthInitiateMessageV4 decryptAuthInitiateV4(byte[] in, ECKey myKey); byte[] encryptAuthResponseV4(AuthResponseMessageV4 message); AuthResponseMessageV4 decryptAuthResponseV4(byte[] in, ECKey myKey); AuthResponseMessageV4 handleAuthResponseV4(ECKey myKey, byte[] initiatePacket, byte[] responsePacket); AuthInitiateMessage createAuthInitiate(@Nullable byte[] token, ECKey key); byte[] encryptAuthMessage(AuthInitiateMessage message); byte[] encryptAuthResponse(AuthResponseMessage message); AuthResponseMessage decryptAuthResponse(byte[] ciphertext, ECKey myKey); AuthInitiateMessage decryptAuthInitiate(byte[] ciphertext, ECKey myKey); AuthResponseMessage handleAuthResponse(ECKey myKey, byte[] initiatePacket, byte[] responsePacket); byte[] handleAuthInitiate(byte[] initiatePacket, ECKey key); static byte recIdFromSignatureV(int v); Secrets getSecrets(); ECPoint getRemotePublicKey(); boolean isInitiator(); static final int NONCE_SIZE; static final int MAC_SIZE; static final int SECRET_SIZE; } | @Test public void testCreateAuthInitiate() throws Exception { AuthInitiateMessage message = initiator.createAuthInitiate(new byte[32], myKey); int expectedLength = 65+32+64+32+1; byte[] buffer = message.encode(); assertEquals(expectedLength, buffer.length); } |
Node implements Serializable { public InetSocketAddress getAddress() { return new InetSocketAddress(this.getHost(), this.getPort()); } Node(String enodeURL); Node(byte[] id, String host, int port); Node(byte[] rlp); NodeID getId(); String getHexId(); String getHost(); int getPort(); byte[] getRLP(); InetSocketAddress getAddress(); String getAddressAsString(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object o); } | @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)); } |
NodeManager { public synchronized List<NodeHandler> getNodes(Set<String> nodesInUse) { List<NodeHandler> handlers = new ArrayList<>(); List<Node> foundNodes = this.peerExplorer.getNodes(); if (this.discoveryEnabled && !foundNodes.isEmpty()) { logger.debug("{} Nodes retrieved from the PE.", foundNodes.size()); foundNodes.stream().filter(n -> !nodeHandlerMap.containsKey(n.getHexId())).forEach(this::createNodeHandler); } for(NodeHandler handler : this.nodeHandlerMap.values()) { if(!nodesInUse.contains(handler.getNode().getHexId())) { handlers.add(handler); } } return handlers; } NodeManager(PeerExplorer peerExplorer, SystemProperties config); NodeStatistics getNodeStatistics(Node n); synchronized List<NodeHandler> getNodes(Set<String> nodesInUse); } | @Test public void getNodesPeerDiscoveryDisable() { List<Node> activePeers = new ArrayList<>(); activePeers.add(new Node(Hex.decode(NODE_ID_2), "127.0.0.2", 8081)); List<Node> bootNodes = new ArrayList<>(); bootNodes.add(new Node(Hex.decode(NODE_ID_3), "127.0.0.3", 8083)); Mockito.when(config.peerActive()).thenReturn(activePeers); Mockito.when(peerExplorer.getNodes()).thenReturn(bootNodes); Mockito.when(config.isPeerDiscoveryEnabled()).thenReturn(false); NodeManager nodeManager = new NodeManager(peerExplorer, config); Set<String> nodesInUse = new HashSet<>(); List<NodeHandler> availableNodes = nodeManager.getNodes(nodesInUse); Assert.assertEquals(1, availableNodes.size()); Assert.assertEquals(NODE_ID_2, availableNodes.get(0).getNode().getHexId()); nodesInUse.add(NODE_ID_2); availableNodes = nodeManager.getNodes(nodesInUse); Assert.assertEquals(0, availableNodes.size()); }
@Test public void getNodesPeerDiscoveryEnableNoPeersFound() { List<Node> activePeers = new ArrayList<>(); List<Node> bootNodes = new ArrayList<>(); Mockito.when(config.peerActive()).thenReturn(activePeers); Mockito.when(peerExplorer.getNodes()).thenReturn(bootNodes); Mockito.when(config.isPeerDiscoveryEnabled()).thenReturn(true); NodeManager nodeManager = new NodeManager(peerExplorer, config); Set<String> nodesInUse = new HashSet<>(); List<NodeHandler> availableNodes = nodeManager.getNodes(nodesInUse); Assert.assertEquals(0, availableNodes.size()); }
@Test public void getNodesPeerDiscoveryEnable() { List<Node> activePeers = new ArrayList<>(); activePeers.add(new Node(Hex.decode(NODE_ID_2), "127.0.0.2", 8081)); List<Node> bootNodes = new ArrayList<>(); bootNodes.add(new Node(Hex.decode(NODE_ID_3), "127.0.0.3", 8083)); Mockito.when(config.peerActive()).thenReturn(activePeers); Mockito.when(peerExplorer.getNodes()).thenReturn(bootNodes); Mockito.when(config.isPeerDiscoveryEnabled()).thenReturn(true); NodeManager nodeManager = new NodeManager(peerExplorer, config); Set<String> nodesInUse = new HashSet<>(); List<NodeHandler> availableNodes = nodeManager.getNodes(nodesInUse); Assert.assertEquals(2, availableNodes.size()); } |
NodeManager { public NodeStatistics getNodeStatistics(Node n) { return discoveryEnabled ? getNodeHandler(n).getNodeStatistics() : DUMMY_STAT; } NodeManager(PeerExplorer peerExplorer, SystemProperties config); NodeStatistics getNodeStatistics(Node n); synchronized List<NodeHandler> getNodes(Set<String> nodesInUse); } | @Test public void purgeNodesTest() { Random random = new Random(); Mockito.when(config.isPeerDiscoveryEnabled()).thenReturn(true); NodeManager nodeManager = new NodeManager(peerExplorer, config); Set<String> keys = new HashSet<>(); for (int i = 0; i <= NodeManager.NODES_TRIM_THRESHOLD+1;i++) { byte[] nodeId = new byte[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); } |
Channel implements Peer { public void setInetSocketAddress(InetSocketAddress inetSocketAddress) { this.inetSocketAddress = inetSocketAddress; } Channel(MessageQueue msgQueue,
MessageCodec messageCodec,
NodeManager nodeManager,
RskWireProtocol.Factory rskWireProtocolFactory,
Eth62MessageFactory eth62MessageFactory,
StaticMessages staticMessages,
String remoteId); void sendHelloMessage(ChannelHandlerContext ctx, FrameCodec frameCodec, String nodeId,
HelloMessage inboundHelloMessage); void activateEth(ChannelHandlerContext ctx, EthVersion version); void setInetSocketAddress(InetSocketAddress inetSocketAddress); NodeStatistics getNodeStatistics(); void setNode(byte[] nodeId); Node getNode(); void initMessageCodes(List<Capability> caps); boolean isProtocolsInitialized(); boolean isUsingNewProtocol(); void onDisconnect(); String getPeerId(); boolean isActive(); NodeID getNodeId(); void disconnect(ReasonCode reason); InetSocketAddress getInetSocketAddress(); PeerStatistics getPeerStats(); boolean hasEthStatusSucceeded(); BigInteger getTotalDifficulty(); SyncStatistics getSyncStats(); void dropConnection(); void sendMessage(Message message); @Override NodeID getPeerNodeID(); @Override InetAddress getAddress(); Stats getStats(); @Override boolean equals(Object o); @Override int hashCode(); @Override double score(long currentTime, MessageType type); @Override void imported(boolean best); @Override String toString(); } | @Test public void equals_true() { InetSocketAddress inetSocketAddress = mock(InetSocketAddress.class); Channel otherChannel = new Channel( messageQueue, messageCodec, nodeManager, rskWireProtocolFactory, eth62MessageFactory, staticMessages, remoteId); target.setInetSocketAddress(inetSocketAddress); otherChannel.setInetSocketAddress(inetSocketAddress); assertEquals(target, otherChannel); }
@Test public void equals_false() { InetSocketAddress inetSocketAddress = mock(InetSocketAddress.class); Channel otherChannel = new Channel( messageQueue, messageCodec, nodeManager, rskWireProtocolFactory, eth62MessageFactory, staticMessages, remoteId); target.setInetSocketAddress(inetSocketAddress); assertNotEquals(target, otherChannel); } |
ChannelManagerImpl implements ChannelManager { @VisibleForTesting int getNumberOfPeersToSendStatusTo(int peerCount) { int peerCountSqrt = (int) Math.sqrt(peerCount); return Math.min(10, Math.min(Math.max(3, peerCountSqrt), peerCount)); } ChannelManagerImpl(RskSystemProperties config, SyncPool syncPool); @Override void start(); @Override void stop(); @VisibleForTesting void tryProcessNewPeers(); boolean isRecentlyDisconnected(InetAddress peerAddress); @Nonnull Set<NodeID> broadcastBlock(@Nonnull final Block block); @Nonnull Set<NodeID> broadcastBlockHash(@Nonnull final List<BlockIdentifier> identifiers, final Set<NodeID> targets); @Override int broadcastStatus(Status status); void add(Channel peer); void notifyDisconnect(Channel channel); Collection<Peer> getActivePeers(); boolean isAddressBlockAvailable(InetAddress inetAddress); @Nonnull Set<NodeID> broadcastTransaction(@Nonnull final Transaction transaction, @Nonnull final Set<NodeID> skip); @Override Set<NodeID> broadcastTransactions(@Nonnull final List<Transaction> transactions, @Nonnull final Set<NodeID> skip); @VisibleForTesting void setActivePeers(Map<NodeID, Channel> newActivePeers); } | @Test public void getNumberOfPeersToSendStatusTo() { ChannelManagerImpl channelManagerImpl = new ChannelManagerImpl(new TestSystemProperties(), null);; assertEquals(1, channelManagerImpl.getNumberOfPeersToSendStatusTo(1)); assertEquals(2, channelManagerImpl.getNumberOfPeersToSendStatusTo(2)); assertEquals(3, channelManagerImpl.getNumberOfPeersToSendStatusTo(3)); assertEquals(3, channelManagerImpl.getNumberOfPeersToSendStatusTo(5)); assertEquals(3, channelManagerImpl.getNumberOfPeersToSendStatusTo(9)); assertEquals(3, channelManagerImpl.getNumberOfPeersToSendStatusTo(12)); assertEquals(4, channelManagerImpl.getNumberOfPeersToSendStatusTo(20)); assertEquals(5, channelManagerImpl.getNumberOfPeersToSendStatusTo(25)); assertEquals(10, channelManagerImpl.getNumberOfPeersToSendStatusTo(1000)); } |
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); } | @Test public void blockAddressIsAvailable() throws UnknownHostException { ChannelManagerImpl channelManagerImpl = new ChannelManagerImpl(new TestSystemProperties(), null);; Assert.assertTrue(channelManagerImpl.isAddressBlockAvailable(InetAddress.getLocalHost())); } |
ChannelManagerImpl implements ChannelManager { @Nonnull public Set<NodeID> broadcastBlock(@Nonnull final Block block) { final Set<NodeID> nodesIdsBroadcastedTo = new HashSet<>(); final BlockIdentifier bi = new BlockIdentifier(block.getHash().getBytes(), block.getNumber()); final Message newBlock = new BlockMessage(block); final Message newBlockHashes = new NewBlockHashesMessage(Arrays.asList(bi)); synchronized (activePeersLock) { activePeers.values().forEach(c -> logger.trace("RSK activePeers: {}", c)); List<Channel> peers = new ArrayList<>(activePeers.values()); Collections.shuffle(peers); int sqrt = (int) Math.floor(Math.sqrt(peers.size())); for (int i = 0; i < sqrt; i++) { Channel peer = peers.get(i); nodesIdsBroadcastedTo.add(peer.getNodeId()); logger.trace("RSK propagate: {}", peer); peer.sendMessage(newBlock); } for (int i = sqrt; i < peers.size(); i++) { Channel peer = peers.get(i); logger.trace("RSK announce: {}", peer); peer.sendMessage(newBlockHashes); } } return nodesIdsBroadcastedTo; } ChannelManagerImpl(RskSystemProperties config, SyncPool syncPool); @Override void start(); @Override void stop(); @VisibleForTesting void tryProcessNewPeers(); boolean isRecentlyDisconnected(InetAddress peerAddress); @Nonnull Set<NodeID> broadcastBlock(@Nonnull final Block block); @Nonnull Set<NodeID> broadcastBlockHash(@Nonnull final List<BlockIdentifier> identifiers, final Set<NodeID> targets); @Override int broadcastStatus(Status status); void add(Channel peer); void notifyDisconnect(Channel channel); Collection<Peer> getActivePeers(); boolean isAddressBlockAvailable(InetAddress inetAddress); @Nonnull Set<NodeID> broadcastTransaction(@Nonnull final Transaction transaction, @Nonnull final Set<NodeID> skip); @Override Set<NodeID> broadcastTransactions(@Nonnull final List<Transaction> transactions, @Nonnull final Set<NodeID> skip); @VisibleForTesting void setActivePeers(Map<NodeID, Channel> newActivePeers); } | @Test public void broadcastBlock() { ChannelManager target = new ChannelManagerImpl(mock(RskSystemProperties.class), mock(SyncPool.class)); Block block = mock(Block.class); when(block.getHash()).thenReturn(new Keccak256(new byte[32])); Set<NodeID> nodeIds = target.broadcastBlock(block); assertTrue(nodeIds.isEmpty()); } |
DataSourceWithCache implements KeyValueDataSource { @Override public byte[] put(byte[] key, byte[] value) { ByteArrayWrapper wrappedKey = ByteUtil.wrap(key); return put(wrappedKey, value); } DataSourceWithCache(KeyValueDataSource base, int cacheSize); @Override byte[] get(byte[] key); @Override byte[] put(byte[] key, 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(); } | @Test public void put() { byte[] randomKey = TestUtils.randomBytes(20); byte[] randomValue = TestUtils.randomBytes(20); dataSourceWithCache.put(randomKey, randomValue); assertThat(baseDataSource.get(randomKey), is(nullValue())); dataSourceWithCache.flush(); assertThat(baseDataSource.get(randomKey), is(randomValue)); } |
DataSourceWithCache implements KeyValueDataSource { @Override public Set<byte[]> keys() { Stream<ByteArrayWrapper> baseKeys; Stream<ByteArrayWrapper> committedKeys; Stream<ByteArrayWrapper> uncommittedKeys; Set<ByteArrayWrapper> uncommittedKeysToRemove; this.lock.readLock().lock(); try { baseKeys = base.keys().stream().map(ByteArrayWrapper::new); committedKeys = committedCache.entrySet().stream() .filter(e -> e.getValue() != null) .map(Map.Entry::getKey); uncommittedKeys = uncommittedCache.entrySet().stream() .filter(e -> e.getValue() != null) .map(Map.Entry::getKey); uncommittedKeysToRemove = uncommittedCache.entrySet().stream() .filter(e -> e.getValue() == null) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } finally { this.lock.readLock().unlock(); } Set<ByteArrayWrapper> knownKeys = Stream.concat(Stream.concat(baseKeys, committedKeys), uncommittedKeys) .collect(Collectors.toSet()); knownKeys.removeAll(uncommittedKeysToRemove); return knownKeys.stream() .map(ByteArrayWrapper::getData) .collect(Collectors.toSet()); } DataSourceWithCache(KeyValueDataSource base, int cacheSize); @Override byte[] get(byte[] key); @Override byte[] put(byte[] key, byte[] value); @Override void delete(byte[] key); @Override Set<byte[]> keys(); @Override void updateBatch(Map<ByteArrayWrapper, byte[]> rows, Set<ByteArrayWrapper> keysToRemove); @Override void flush(); String getName(); void init(); boolean isAlive(); void close(); } | @Test public void keys() { Map<ByteArrayWrapper, byte[]> initialEntries = generateRandomValuesToUpdate(CACHE_SIZE); Set<byte[]> initialKeys = initialEntries.keySet().stream().map(ByteArrayWrapper::getData).collect(Collectors.toSet()); baseDataSource.updateBatch(initialEntries, Collections.emptySet()); assertThat(dataSourceWithCache.keys(), is(initialKeys)); byte[] randomKey = TestUtils.randomBytes(20); dataSourceWithCache.get(randomKey); assertThat(dataSourceWithCache.keys(), not(hasItem(randomKey))); } |
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(); } | @Test public void delete() { byte[] randomKey = TestUtils.randomBytes(20); baseDataSource.put(randomKey, TestUtils.randomBytes(20)); dataSourceWithCache.delete(randomKey); dataSourceWithCache.flush(); assertThat(baseDataSource.get(randomKey), is(nullValue())); } |
DataSourceWithCache implements KeyValueDataSource { @Override public void updateBatch(Map<ByteArrayWrapper, byte[]> rows, Set<ByteArrayWrapper> keysToRemove) { if (rows.containsKey(null) || rows.containsValue(null)) { throw new IllegalArgumentException("Cannot update null values"); } rows.keySet().removeAll(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(); } | @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())); } } |
TransactionReceipt { public byte[] getStatus() { return this.status; } TransactionReceipt(); TransactionReceipt(byte[] rlp); TransactionReceipt(byte[] postTxState, byte[] cumulativeGas, byte[] gasUsed,
Bloom bloomFilter, List<LogInfo> logInfoList, byte[] status); byte[] getPostTxState(); byte[] getCumulativeGas(); byte[] getGasUsed(); long getCumulativeGasLong(); Bloom getBloomFilter(); List<LogInfo> getLogInfoList(); byte[] getEncoded(); void setStatus(byte[] status); boolean isSuccessful(); void setTxStatus(boolean success); boolean hasTxStatus(); boolean isTxStatusOK(); void setPostTxState(byte[] postTxState); void setCumulativeGas(long cumulativeGas); void setGasUsed(long gasUsed); void setCumulativeGas(byte[] cumulativeGas); void setGasUsed(byte[] gasUsed); void setLogInfoList(List<LogInfo> logInfoList); void setTransaction(Transaction transaction); Transaction getTransaction(); @Override String toString(); byte[] getStatus(); } | @Test public void test_2() { assertTrue(TypeConverter.toJsonHex(EMPTY_BYTE_ARRAY).equals("0x00")); byte[] rlpSuccess = Hex.decode("f9010c808255aeb9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c08255ae01"); byte[] rlpFailed = Hex.decode("f9010c808255aeb9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c08255ae80"); TransactionReceipt txReceipt = new TransactionReceipt(rlpSuccess); assertTrue(Arrays.equals(txReceipt.getStatus(), new byte[]{0x01})); txReceipt = new TransactionReceipt(rlpFailed); assertTrue(Arrays.equals(txReceipt.getStatus(), EMPTY_BYTE_ARRAY)); } |
TransactionExecutor { public boolean executeTransaction() { if (!this.init()) { return false; } this.execute(); this.go(); this.finalization(); return true; } TransactionExecutor(
Constants constants, ActivationConfig activationConfig, Transaction tx, int txindex, RskAddress coinbase,
Repository track, BlockStore blockStore, ReceiptStore receiptStore, BlockFactory blockFactory,
ProgramInvokeFactory programInvokeFactory, Block executionBlock, long gasUsedInTheBlock, VmConfig vmConfig,
boolean playVm, boolean remascEnabled, PrecompiledContracts precompiledContracts, Set<DataWord> deletedAccounts,
SignatureCache signatureCache); boolean executeTransaction(); TransactionReceipt getReceipt(); void extractTrace(ProgramTraceProcessor programTraceProcessor); TransactionExecutor setLocalCall(boolean localCall); List<LogInfo> getVMLogs(); ProgramResult getResult(); long getGasUsed(); Coin getPaidFees(); } | @Test public void testInitHandlesFreeTransactionsOK() { BlockTxSignatureCache blockTxSignatureCache = mock(BlockTxSignatureCache.class); Transaction transaction = mock(Transaction.class); TransactionExecutor txExecutor = new TransactionExecutor( constants, activationConfig, transaction, txIndex, rskAddress, repository, blockStore, receiptStore, blockFactory, programInvokeFactory, executionBlock, gasUsedInTheBlock, vmConfig, true, true, precompiledContracts, deletedAccounts, blockTxSignatureCache ); when(transaction.getGasLimit()).thenReturn(BigInteger.valueOf(4000000).toByteArray()); when(executionBlock.getGasLimit()).thenReturn(BigInteger.valueOf(6800000).toByteArray()); when(repository.getNonce(transaction.getSender())).thenReturn(BigInteger.valueOf(1L)); when(transaction.getNonce()).thenReturn(BigInteger.valueOf(1L).toByteArray()); RskAddress receiver = new RskAddress("0000000000000000000000000000000000000001"); when(transaction.getReceiveAddress()).thenReturn(receiver); when(transaction.acceptTransactionSignature(constants.getChainId())).thenReturn(true); when(repository.getBalance(transaction.getSender())).thenReturn(new Coin(BigInteger.valueOf(0L))); when(transaction.getValue()).thenReturn(new Coin(BigInteger.valueOf(68000))); assertEquals(0, transaction.transactionCost(constants, activationConfig.forBlock(executionBlock.getNumber()))); assertFalse(txExecutor.executeTransaction()); }
@Test public void InvalidTxsIsInBlockAndShouldntBeInCache(){ ReceivedTxSignatureCache receivedTxSignatureCache = mock(ReceivedTxSignatureCache.class); BlockTxSignatureCache blockTxSignatureCache = new BlockTxSignatureCache(receivedTxSignatureCache); MutableRepository cacheTrack = mock(MutableRepository.class); when(repository.startTracking()).thenReturn(cacheTrack); RskAddress sender = new RskAddress("0000000000000000000000000000000000000001"); RskAddress receiver = new RskAddress("0000000000000000000000000000000000000002"); byte[] gasLimit = BigInteger.valueOf(4000000).toByteArray(); byte[] txNonce = BigInteger.valueOf(1L).toByteArray(); Coin gasPrice = Coin.valueOf(1); Coin value = new Coin(BigInteger.valueOf(2)); Transaction transaction = getTransaction(sender, receiver, gasLimit, txNonce, gasPrice, value); when(executionBlock.getGasLimit()).thenReturn(BigInteger.valueOf(6800000).toByteArray()); when(repository.getNonce(sender)).thenReturn(BigInteger.valueOf(1L)); when(repository.getBalance(sender)).thenReturn(new Coin(BigInteger.valueOf(0L))); TransactionExecutor txExecutor = new TransactionExecutor( constants, activationConfig, transaction, txIndex, rskAddress, repository, blockStore, receiptStore, blockFactory, programInvokeFactory, executionBlock, gasUsedInTheBlock, vmConfig, true, true, precompiledContracts, deletedAccounts, blockTxSignatureCache ); assertEquals(0, transaction.transactionCost(constants, activationConfig.forBlock(executionBlock.getNumber()))); assertFalse(txExecutor.executeTransaction()); assertFalse(blockTxSignatureCache.containsTx(transaction)); }
@Test public void remascTxIsReceivedAndShouldntBeInCache(){ ReceivedTxSignatureCache receivedTxSignatureCache = mock(ReceivedTxSignatureCache.class); BlockTxSignatureCache blockTxSignatureCache = new BlockTxSignatureCache(receivedTxSignatureCache); MutableRepository cacheTrack = mock(MutableRepository.class); when(repository.startTracking()).thenReturn(cacheTrack); RskAddress sender = PrecompiledContracts.REMASC_ADDR; RskAddress receiver = new RskAddress("0000000000000000000000000000000000000002"); byte[] gasLimit = BigInteger.valueOf(4000000).toByteArray(); byte[] txNonce = BigInteger.valueOf(1L).toByteArray(); Coin gasPrice = Coin.valueOf(1); Coin value = new Coin(BigInteger.valueOf(2)); Transaction transaction = getTransaction(sender, receiver, gasLimit, txNonce, gasPrice, value); when(executionBlock.getGasLimit()).thenReturn(BigInteger.valueOf(6800000).toByteArray()); when(repository.getNonce(sender)).thenReturn(BigInteger.valueOf(1L)); when(repository.getBalance(sender)).thenReturn(new Coin(BigInteger.valueOf(0L))); TransactionExecutor txExecutor = new TransactionExecutor( constants, activationConfig, transaction, txIndex, rskAddress, repository, blockStore, receiptStore, blockFactory, programInvokeFactory, executionBlock, gasUsedInTheBlock, vmConfig, true, true, precompiledContracts, deletedAccounts, blockTxSignatureCache ); assertEquals(0, transaction.transactionCost(constants, activationConfig.forBlock(executionBlock.getNumber()))); assertFalse(txExecutor.executeTransaction()); assertFalse(blockTxSignatureCache.containsTx(transaction)); } |
BlockHeaderBuilder { public BlockHeader build() { initializeWithDefaultValues(); if (createConsensusCompliantHeader) { useRskip92Encoding = activationConfig.isActive(ConsensusRule.RSKIP92, number); includeForkDetectionData = activationConfig.isActive(ConsensusRule.RSKIP110, number) && mergedMiningForkDetectionData.length > 0; } if (createUmmCompliantHeader) { if (activationConfig.isActive(ConsensusRule.RSKIPUMM, number)) { if (ummRoot == null) { ummRoot = new byte[0]; } } } return new BlockHeader( parentHash, unclesHash, coinbase, stateRoot, txTrieRoot, receiptTrieRoot, logsBloom, difficulty, number, gasLimit, gasUsed, timestamp, extraData, paidFees, bitcoinMergedMiningHeader, bitcoinMergedMiningMerkleProof, bitcoinMergedMiningCoinbaseTransaction, mergedMiningForkDetectionData, minimumGasPrice, uncleCount, false, useRskip92Encoding, includeForkDetectionData, ummRoot ); } BlockHeaderBuilder(ActivationConfig activationConfig); BlockHeaderBuilder setCreateConsensusCompliantHeader(boolean createConsensusCompliantHeader); BlockHeaderBuilder setCreateUmmCompliantHeader(boolean createUmmCompliantHeader); BlockHeaderBuilder setStateRoot(byte[] stateRoot); BlockHeaderBuilder setDifficulty(BlockDifficulty difficulty); BlockHeaderBuilder setPaidFees(Coin paidFees); BlockHeaderBuilder setGasUsed(long gasUsed); BlockHeaderBuilder setLogsBloom(byte[] logsBloom); BlockHeaderBuilder setBitcoinMergedMiningHeader(byte[] bitcoinMergedMiningHeader); BlockHeaderBuilder setBitcoinMergedMiningMerkleProof(byte[] bitcoinMergedMiningMerkleProof); BlockHeaderBuilder setBitcoinMergedMiningCoinbaseTransaction(byte[] bitcoinMergedMiningCoinbaseTransaction); BlockHeaderBuilder setTxTrieRoot(byte[] txTrieRoot); BlockHeaderBuilder setEmptyTxTrieRoot(); BlockHeaderBuilder setReceiptTrieRoot(byte[] receiptTrieRoot); BlockHeaderBuilder setTimestamp(long timestamp); BlockHeaderBuilder setNumber(long number); BlockHeaderBuilder setGasLimit(byte[] gasLimit); BlockHeaderBuilder setExtraData(byte[] extraData); BlockHeaderBuilder setMergedMiningForkDetectionData(byte[] mergedMiningForkDetectionData); BlockHeaderBuilder setMinimumGasPrice(Coin minimumGasPrice); BlockHeaderBuilder setUncleCount(int uncleCount); BlockHeaderBuilder setUseRskip92Encoding(boolean useRskip92Encoding); BlockHeaderBuilder setIncludeForkDetectionData(boolean includeForkDetectionData); BlockHeaderBuilder setParentHashFromKeccak256(Keccak256 parentHash); BlockHeaderBuilder setParentHash(byte[] parentHash); BlockHeaderBuilder setEmptyUnclesHash(); BlockHeaderBuilder setUnclesHash(byte[] unclesHash); BlockHeaderBuilder setCoinbase(RskAddress coinbase); BlockHeaderBuilder setDifficultyFromBytes(@Nullable byte[] data); BlockHeaderBuilder setEmptyMergedMiningForkDetectionData(); BlockHeaderBuilder setEmptyExtraData(); BlockHeaderBuilder setEmptyLogsBloom(); BlockHeaderBuilder setEmptyStateRoot(); BlockHeaderBuilder setEmptyReceiptTrieRoot(); BlockHeaderBuilder setUmmRoot(byte[] ummRoot); BlockHeader build(); } | @Test public void createsHeaderWithEmptyStateRoot() { BlockHeader header = blockHeaderBuilder.build(); assertArrayEquals(HashUtil.EMPTY_TRIE_HASH, header.getStateRoot()); }
@Test public void createsHeaderWithEmptyTxTrieRoot() { BlockHeader header = blockHeaderBuilder.build(); assertArrayEquals(HashUtil.EMPTY_TRIE_HASH, header.getTxTrieRoot()); }
@Test public void createsHeaderWithEmptyReceiptTrieRoot() { BlockHeader header = blockHeaderBuilder.build(); assertArrayEquals(HashUtil.EMPTY_TRIE_HASH, header.getReceiptsRoot()); }
@Test public void createsHeaderWithEmptyLogsBloom() { BlockHeader header = blockHeaderBuilder.build(); assertArrayEquals(new Bloom().getData(), header.getLogsBloom()); }
@Test public void createsHeaderWithEmptyPaidFees() { BlockHeader header = blockHeaderBuilder.build(); assertEquals(Coin.valueOf(0), header.getPaidFees()); }
@Test public void createsHeaderWithEmptyMinimumGasPrice() { BlockHeader header = blockHeaderBuilder.build(); assertEquals(Coin.valueOf(0), header.getMinimumGasPrice()); }
@Test public void createsHeaderWithEmptyMergedMiningFields() { BlockHeader header = blockHeaderBuilder.build(); assertTrue(Arrays.equals(new byte[0], header.getBitcoinMergedMiningMerkleProof())); assertTrue(Arrays.equals(new byte[0], header.getBitcoinMergedMiningHeader())); assertTrue(Arrays.equals(new byte[0], header.getBitcoinMergedMiningCoinbaseTransaction())); assertTrue(Arrays.equals(new byte[0], header.getExtraData())); }
@Test public void createsHeaderWithEmptyUmmRootAndRskipUmmOn() { BlockHeader header = blockHeaderBuilder.build(); assertArrayEquals(new byte[0], header.getUmmRoot()); }
@Test public void createsHeaderWithEmptyUmmRootAndRskipUmmOff() { BlockHeaderBuilder builder = new BlockHeaderBuilder(ActivationConfigsForTest.allBut(ConsensusRule.RSKIPUMM)); BlockHeader header = builder.build(); assertNull(header.getUmmRoot()); } |
Web3Impl implements Web3 { @Override public boolean eth_mining() { Boolean s = null; try { return s = minerClient.isMining(); } finally { if (logger.isDebugEnabled()) { logger.debug("eth_mining(): {}", s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void eth_mining() { Ethereum ethMock = Web3Mocks.getMockEthereum(); Blockchain blockchain = Web3Mocks.getMockBlockchain(); BlockStore blockStore = Web3Mocks.getMockBlockStore(); RskSystemProperties mockProperties = Web3Mocks.getMockProperties(); MinerClient minerClient = new SimpleMinerClient(); PersonalModule personalModule = new PersonalModuleWalletDisabled(); TxPoolModule txPoolModule = new TxPoolModuleImpl(Web3Mocks.getMockTransactionPool()); DebugModule debugModule = new DebugModuleImpl(null, null, Web3Mocks.getMockMessageHandler(), null); Web3 web3 = new Web3Impl( ethMock, blockchain, blockStore, null, mockProperties, minerClient, null, personalModule, null, null, txPoolModule, null, debugModule, null, null, Web3Mocks.getMockChannelManager(), null, null, null, null, null, null, null, mock(Web3InformationRetriever.class)); assertTrue("Node is not mining", !web3.eth_mining()); try { minerClient.start(); assertTrue("Node is mining", web3.eth_mining()); } finally { minerClient.stop(); } assertTrue("Node is not mining", !web3.eth_mining()); } |
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); } | @Test public void getEmptyTransactionList() { TransactionSet txset = new TransactionSet(); List<Transaction> result = txset.getTransactions(); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } |
TransactionSet { public boolean hasTransaction(Transaction transaction) { return this.transactionsByHash.containsKey(transaction.getHash()); } TransactionSet(); TransactionSet(TransactionSet transactionSet); TransactionSet(Map<Keccak256, Transaction> transactionsByHash, Map<RskAddress, List<Transaction>> transactionsByAddress); void addTransaction(Transaction transaction); boolean hasTransaction(Transaction transaction); void removeTransactionByHash(Keccak256 hash); List<Transaction> getTransactions(); List<Transaction> getTransactionsWithSender(RskAddress senderAddress); } | @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)); } |
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); } | @Test public void getEmptyTransactionListByUnknownSender() { TransactionSet txset = new TransactionSet(); List<Transaction> result = txset.getTransactionsWithSender(new RskAddress(new byte[20])); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } |
Web3Impl implements Web3 { @Override public String eth_gasPrice() { String gasPrice = null; try { gasPrice = TypeConverter.toQuantityJsonHex(eth.getGasPrice().asBigInteger().longValue()); return gasPrice; } finally { if (logger.isDebugEnabled()) { logger.debug("eth_gasPrice(): {}", gasPrice); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getGasPrice() { Web3Impl web3 = createWeb3(); web3.eth = new SimpleEthereum(); String expectedValue = ByteUtil.toHexString(new BigInteger("20000000000").toByteArray()); expectedValue = "0x" + (expectedValue.startsWith("0") ? expectedValue.substring(1) : expectedValue); org.junit.Assert.assertEquals(expectedValue, web3.eth_gasPrice()); } |
Transaction { public byte[] getEncoded() { if (this.rlpEncoding == null) { byte[] v; byte[] r; byte[] s; if (this.signature != null) { v = RLP.encodeByte((byte) (chainId == 0 ? signature.getV() : (signature.getV() - LOWER_REAL_V) + (chainId * 2 + CHAIN_ID_INC))); r = RLP.encodeElement(BigIntegers.asUnsignedByteArray(signature.getR())); s = RLP.encodeElement(BigIntegers.asUnsignedByteArray(signature.getS())); } else { v = chainId == 0 ? RLP.encodeElement(EMPTY_BYTE_ARRAY) : RLP.encodeByte(chainId); r = RLP.encodeElement(EMPTY_BYTE_ARRAY); s = RLP.encodeElement(EMPTY_BYTE_ARRAY); } this.rlpEncoding = encode(v, r, s); } return ByteUtil.cloneBytes(this.rlpEncoding); } protected Transaction(byte[] rawData); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data, byte[] r, byte[] s, byte v); Transaction(long nonce, long gasPrice, long gas, String to, long value, byte[] data, byte chainId); Transaction(BigInteger nonce, BigInteger gasPrice, BigInteger gas, String to, BigInteger value, byte[] data,
byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String data, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, byte[] decodedData, byte chainId); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] valueRaw, byte[] data,
byte chainId); Transaction toImmutableTransaction(); long transactionCost(Constants constants, ActivationConfig.ForBlock activations); void verify(); Keccak256 getHash(); Keccak256 getRawHash(); byte[] getNonce(); Coin getValue(); RskAddress getReceiveAddress(); Coin getGasPrice(); byte[] getGasLimit(); byte[] getData(); ECDSASignature getSignature(); boolean acceptTransactionSignature(byte currentChainId); void sign(byte[] privKeyBytes); void setSignature(ECDSASignature signature); void setSignature(ECKey.ECDSASignature signature); @Nullable RskAddress getContractAddress(); boolean isContractCreation(); ECKey getKey(); synchronized RskAddress getSender(); synchronized RskAddress getSender(SignatureCache signatureCache); byte getChainId(); @Override String toString(); byte[] getEncodedRaw(); byte[] getEncoded(); BigInteger getGasLimitAsInteger(); BigInteger getNonceAsInteger(); @Override int hashCode(); @Override boolean equals(Object obj); boolean isLocalCallTransaction(); void setLocalCallTransaction(boolean isLocalCall); boolean isRemascTransaction(int txPosition, int txsSize); static final int DATAWORD_LENGTH; } | @Ignore @Test public void encodeReceiptTest() { String data = "f90244a0f5ff3fbd159773816a7c707a9b8cb6bb778b934a8f6466c7830ed970498f4b688301e848b902000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000dbda94cd2a3d9f938e13cd947ec05abc7fe734df8dd826c083a1a1a1"; byte[] stateRoot = Hex.decode("f5ff3fbd159773816a7c707a9b8cb6bb778b934a8f6466c7830ed970498f4b68"); byte[] gasUsed = Hex.decode("01E848"); Bloom bloom = new Bloom(Hex.decode("0000000000000000800000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")); LogInfo logInfo1 = new LogInfo( Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826"), null, Hex.decode("a1a1a1") ); List<LogInfo> logs = new ArrayList<>(); logs.add(logInfo1); TransactionReceipt receipt = new TransactionReceipt(stateRoot, gasUsed, gasUsed, bloom, logs, TransactionReceipt.SUCCESS_STATUS); assertEquals(data, ByteUtil.toHexString(receipt.getEncoded())); } |
Transaction { public void verify() { validate(); } protected Transaction(byte[] rawData); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data, byte[] r, byte[] s, byte v); Transaction(long nonce, long gasPrice, long gas, String to, long value, byte[] data, byte chainId); Transaction(BigInteger nonce, BigInteger gasPrice, BigInteger gas, String to, BigInteger value, byte[] data,
byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String data, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, byte[] decodedData, byte chainId); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] valueRaw, byte[] data,
byte chainId); Transaction toImmutableTransaction(); long transactionCost(Constants constants, ActivationConfig.ForBlock activations); void verify(); Keccak256 getHash(); Keccak256 getRawHash(); byte[] getNonce(); Coin getValue(); RskAddress getReceiveAddress(); Coin getGasPrice(); byte[] getGasLimit(); byte[] getData(); ECDSASignature getSignature(); boolean acceptTransactionSignature(byte currentChainId); void sign(byte[] privKeyBytes); void setSignature(ECDSASignature signature); void setSignature(ECKey.ECDSASignature signature); @Nullable RskAddress getContractAddress(); boolean isContractCreation(); ECKey getKey(); synchronized RskAddress getSender(); synchronized RskAddress getSender(SignatureCache signatureCache); byte getChainId(); @Override String toString(); byte[] getEncodedRaw(); byte[] getEncoded(); BigInteger getGasLimitAsInteger(); BigInteger getNonceAsInteger(); @Override int hashCode(); @Override boolean equals(Object obj); boolean isLocalCallTransaction(); void setLocalCallTransaction(boolean isLocalCall); boolean isRemascTransaction(int txPosition, int txsSize); static final int DATAWORD_LENGTH; } | @Test public void verifyTx_noSignature() { BigInteger value = new BigInteger("1000000000000000000000"); byte[] privKey = HashUtil.keccak256("cat".getBytes()); ECKey ecKey = ECKey.fromPrivate(privKey); byte[] gasPrice = Hex.decode("09184e72a000"); byte[] gas = Hex.decode("4255"); Transaction tx = new Transaction(new byte[0], gasPrice, gas, ecKey.getAddress(), value.toByteArray(),null); try { tx.verify(); } catch (Exception e) { fail(e.getMessage()); } } |
Transaction { @Override public String toString() { return "TransactionData [" + "hash=" + ByteUtil.toHexStringOrEmpty(getHash().getBytes()) + " nonce=" + ByteUtil.toHexStringOrEmpty(nonce) + ", gasPrice=" + gasPrice + ", gas=" + ByteUtil.toHexStringOrEmpty(gasLimit) + ", receiveAddress=" + receiveAddress + ", value=" + value + ", data=" + ByteUtil.toHexStringOrEmpty(data) + ", signatureV=" + (signature == null ? "" : signature.getV()) + ", signatureR=" + (signature == null ? "" : ByteUtil.toHexStringOrEmpty(BigIntegers.asUnsignedByteArray(signature.getR()))) + ", signatureS=" + (signature == null ? "" : ByteUtil.toHexStringOrEmpty(BigIntegers.asUnsignedByteArray(signature.getS()))) + "]"; } protected Transaction(byte[] rawData); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] value, byte[] data, byte[] r, byte[] s, byte v); Transaction(long nonce, long gasPrice, long gas, String to, long value, byte[] data, byte chainId); Transaction(BigInteger nonce, BigInteger gasPrice, BigInteger gas, String to, BigInteger value, byte[] data,
byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String data, byte chainId); Transaction(String to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, byte[] decodedData, byte chainId); Transaction(byte[] nonce, byte[] gasPriceRaw, byte[] gasLimit, byte[] receiveAddress, byte[] valueRaw, byte[] data,
byte chainId); Transaction toImmutableTransaction(); long transactionCost(Constants constants, ActivationConfig.ForBlock activations); void verify(); Keccak256 getHash(); Keccak256 getRawHash(); byte[] getNonce(); Coin getValue(); RskAddress getReceiveAddress(); Coin getGasPrice(); byte[] getGasLimit(); byte[] getData(); ECDSASignature getSignature(); boolean acceptTransactionSignature(byte currentChainId); void sign(byte[] privKeyBytes); void setSignature(ECDSASignature signature); void setSignature(ECKey.ECDSASignature signature); @Nullable RskAddress getContractAddress(); boolean isContractCreation(); ECKey getKey(); synchronized RskAddress getSender(); synchronized RskAddress getSender(SignatureCache signatureCache); byte getChainId(); @Override String toString(); byte[] getEncodedRaw(); byte[] getEncoded(); BigInteger getGasLimitAsInteger(); BigInteger getNonceAsInteger(); @Override int hashCode(); @Override boolean equals(Object obj); boolean isLocalCallTransaction(); void setLocalCallTransaction(boolean isLocalCall); boolean isRemascTransaction(int txPosition, int txsSize); static final int DATAWORD_LENGTH; } | @Test public void toString_nullElements() { byte[] encodedNull = RLP.encodeElement(null); byte[] encodedEmptyArray = RLP.encodeElement(EMPTY_BYTE_ARRAY); byte[] rawData = RLP.encodeList(encodedNull, encodedNull, encodedNull, encodedNull, encodedNull, encodedNull, encodedEmptyArray, encodedEmptyArray, encodedEmptyArray); Transaction tx = new ImmutableTransaction(rawData); try { tx.toString(); } catch (Exception e) { fail(e.getMessage()); } } |
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(); } | @Test public void testGetEncoded() { String expected = "dc809a0100000000000000000000000000000000000000000000000000"; AccountState acct = new AccountState(BigInteger.ZERO, new Coin(BigInteger.valueOf(2).pow(200))); assertEquals(expected, ByteUtil.toHexString(acct.getEncoded())); } |
DifficultyRule extends DependentBlockHeaderRule { @Override public boolean validate(BlockHeader header, BlockHeader parent) { BlockDifficulty calcDifficulty = difficultyCalculator.calcDifficulty(header, parent); BlockDifficulty difficulty = header.getDifficulty(); if (!difficulty.equals(calcDifficulty)) { logger.error("#{}: difficulty != calcDifficulty", header.getNumber()); return false; } return true; } DifficultyRule(DifficultyCalculator difficultyCalculator); @Override boolean validate(BlockHeader header, BlockHeader parent); } | @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)); } |
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); } | @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)); } |
ParentGasLimitRule extends DependentBlockHeaderRule { @Override public boolean validate(BlockHeader header, BlockHeader parent) { BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit()); BigInteger parentGasLimit = new BigInteger(1, parent.getGasLimit()); BigInteger deltaLimit = parentGasLimit.divide(gasLimitBoundDivisor); if (headerGasLimit.compareTo(parentGasLimit.subtract(deltaLimit)) < 0 || headerGasLimit.compareTo(parentGasLimit.add(deltaLimit)) > 0) { logger.error(String.format("#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR", header.getNumber())); return false; } return true; } ParentGasLimitRule(int gasLimitBoundDivisor); @Override boolean validate(BlockHeader header, BlockHeader parent); } | @Test public void parentGasLimitLessThanGasLimit() { BlockHeader header = getHeader(10000); BlockHeader parent = getHeader(9999); assertTrue(rule.validate(header, parent)); }
@Test public void parentGasLimitTooLessThanGasLimit() { BlockHeader header = getHeader(100); BlockHeader parent = getHeader(9); assertFalse(rule.validate(header, parent)); }
@Test public void parentGasLimitGreaterThanGasLimit() { BlockHeader header = getHeader(10000); BlockHeader parent = getHeader(10001); assertTrue(rule.validate(header, parent)); }
@Test public void parentGasLimitTooGreaterThanGasLimit() { BlockHeader header = getHeader(9); BlockHeader parent = getHeader(100); assertFalse(rule.validate(header, parent)); }
@Test public void parentGasLimitOfBy1Tests() { BlockHeader parent = getHeader(2049); BlockHeader headerGGood = getHeader(2051); BlockHeader headerGBad = getHeader(2052); BlockHeader headerLGood = getHeader(2047); BlockHeader headerLBad = getHeader(2046); assertTrue(rule.validate(headerGGood, parent)); assertTrue(rule.validate(headerLGood, parent)); assertFalse(rule.validate(headerGBad, parent)); assertFalse(rule.validate(headerLBad, parent)); } |
Web3Impl implements Web3 { @Override public TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash) { logger.trace("eth_getTransactionReceipt({})", transactionHash); byte[] hash = stringHexToByteArray(transactionHash); TransactionInfo txInfo = receiptStore.getInMainChain(hash, blockStore); if (txInfo == null) { logger.trace("No transaction info for {}", transactionHash); return null; } Block block = blockStore.getBlockByHash(txInfo.getBlockHash()); Transaction tx = block.getTransactionsList().get(txInfo.getIndex()); txInfo.setTransaction(tx); return new TransactionReceiptDTO(block, txInfo); } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getUnknownTransactionReceipt() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); Web3Impl web3 = createWeb3(world, receiptStore); Account acc1 = new AccountBuilder().name("acc1").build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); String hashString = tx.getHash().toHexString(); Assert.assertNull(web3.eth_getTransactionReceipt(hashString)); Assert.assertNull(web3.rsk_getRawTransactionReceiptByHash(hashString)); }
@Test public void getTransactionReceipt() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); Web3Impl web3 = createWeb3(world, receiptStore); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).transactions(txs).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); String hashString = tx.getHash().toHexString(); TransactionReceiptDTO tr = web3.eth_getTransactionReceipt(hashString); assertNotNull(tr); org.junit.Assert.assertEquals("0x" + hashString, tr.getTransactionHash()); String trxFrom = TypeConverter.toJsonHex(tx.getSender().getBytes()); org.junit.Assert.assertEquals(trxFrom, tr.getFrom()); String trxTo = TypeConverter.toJsonHex(tx.getReceiveAddress().getBytes()); org.junit.Assert.assertEquals(trxTo, tr.getTo()); String blockHashString = "0x" + block1.getHash(); org.junit.Assert.assertEquals(blockHashString, tr.getBlockHash()); String blockNumberAsHex = "0x" + Long.toHexString(block1.getNumber()); org.junit.Assert.assertEquals(blockNumberAsHex, tr.getBlockNumber()); String rawTransactionReceipt = web3.rsk_getRawTransactionReceiptByHash(hashString); String expectedRawTxReceipt = "0xf9010c01825208b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c082520801"; Assert.assertEquals(expectedRawTxReceipt, rawTransactionReceipt); String[] transactionReceiptNodes = web3.rsk_getTransactionReceiptNodesByHash(blockHashString, hashString); ArrayList<String> expectedRawTxReceiptNodes = new ArrayList<>(); expectedRawTxReceiptNodes.add("0x70078048ee76b19fc451dba9dbee8b3e73084f79ea540d3940b3b36b128e8024e9302500010f"); Assert.assertEquals(1, transactionReceiptNodes.length); Assert.assertEquals(expectedRawTxReceiptNodes.get(0), transactionReceiptNodes[0]); }
@Test public void getTransactionReceiptNotInMainBlockchain() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); Web3Impl web3 = createWeb3(world, receiptStore); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).difficulty(3l).transactions(txs).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); Block block1b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis) .difficulty(block1.getDifficulty().asBigInteger().longValue()-1).build(); Block block2b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(2).parent(block1b).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(block1b)); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block2b)); String hashString = tx.getHash().toHexString(); TransactionReceiptDTO tr = web3.eth_getTransactionReceipt(hashString); Assert.assertNull(tr); } |
GasCost { public static long toGas(byte[] bytes) throws InvalidGasException { if (bytes.length > 8) { return Long.MAX_VALUE; } long result = ByteUtil.byteArrayToLong(bytes); if (result < 0) { throw new InvalidGasException(bytes); } return result; } private GasCost(); static long toGas(byte[] bytes); static long toGas(BigInteger big); static long toGas(long number); static long add(long x, long y); static long multiply(long x, long y); static long subtract(long x, long y); static long calculateTotal(long baseCost, long unitCost, long units); static final long STEP; static final long SSTORE; static final long ZEROSTEP; static final long QUICKSTEP; static final long FASTESTSTEP; static final long FASTSTEP; static final long MIDSTEP; static final long SLOWSTEP; static final long EXTSTEP; static final long GENESISGASLIMIT; static final long MINGASLIMIT; static final long BALANCE; static final long SHA3; static final long SHA3_WORD; static final long SLOAD; static final long STOP; static final long SUICIDE; static final long CLEAR_SSTORE; static final long SET_SSTORE; static final long RESET_SSTORE; static final long REFUND_SSTORE; static final long CREATE; static final long JUMPDEST; static final long CREATE_DATA_BYTE; static final long CALL; static final long STIPEND_CALL; static final long VT_CALL; static final long NEW_ACCT_CALL; static final long MEMORY; static final long MEMORY_V1; static final long SUICIDE_REFUND; static final long QUAD_COEFF_DIV; static final long CREATE_DATA; static final long REPLACE_DATA; static final long TX_NO_ZERO_DATA; static final long TX_ZERO_DATA; static final long TRANSACTION; static final long TRANSACTION_DEFAULT; static final long TRANSACTION_CREATE_CONTRACT; static final long LOG_GAS; static final long LOG_DATA_GAS; static final long LOG_TOPIC_GAS; static final long COPY_GAS; static final long EXP_GAS; static final long EXP_BYTE_GAS; static final long IDENTITY; static final long IDENTITY_WORD; static final long RIPEMD160; static final long RIPEMD160_WORD; static final long SHA256; static final long SHA256_WORD; static final long EC_RECOVER; static final long EXT_CODE_SIZE; static final long EXT_CODE_COPY; static final long EXT_CODE_HASH; static final long CODEREPLACE; static final long NEW_ACCT_SUICIDE; static final long RETURN; static final long MAX_GAS; } | @Test public void toGas() { Assert.assertEquals(0, GasCost.toGas(new byte[0])); Assert.assertEquals(1, GasCost.toGas(new byte[] { 0x01 })); Assert.assertEquals(255, GasCost.toGas(new byte[] { (byte)0xff })); Assert.assertEquals( Long.MAX_VALUE, GasCost.toGas(BigInteger.valueOf(Long.MAX_VALUE).toByteArray()) ); }
@Test public void toGasOverflowsSlightly() { byte[] bytes = new byte[32]; for (int k = 0; k < 17; k++) { bytes[k] = (byte)0x00; } bytes[17] = (byte)0x80; for (int k = 18; k < 32; k++) { bytes[k] = (byte)0x00; } Assert.assertEquals(GasCost.toGas(bytes), Long.MAX_VALUE); }
@Test(expected = GasCost.InvalidGasException.class) public void toGasGivesNegativeValue() throws GasCost.InvalidGasException { byte[] negativeBytes = new byte[]{ (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, }; GasCost.toGas(negativeBytes); }
@Test public void toGasArrayTooBig() throws GasCost.InvalidGasException { byte[] bigArray = new byte[]{ (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, (byte)255, }; Assert.assertEquals(GasCost.toGas(bigArray), Long.MAX_VALUE); }
@Test(expected = GasCost.InvalidGasException.class) public void toGasFromLongWithNegativeLong() { GasCost.toGas(-1L); }
@Test(expected = GasCost.InvalidGasException.class) public void toGasFromOverflowedLong() { Assert.assertEquals(Long.MAX_VALUE, GasCost.toGas(Long.MAX_VALUE + 1)); }
@Test public void toGasFromLong() { Assert.assertEquals(Long.MAX_VALUE, GasCost.toGas(Long.MAX_VALUE)); Assert.assertEquals(123L, GasCost.toGas(123L)); }
@Test public void toGasWithBigInteger() { BigInteger bi = BigInteger.valueOf(Long.MAX_VALUE - 10); Assert.assertEquals(Long.MAX_VALUE - 10, GasCost.toGas(bi)); }
@Test(expected = GasCost.InvalidGasException.class) public void toGasWithNegativeBigInteger() { BigInteger bi = BigInteger.valueOf(-1); GasCost.toGas(bi); }
@Test(expected = GasCost.InvalidGasException.class) public void moreNegativeBiToGas() { Assert.assertEquals(Long.MAX_VALUE, GasCost.toGas(BigInteger.valueOf(-3512))); }
@Test(expected = GasCost.InvalidGasException.class) public void mostNegativeBiToGas() { Assert.assertEquals(Long.MAX_VALUE, GasCost.toGas(BigInteger.valueOf(-99999999999999L))); } |
GasCost { public static long add(long x, long y) throws InvalidGasException { if (x < 0 || y < 0) { throw new InvalidGasException(String.format("%d + %d", x, y)); } long result = x + y; if (result < 0) { return Long.MAX_VALUE; } return result; } private GasCost(); static long toGas(byte[] bytes); static long toGas(BigInteger big); static long toGas(long number); static long add(long x, long y); static long multiply(long x, long y); static long subtract(long x, long y); static long calculateTotal(long baseCost, long unitCost, long units); static final long STEP; static final long SSTORE; static final long ZEROSTEP; static final long QUICKSTEP; static final long FASTESTSTEP; static final long FASTSTEP; static final long MIDSTEP; static final long SLOWSTEP; static final long EXTSTEP; static final long GENESISGASLIMIT; static final long MINGASLIMIT; static final long BALANCE; static final long SHA3; static final long SHA3_WORD; static final long SLOAD; static final long STOP; static final long SUICIDE; static final long CLEAR_SSTORE; static final long SET_SSTORE; static final long RESET_SSTORE; static final long REFUND_SSTORE; static final long CREATE; static final long JUMPDEST; static final long CREATE_DATA_BYTE; static final long CALL; static final long STIPEND_CALL; static final long VT_CALL; static final long NEW_ACCT_CALL; static final long MEMORY; static final long MEMORY_V1; static final long SUICIDE_REFUND; static final long QUAD_COEFF_DIV; static final long CREATE_DATA; static final long REPLACE_DATA; static final long TX_NO_ZERO_DATA; static final long TX_ZERO_DATA; static final long TRANSACTION; static final long TRANSACTION_DEFAULT; static final long TRANSACTION_CREATE_CONTRACT; static final long LOG_GAS; static final long LOG_DATA_GAS; static final long LOG_TOPIC_GAS; static final long COPY_GAS; static final long EXP_GAS; static final long EXP_BYTE_GAS; static final long IDENTITY; static final long IDENTITY_WORD; static final long RIPEMD160; static final long RIPEMD160_WORD; static final long SHA256; static final long SHA256_WORD; static final long EC_RECOVER; static final long EXT_CODE_SIZE; static final long EXT_CODE_COPY; static final long EXT_CODE_HASH; static final long CODEREPLACE; static final long NEW_ACCT_SUICIDE; static final long RETURN; static final long MAX_GAS; } | @Test public void calculateAddGas() { Assert.assertEquals(1, GasCost.add(1, 0)); Assert.assertEquals(2, GasCost.add(1, 1)); Assert.assertEquals(1000000, GasCost.add(500000, 500000)); }
@Test public void calculateAddGasWithOverflow() { Assert.assertEquals(Long.MAX_VALUE, GasCost.add(Long.MAX_VALUE, 1)); Assert.assertEquals(Long.MAX_VALUE, GasCost.add(1, Long.MAX_VALUE)); Assert.assertEquals(Long.MAX_VALUE, GasCost.add(Long.MAX_VALUE, Long.MAX_VALUE)); }
@Test(expected = GasCost.InvalidGasException.class) public void calculateAddGasCostWithSecondNegativeInputAndResult() throws GasCost.InvalidGasException { GasCost.add(0, -1); }
@Test(expected = GasCost.InvalidGasException.class) public void calculateAddGasCostWithFirstNegativeInputAndResult() throws GasCost.InvalidGasException { GasCost.add(-1, 1); } |
GasCost { public static long subtract(long x, long y) throws InvalidGasException { if (y < 0 || y > x) { throw new InvalidGasException(String.format("%d - %d", x, y)); } return x - y; } private GasCost(); static long toGas(byte[] bytes); static long toGas(BigInteger big); static long toGas(long number); static long add(long x, long y); static long multiply(long x, long y); static long subtract(long x, long y); static long calculateTotal(long baseCost, long unitCost, long units); static final long STEP; static final long SSTORE; static final long ZEROSTEP; static final long QUICKSTEP; static final long FASTESTSTEP; static final long FASTSTEP; static final long MIDSTEP; static final long SLOWSTEP; static final long EXTSTEP; static final long GENESISGASLIMIT; static final long MINGASLIMIT; static final long BALANCE; static final long SHA3; static final long SHA3_WORD; static final long SLOAD; static final long STOP; static final long SUICIDE; static final long CLEAR_SSTORE; static final long SET_SSTORE; static final long RESET_SSTORE; static final long REFUND_SSTORE; static final long CREATE; static final long JUMPDEST; static final long CREATE_DATA_BYTE; static final long CALL; static final long STIPEND_CALL; static final long VT_CALL; static final long NEW_ACCT_CALL; static final long MEMORY; static final long MEMORY_V1; static final long SUICIDE_REFUND; static final long QUAD_COEFF_DIV; static final long CREATE_DATA; static final long REPLACE_DATA; static final long TX_NO_ZERO_DATA; static final long TX_ZERO_DATA; static final long TRANSACTION; static final long TRANSACTION_DEFAULT; static final long TRANSACTION_CREATE_CONTRACT; static final long LOG_GAS; static final long LOG_DATA_GAS; static final long LOG_TOPIC_GAS; static final long COPY_GAS; static final long EXP_GAS; static final long EXP_BYTE_GAS; static final long IDENTITY; static final long IDENTITY_WORD; static final long RIPEMD160; static final long RIPEMD160_WORD; static final long SHA256; static final long SHA256_WORD; static final long EC_RECOVER; static final long EXT_CODE_SIZE; static final long EXT_CODE_COPY; static final long EXT_CODE_HASH; static final long CODEREPLACE; static final long NEW_ACCT_SUICIDE; static final long RETURN; static final long MAX_GAS; } | @Test public void calculateSubtractGasCost() { Assert.assertEquals(1, GasCost.subtract(1, 0)); Assert.assertEquals(0, GasCost.subtract(1, 1)); Assert.assertEquals(1000000, GasCost.subtract(1500000, 500000)); Assert.assertEquals(0, GasCost.subtract(Long.MAX_VALUE, Long.MAX_VALUE)); }
@Test(expected = GasCost.InvalidGasException.class) public void calculateSubtractWithNegativeInput() throws GasCost.InvalidGasException { GasCost.subtract(1, -1); }
@Test(expected = GasCost.InvalidGasException.class) public void calculateSubtractWithExtremelyNegativeResult() throws GasCost.InvalidGasException { GasCost.subtract(0, Long.MAX_VALUE); }
@Test(expected = GasCost.InvalidGasException.class) public void calculateSubtractGasToInvalidSubtle() throws GasCost.InvalidGasException { GasCost.subtract(1, 2); }
@Test(expected = GasCost.InvalidGasException.class) public void calculateSubtractGasToInvalidObvious() throws GasCost.InvalidGasException { GasCost.subtract(1, 159); } |
GasCost { public static long multiply(long x, long y) throws InvalidGasException { if (x < 0 || y < 0) { throw new InvalidGasException(String.format("%d * %d", x, y)); } long result = x * y; if (multiplicationOverflowed(x, y, result)) { return Long.MAX_VALUE; } return result; } private GasCost(); static long toGas(byte[] bytes); static long toGas(BigInteger big); static long toGas(long number); static long add(long x, long y); static long multiply(long x, long y); static long subtract(long x, long y); static long calculateTotal(long baseCost, long unitCost, long units); static final long STEP; static final long SSTORE; static final long ZEROSTEP; static final long QUICKSTEP; static final long FASTESTSTEP; static final long FASTSTEP; static final long MIDSTEP; static final long SLOWSTEP; static final long EXTSTEP; static final long GENESISGASLIMIT; static final long MINGASLIMIT; static final long BALANCE; static final long SHA3; static final long SHA3_WORD; static final long SLOAD; static final long STOP; static final long SUICIDE; static final long CLEAR_SSTORE; static final long SET_SSTORE; static final long RESET_SSTORE; static final long REFUND_SSTORE; static final long CREATE; static final long JUMPDEST; static final long CREATE_DATA_BYTE; static final long CALL; static final long STIPEND_CALL; static final long VT_CALL; static final long NEW_ACCT_CALL; static final long MEMORY; static final long MEMORY_V1; static final long SUICIDE_REFUND; static final long QUAD_COEFF_DIV; static final long CREATE_DATA; static final long REPLACE_DATA; static final long TX_NO_ZERO_DATA; static final long TX_ZERO_DATA; static final long TRANSACTION; static final long TRANSACTION_DEFAULT; static final long TRANSACTION_CREATE_CONTRACT; static final long LOG_GAS; static final long LOG_DATA_GAS; static final long LOG_TOPIC_GAS; static final long COPY_GAS; static final long EXP_GAS; static final long EXP_BYTE_GAS; static final long IDENTITY; static final long IDENTITY_WORD; static final long RIPEMD160; static final long RIPEMD160_WORD; static final long SHA256; static final long SHA256_WORD; static final long EC_RECOVER; static final long EXT_CODE_SIZE; static final long EXT_CODE_COPY; static final long EXT_CODE_HASH; static final long CODEREPLACE; static final long NEW_ACCT_SUICIDE; static final long RETURN; static final long MAX_GAS; } | @Test(expected = GasCost.InvalidGasException.class) public void multiplyWithNegativeValues() throws GasCost.InvalidGasException { GasCost.multiply(-1, -2); }
@Test(expected = GasCost.InvalidGasException.class) public void multiplyWithXNegative() throws GasCost.InvalidGasException { GasCost.multiply(-1, 123); }
@Test(expected = GasCost.InvalidGasException.class) public void multiplyWithYNegative() throws GasCost.InvalidGasException { GasCost.multiply(1, -9123); }
@Test public void multiply() { long x = (long) Math.pow(2, 62); long y = (long) Math.pow(2, 12); long overflowed = GasCost.multiply(x, y); Assert.assertEquals("overflowed is coverted to max gas", Long.MAX_VALUE, overflowed); }
@Test public void multiplyOverflowing() throws GasCost.InvalidGasException { Assert.assertEquals(Long.MAX_VALUE, GasCost.multiply(4611686018427387903L, 4096L)); }
@Test(expected = GasCost.InvalidGasException.class) public void multiplyWithNegativeInput() throws GasCost.InvalidGasException { GasCost.multiply(1, -9123); } |
Web3Impl implements Web3 { @Override public TransactionResultDTO eth_getTransactionByHash(String transactionHash) { TransactionResultDTO s = null; try { Keccak256 txHash = new Keccak256(stringHexToByteArray(transactionHash)); Block block = null; TransactionInfo txInfo = this.receiptStore.getInMainChain(txHash.getBytes(), blockStore); if (txInfo == null) { List<Transaction> txs = web3InformationRetriever.getTransactions("pending"); for (Transaction tx : txs) { if (tx.getHash().equals(txHash)) { return s = new TransactionResultDTO(null, null, tx); } } } else { block = blockchain.getBlockByHash(txInfo.getBlockHash()); Block mainBlock = blockchain.getBlockByNumber(block.getNumber()); if (!block.getHash().equals(mainBlock.getHash())) { return null; } txInfo.setTransaction(block.getTransactionsList().get(txInfo.getIndex())); } if (txInfo == null) { return null; } return s = new TransactionResultDTO(block, txInfo.getIndex(), txInfo.getReceipt().getTransaction()); } finally { logger.debug("eth_getTransactionByHash({}): {}", transactionHash, s); } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getTransactionByHash() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); Web3Impl web3 = createWeb3(world, receiptStore); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).transactions(txs).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); String hashString = tx.getHash().toHexString(); TransactionResultDTO tr = web3.eth_getTransactionByHash(hashString); assertNotNull(tr); org.junit.Assert.assertEquals("0x" + hashString, tr.hash); String blockHashString = "0x" + block1.getHash(); org.junit.Assert.assertEquals(blockHashString, tr.blockHash); org.junit.Assert.assertEquals("0x", tr.input); org.junit.Assert.assertEquals("0x" + ByteUtil.toHexString(tx.getReceiveAddress().getBytes()), tr.to); Assert.assertArrayEquals(new byte[] {tx.getSignature().getV()}, TypeConverter.stringHexToByteArray(tr.v)); Assert.assertThat(TypeConverter.stringHexToBigInteger(tr.s), is(tx.getSignature().getS())); Assert.assertThat(TypeConverter.stringHexToBigInteger(tr.r), is(tx.getSignature().getR())); }
@Test public void getPendingTransactionByHash() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); BlockChainImpl blockChain = world.getBlockChain(); BlockStore blockStore = world.getBlockStore(); TransactionExecutorFactory transactionExecutorFactory = buildTransactionExecutorFactory(blockStore, world.getBlockTxSignatureCache()); TransactionPool transactionPool = new TransactionPoolImpl(config, world.getRepositoryLocator(), blockStore, blockFactory, null, transactionExecutorFactory, world.getReceivedTxSignatureCache(), 10, 100); transactionPool.processBest(blockChain.getBestBlock()); Web3Impl web3 = createWeb3(world, transactionPool, receiptStore); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); transactionPool.addTransaction(tx); String hashString = tx.getHash().toHexString(); TransactionResultDTO tr = web3.eth_getTransactionByHash(hashString); assertNotNull(tr); org.junit.Assert.assertEquals("0x" + hashString, tr.hash); org.junit.Assert.assertEquals("0", tr.nonce); org.junit.Assert.assertEquals(null, tr.blockHash); org.junit.Assert.assertEquals(null, tr.transactionIndex); org.junit.Assert.assertEquals("0x", tr.input); org.junit.Assert.assertEquals("0x" + ByteUtil.toHexString(tx.getReceiveAddress().getBytes()), tr.to); }
@Test public void getTransactionByHashNotInMainBlockchain() throws Exception { ReceiptStore receiptStore = new ReceiptStoreImpl(new HashMapDB()); World world = new World(receiptStore); Web3Impl web3 = createWeb3(world, receiptStore); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(10).parent(genesis).transactions(txs).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); Block block1b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(block1.getDifficulty().asBigInteger().longValue()-1).parent(genesis).build(); Block block2b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(block1.getDifficulty().asBigInteger().longValue()+1).parent(block1b).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(block1b)); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block2b)); String hashString = tx.getHash().toHexString(); TransactionResultDTO tr = web3.eth_getTransactionByHash(hashString); Assert.assertNull(tr); } |
GasCost { public static long calculateTotal(long baseCost, long unitCost, long units) throws InvalidGasException { if (baseCost < 0 || unitCost < 0 || units < 0) { throw new InvalidGasException(String.format("%d + %d * %d", baseCost, unitCost, units)); } long mult = unitCost * units; if (multiplicationOverflowed(unitCost, units, mult)) { return Long.MAX_VALUE; } long result = baseCost + mult; if (result < 0) { return Long.MAX_VALUE; } return result; } private GasCost(); static long toGas(byte[] bytes); static long toGas(BigInteger big); static long toGas(long number); static long add(long x, long y); static long multiply(long x, long y); static long subtract(long x, long y); static long calculateTotal(long baseCost, long unitCost, long units); static final long STEP; static final long SSTORE; static final long ZEROSTEP; static final long QUICKSTEP; static final long FASTESTSTEP; static final long FASTSTEP; static final long MIDSTEP; static final long SLOWSTEP; static final long EXTSTEP; static final long GENESISGASLIMIT; static final long MINGASLIMIT; static final long BALANCE; static final long SHA3; static final long SHA3_WORD; static final long SLOAD; static final long STOP; static final long SUICIDE; static final long CLEAR_SSTORE; static final long SET_SSTORE; static final long RESET_SSTORE; static final long REFUND_SSTORE; static final long CREATE; static final long JUMPDEST; static final long CREATE_DATA_BYTE; static final long CALL; static final long STIPEND_CALL; static final long VT_CALL; static final long NEW_ACCT_CALL; static final long MEMORY; static final long MEMORY_V1; static final long SUICIDE_REFUND; static final long QUAD_COEFF_DIV; static final long CREATE_DATA; static final long REPLACE_DATA; static final long TX_NO_ZERO_DATA; static final long TX_ZERO_DATA; static final long TRANSACTION; static final long TRANSACTION_DEFAULT; static final long TRANSACTION_CREATE_CONTRACT; static final long LOG_GAS; static final long LOG_DATA_GAS; static final long LOG_TOPIC_GAS; static final long COPY_GAS; static final long EXP_GAS; static final long EXP_BYTE_GAS; static final long IDENTITY; static final long IDENTITY_WORD; static final long RIPEMD160; static final long RIPEMD160_WORD; static final long SHA256; static final long SHA256_WORD; static final long EC_RECOVER; static final long EXT_CODE_SIZE; static final long EXT_CODE_COPY; static final long EXT_CODE_HASH; static final long CODEREPLACE; static final long NEW_ACCT_SUICIDE; static final long RETURN; static final long MAX_GAS; } | @Test public void calculateGasCost() throws GasCost.InvalidGasException { Assert.assertEquals(1, GasCost.calculateTotal(1, 0, 0)); Assert.assertEquals(2, GasCost.calculateTotal(0, 2, 1)); Assert.assertEquals(7, GasCost.calculateTotal(1, 2, 3)); Assert.assertEquals(10, GasCost.calculateTotal(4, 3, 2)); Assert.assertEquals(GasCost.CREATE + 100 * GasCost.CREATE_DATA, GasCost.calculateTotal(GasCost.CREATE, GasCost.CREATE_DATA, 100)); Assert.assertEquals(Long.MAX_VALUE, GasCost.calculateTotal(1, Long.MAX_VALUE, 1)); Assert.assertEquals(Long.MAX_VALUE, GasCost.calculateTotal(Long.MAX_VALUE, Long.MAX_VALUE, 1)); Assert.assertEquals(Long.MAX_VALUE, GasCost.calculateTotal(0, Long.MAX_VALUE, 2)); }
@Test(expected = GasCost.InvalidGasException.class) public void calculateGasCostWithNegativeSecondInputs() throws GasCost.InvalidGasException { GasCost.calculateTotal(1, -1, 1); }
@Test(expected = GasCost.InvalidGasException.class) public void calculateGasCostWithNegativeFirstInput() throws GasCost.InvalidGasException { GasCost.calculateTotal(-1, 1, 1); }
@Test(expected = GasCost.InvalidGasException.class) public void calculateGasCostWithNegativeThirdInput() throws GasCost.InvalidGasException { GasCost.calculateTotal(1, 1, -1); }
@Test public void calculateGasCostBeyondMaxGas() throws GasCost.InvalidGasException { Assert.assertEquals(Long.MAX_VALUE, GasCost.calculateTotal(1, Long.MAX_VALUE, 1)); Assert.assertEquals(Long.MAX_VALUE, GasCost.calculateTotal(1, Long.MAX_VALUE, 1)); Assert.assertEquals(Long.MAX_VALUE, GasCost.calculateTotal(Long.MAX_VALUE, 1, 1)); } |
DataWord implements Comparable<DataWord> { public DataWord add(DataWord word) { byte[] newdata = new byte[BYTES]; for (int i = 31, overflow = 0; i >= 0; i--) { int v = (this.data[i] & 0xff) + (word.data[i] & 0xff) + overflow; newdata[i] = (byte) v; overflow = v >>> 8; } return new DataWord(newdata); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; } | @Test public void testAdd() { byte[] three = new byte[32]; for (int i = 0; i < three.length; i++) { three[i] = (byte) 0xff; } DataWord x = DataWord.valueOf(three); byte[] xdata = x.getData(); DataWord result = x.add(DataWord.valueOf(three)); assertArrayEquals(xdata, x.getData()); assertEquals(32, result.getData().length); } |
DataWord implements Comparable<DataWord> { public DataWord mod(DataWord word) { if (word.isZero()) { return DataWord.ZERO; } BigInteger result = value().mod(word.value()); return valueOf(result.and(MAX_VALUE)); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; } | @Test public void testMod() { String expected = "000000000000000000000000000000000000000000000000000000000000001a"; byte[] one = new byte[32]; one[31] = 0x1e; byte[] two = new byte[32]; for (int i = 0; i < two.length; i++) { two[i] = (byte) 0xff; } two[31] = 0x56; DataWord x = DataWord.valueOf(one); byte[] xdata = x.getData(); DataWord y = DataWord.valueOf(two); byte[] ydata = y.getData(); DataWord result = y.mod(x); assertArrayEquals(xdata, x.getData()); assertArrayEquals(ydata, y.getData()); assertEquals(32, result.getData().length); assertEquals(expected, ByteUtil.toHexString(result.getData())); } |
DataWord implements Comparable<DataWord> { public DataWord mul(DataWord word) { BigInteger result = value().multiply(word.value()); return valueOf(result.and(MAX_VALUE)); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; } | @Test public void testMul() { byte[] one = new byte[32]; one[31] = 0x1; byte[] two = new byte[32]; two[11] = 0x1; DataWord x = DataWord.valueOf(one); DataWord y = DataWord.valueOf(two); byte[] xdata = x.getData(); byte[] ydata = y.getData(); DataWord result = x.mul(y); assertArrayEquals(xdata, x.getData()); assertArrayEquals(ydata, y.getData()); assertEquals(32, y.getData().length); assertEquals("0000000000000000000000010000000000000000000000000000000000000000", ByteUtil.toHexString(y.getData())); assertEquals(32, result.getData().length); assertEquals("0000000000000000000000010000000000000000000000000000000000000000", ByteUtil.toHexString(result.getData())); } |
DataWord implements Comparable<DataWord> { public DataWord div(DataWord word) { if (word.isZero()) { return DataWord.ZERO; } BigInteger result = value().divide(word.value()); return valueOf(result.and(MAX_VALUE)); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; } | @Test public void testDiv() { byte[] one = new byte[32]; one[30] = 0x01; one[31] = 0x2c; byte[] two = new byte[32]; two[31] = 0x0f; DataWord x = DataWord.valueOf(one); DataWord y = DataWord.valueOf(two); byte[] xdata = x.getData(); byte[] ydata = y.getData(); DataWord result =x.div(y); assertArrayEquals(xdata, x.getData()); assertArrayEquals(ydata, y.getData()); assertEquals(32, result.getData().length); assertEquals("0000000000000000000000000000000000000000000000000000000000000014", ByteUtil.toHexString(result.getData())); } |
DataWord implements Comparable<DataWord> { public static DataWord valueOf(int num) { byte[] data = new byte[BYTES]; ByteBuffer.wrap(data).putInt(data.length - Integer.BYTES, num); return valueOf(data); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; } | @Test public void testPow() { BigInteger x = BigInteger.valueOf(Integer.MAX_VALUE); BigInteger y = BigInteger.valueOf(1000); BigInteger result1 = x.modPow(x, y); BigInteger result2 = pow(x, y); } |
DataWord implements Comparable<DataWord> { public DataWord signExtend(byte k) { byte[] newdata = getData(); if (0 > k || k > 31) { throw new IndexOutOfBoundsException(); } byte mask = (new BigInteger(newdata)).testBit((k * 8) + 7) ? (byte) 0xff : 0; for (int i = 31; i > k; i--) { newdata[31 - i] = mask; } return new DataWord(newdata); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; } | @Test(expected = IndexOutOfBoundsException.class) public void testSignExtendException1() { byte k = -1; DataWord x = DataWord.ZERO; x.signExtend(k); }
@Test(expected = IndexOutOfBoundsException.class) public void testSignExtendException2() { byte k = 32; DataWord x = DataWord.ZERO; x.signExtend(k); } |
DataWord implements Comparable<DataWord> { public static DataWord fromString(String value) { return valueOf(value.getBytes(StandardCharsets.UTF_8)); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; } | @Test public void testFromString() { DataWord parsed = DataWord.fromString("01234567890123456789012345678901"); assertEquals(new String(parsed.getData()),"01234567890123456789012345678901"); } |
DataWord implements Comparable<DataWord> { public static DataWord fromLongString(String value) { return valueOf(HashUtil.keccak256(value.getBytes(StandardCharsets.UTF_8))); } private DataWord(byte[] data); byte[] getData(); byte[] getNoLeadZeroesData(); byte[] getByteArrayForStorage(); byte[] getLast20Bytes(); BigInteger value(); int intValue(); int intValueCheck(); int intValueSafe(); long longValue(); long longValueSafe(); BigInteger sValue(); String bigIntValue(); boolean isZero(); boolean isNegative(); DataWord and(DataWord w2); DataWord or(DataWord w2); DataWord xor(DataWord w2); DataWord bnot(); DataWord add(DataWord word); DataWord mul(DataWord word); DataWord div(DataWord word); DataWord sDiv(DataWord word); DataWord sub(DataWord word); DataWord exp(DataWord word); DataWord mod(DataWord word); DataWord sMod(DataWord word); DataWord addmod(DataWord word1, DataWord word2); DataWord mulmod(DataWord word1, DataWord word2); DataWord shiftLeft(DataWord arg); DataWord shiftRight(DataWord arg); DataWord shiftRightSigned(DataWord arg); @JsonValue @Override String toString(); String toPrefixString(); String shortHex(); @Override boolean equals(Object o); boolean equalValue(DataWord o); @Override int hashCode(); @Override int compareTo(DataWord o); DataWord signExtend(byte k); boolean occupyMoreThan(int n); int bytesOccupied(); static int numberOfLeadingZeros(byte i); static int numberOfTrailingNonZeros(byte i); int bitsOccupied(); boolean isHex(String hex); static DataWord fromString(String value); static DataWord fromLongString(String value); @JsonCreator static DataWord valueFromHex(String data); static DataWord valueOf(int num); static DataWord valueOf(long num); static DataWord valueOf(byte[] data); static DataWord valueOf(byte[] data, int offset, int length); static final int BYTES; static final BigInteger _2_256; static final BigInteger MAX_VALUE; static final DataWord ZERO; static final DataWord ONE; static final int MAX_POW; } | @Test public void testFromLongString() { String value = "012345678901234567890123456789012345678901234567890123456789"; byte[] hashedValue = HashUtil.keccak256(value.getBytes(StandardCharsets.UTF_8)); DataWord parsed = DataWord.fromLongString(value); assertArrayEquals(parsed.getData(),hashedValue); } |
VM { public void steps(Program aprogram, long steps) { program = aprogram; stack = program.getStack(); try { for(long s=0;s<steps;s++) { if (program.isStopped()) { break; } if (vmConfig.vmTrace()) { program.saveOpTrace(); } op = OpCode.code(program.getCurrentOp()); checkOpcode(); program.setLastOp(op.val()); program.verifyStackSize(op.require()); program.verifyStackOverflow(op.require(), op.ret()); oldMemSize = program.getMemSize(); if (isLogEnabled) { hint = ""; } gasCost = op.getTier().asInt(); if (vmConfig.dumpBlock() >= 0) { gasBefore = program.getRemainingGas(); memWords = 0; } if (vmConfig.dumpBlock() >= 0 && program.getNumber().intValue() == vmConfig.dumpBlock()) { this.dumpLine(op, gasBefore, gasCost , memWords, program); } if (vmHook != null) { vmHook.step(program, op); } executeOpcode(); if (vmConfig.vmTrace()) { program.saveOpGasCost(gasCost); } logOpCode(); vmCounter++; } } catch (RuntimeException e) { logger.error("VM halted", e); program.spendAllGas(); program.resetFutureRefund(); program.stop(); throw e; } finally { if (isLogEnabled) { program.fullTrace(); } } } VM(VmConfig vmConfig, PrecompiledContracts precompiledContracts); void step(Program aprogram); int getVmCounter(); void resetVmCounter(); static long limitedAddToMaxLong(long left, long right); void steps(Program aprogram, long steps); void initDebugData(); void play(Program program); static void setVmHook(VMHook vmHook); } | @Test public void testCALLWithBigUserSpecifiedGas() { String maxGasValue = "7FFFFFFFFFFFFFFF"; RskAddress callee = createAddress("callee"); invoke = new ProgramInvokeMockImpl(compile("" + " ADD" ), callee); program = getProgram(compile("" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x01" + " PUSH20 0x" + callee.toHexString() + " PUSH8 0x" + maxGasValue + " CALL" ), createTransaction(0)); program.fullTrace(); vm.steps(program, Long.MAX_VALUE); Assert.assertEquals( "faulty program with bigger gas limit than gas available should use all the gas in a block", program.getResult().getGasUsed(), invoke.getGas() ); }
@Test(expected = Program.OutOfGasException.class) public void testLOGWithDataCostBiggerThanPreviousGasSize() { invoke.setGasLimit(6_800_000); long previousGasMaxSize = 0x3fffffffffffffffL; long sizeRequired = Math.floorDiv(previousGasMaxSize, GasCost.LOG_DATA_GAS) + 1; String sizeInHex = String.format("%016X", sizeRequired); assert(sizeRequired * GasCost.LOG_DATA_GAS > previousGasMaxSize); assert(sizeRequired > 0); program = getProgram(compile("" + " PUSH8 0x" + sizeInHex + " PUSH1 0x00" + " LOG0" )); program.fullTrace(); try { vm.steps(program, Long.MAX_VALUE); } finally { invoke.setGasLimit(100000); } }
@Test public void testSTATICCALLWithStatusOne() { invoke = new ProgramInvokeMockImpl(compile("PUSH1 0x01 PUSH1 0x02 SUB"), null); program = getProgram(compile("PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + invoke.getContractAddress() + " PUSH4 0x005B8D80" + " STATICCALL" )); program.fullTrace(); vm.steps(program, Long.MAX_VALUE); assertEquals(DataWord.ONE, program.stackPop()); assertTrue(program.getStack().isEmpty()); }
@Test public void testReturnDataCopyChargesCorrectGas() { invoke = new ProgramInvokeMockImpl(compile("" + " PUSH1 0x01 PUSH1 0x02 SUB PUSH1 0x00 MSTORE" + " PUSH1 0x20 PUSH1 0x00 RETURN" ), null); Program goodProgram = getProgram(compile("" + " PUSH1 0x20 " + " PUSH1 0x00 " + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + invoke.getContractAddress() + " PUSH1 0xFF" + " STATICCALL" + " PUSH1 0x20" + " PUSH1 0x00 " + " PUSH1 0x20" + " RETURNDATACOPY" + " PUSH1 0x20" + " PUSH1 0x20" + " RETURN" )); Program badProgram = getProgram(compile("" + " PUSH1 0x20 " + " PUSH1 0x00 " + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + invoke.getContractAddress() + " PUSH1 0xFF" + " STATICCALL" + " PUSH1 0x00" + " PUSH1 0x00 " + " PUSH1 0x20" + " RETURNDATACOPY" + " PUSH1 0x20" + " PUSH1 0x20" + " RETURN" )); vm.steps(goodProgram, Long.MAX_VALUE); vm.steps(badProgram, Long.MAX_VALUE); assertEquals("good program has 64 mem", 64, goodProgram.getMemSize()); assertEquals("bad program has 64 mem", 64, badProgram.getMemSize()); assertEquals("good program uses 3 more gas than the bad one", goodProgram.getResult().getGasUsed(), badProgram.getResult().getGasUsed() + 3); }
@Test public void getFreeMemoryUsingPrecompiledContractLyingAboutReturnSize() { Program initContract = getProgram(compile( " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x01" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + PrecompiledContracts.IDENTITY_ADDR_STR + " PUSH1 0xFF" + " CALL" )); Program bad = getProgram(compile("" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x20" + " PUSH1 0x01" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + PrecompiledContracts.IDENTITY_ADDR_STR + " PUSH4 0x005B8D80" + " CALL" )); Program good = getProgram(compile("PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x20" + " PUSH1 0x20" + " PUSH1 0x20" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + PrecompiledContracts.IDENTITY_ADDR_STR + " PUSH4 0x005B8D80" + " CALL" )); vm.steps(initContract, Long.MAX_VALUE); vm.steps(bad, Long.MAX_VALUE); vm.steps(good, Long.MAX_VALUE); Assert.assertEquals("good program will asign a new word of memory, so will charge 3 more", good.getResult().getGasUsed(), bad.getResult().getGasUsed() + GasCost.MEMORY); Assert.assertEquals("good program will have more memory, as it paid for it", good.getMemSize(), bad.getMemSize() + 32); }
@Test public void testCallDataCopyDoesNotExpandMemoryForFree() { invoke = new ProgramInvokeMockImpl(compile( " PUSH1 0x00 PUSH1 0x00 MSTORE " + " PUSH1 0x20 PUSH1 0x00 RETURN" ), null); Program badProgram = getProgram(compile( " PUSH1 0x20" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + invoke.getContractAddress() + " PUSH2 0xFFFF" + " STATICCALL" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x01 MSIZE SUB" + " CALLDATACOPY" )); Program goodProgram = getProgram(compile( " PUSH1 0x20" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + invoke.getContractAddress() + " PUSH2 0xFFFF" + " STATICCALL" + " PUSH1 0x20" + " PUSH1 0x00" + " PUSH1 0x01 MSIZE SUB" + " CALLDATACOPY" )); vm.steps(goodProgram, Long.MAX_VALUE); vm.steps(badProgram, Long.MAX_VALUE); assertEquals(32, badProgram.getMemSize()); assertEquals(64, goodProgram.getMemSize()); }
@Test public void getFreeMemoryUsingPrecompiledContractAndSettingFarOffOffset() { Program initContract = getProgram(compile( " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x01" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + PrecompiledContracts.IDENTITY_ADDR_STR + " PUSH1 0xFF" + " CALL" )); Program bad = getProgram(compile("" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH4 0x01000000" + " PUSH1 0x01" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + PrecompiledContracts.IDENTITY_ADDR_STR + " PUSH4 0x005B8D80" + " CALL" )); Program good = getProgram(compile("PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x01" + " PUSH1 0x00" + " PUSH1 0x01" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + PrecompiledContracts.IDENTITY_ADDR_STR + " PUSH4 0x005B8D80" + " CALL" )); vm.steps(initContract, Long.MAX_VALUE); vm.steps(bad, Long.MAX_VALUE); vm.steps(good, Long.MAX_VALUE); Assert.assertEquals(good.getResult().getGasUsed(), bad.getResult().getGasUsed()); Assert.assertEquals(good.getMemSize(), bad.getMemSize()); }
@Test(expected = EmptyStackException.class) public void testSTATICCALLWithStatusOneFailsWithOldCode() { invoke = new ProgramInvokeMockImpl(compile("PUSH1 0x01 PUSH1 0x02 SUB"), null); program = getProgram(compile("PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + invoke.getContractAddress() + " PUSH4 0x005B8D80" + " STATICCALL"), null, true); program.fullTrace(); vm.steps(program, Long.MAX_VALUE); }
@Test public void testSTATICCALLWithStatusOneAndAdditionalValueInStackUsingPreFixStaticCall() { invoke = new ProgramInvokeMockImpl(compile("PUSH1 0x01 PUSH1 0x02 SUB"), null); program = getProgram(compile("PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + invoke.getContractAddress() + " PUSH4 0x005B8D80" + " STATICCALL"), null, true); program.fullTrace(); vm.steps(program, Long.MAX_VALUE); assertEquals(DataWord.ONE, program.stackPop()); assertTrue(program.getStack().isEmpty()); }
@Test public void testSTATICCALLWithStatusOneAndAdditionalValueInStackUsingFixStaticCallLeavesValueInStack() { invoke = new ProgramInvokeMockImpl(compile("PUSH1 0x01 PUSH1 0x02 SUB"), null); program = getProgram(compile("PUSH1 0x2a" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH1 0x00" + " PUSH20 0x" + invoke.getContractAddress() + " PUSH4 0x005B8D80" + " STATICCALL")); program.fullTrace(); vm.steps(program, Long.MAX_VALUE); assertEquals(DataWord.ONE, program.stackPop()); assertFalse(program.getStack().isEmpty()); assertEquals(1, program.getStack().size()); assertEquals(DataWord.valueOf(42), program.getStack().pop()); } |
Web3Impl implements Web3 { @Override public TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index) { TransactionResultDTO s = null; try { Block b = getBlockByJSonHash(blockHash); if (b == null) { return null; } int idx = JSonHexToInt(index); if (idx >= b.getTransactionsList().size()) { return null; } Transaction tx = b.getTransactionsList().get(idx); return s = new TransactionResultDTO(b, idx, tx); } finally { if (logger.isDebugEnabled()) { logger.debug("eth_getTransactionByBlockHashAndIndex({}, {}): {}", blockHash, index, s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getTransactionByBlockHashAndIndex() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).transactions(txs).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); String hashString = tx.getHash().toHexString(); String blockHashString = block1.getHash().toHexString(); TransactionResultDTO tr = web3.eth_getTransactionByBlockHashAndIndex(blockHashString, "0x0"); assertNotNull(tr); org.junit.Assert.assertEquals("0x" + hashString, tr.hash); org.junit.Assert.assertEquals("0x" + blockHashString, tr.blockHash); }
@Test public void getUnknownTransactionByBlockHashAndIndex() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); String blockHashString = block1.getHash().toString(); TransactionResultDTO tr = web3.eth_getTransactionByBlockHashAndIndex(blockHashString, "0x0"); Assert.assertNull(tr); } |
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(); } | @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()); } |
Web3Impl implements Web3 { @Override public TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index) { TransactionResultDTO s = null; try { Optional<Block> block = web3InformationRetriever.getBlock(bnOrId); if (!block.isPresent()) { return null; } int idx = JSonHexToInt(index); List<Transaction> txs = web3InformationRetriever.getTransactions(bnOrId); if (idx >= txs.size()) { return null; } s = new TransactionResultDTO(block.get(), idx, txs.get(idx)); return s; } finally { if (logger.isDebugEnabled()) { logger.debug("eth_getTransactionByBlockNumberAndIndex({}, {}): {}", bnOrId, index, s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getTransactionByBlockNumberAndIndex() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).transactions(txs).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); String hashString = tx.getHash().toHexString(); String blockHashString = block1.getHash().toHexString(); TransactionResultDTO tr = web3.eth_getTransactionByBlockNumberAndIndex("0x01", "0x0"); assertNotNull(tr); org.junit.Assert.assertEquals("0x" + hashString, tr.hash); org.junit.Assert.assertEquals("0x" + blockHashString, tr.blockHash); }
@Test public void getUnknownTransactionByBlockNumberAndIndex() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); TransactionResultDTO tr = web3.eth_getTransactionByBlockNumberAndIndex("0x1", "0x0"); Assert.assertNull(tr); } |
Web3Impl implements Web3 { @Override public String eth_getTransactionCount(String address, String blockId) { String s = null; try { RskAddress addr = new RskAddress(address); AccountInformationProvider accountInformationProvider = web3InformationRetriever .getInformationProvider(blockId); BigInteger nonce = accountInformationProvider.getNonce(addr); s = toQuantityJsonHex(nonce); return s; } finally { if (logger.isDebugEnabled()) { logger.debug("eth_getTransactionCount({}, {}): {}", address, blockId, s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getTransactionCount() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(100000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).transactions(txs).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); String accountAddress = ByteUtil.toHexString(acc1.getAddress().getBytes()); String count = web3.eth_getTransactionCount(accountAddress, "0x1"); assertNotNull(count); org.junit.Assert.assertEquals("0x1", count); count = web3.eth_getTransactionCount(accountAddress, "0x0"); assertNotNull(count); org.junit.Assert.assertEquals("0x0", count); } |
Web3Impl implements Web3 { @Override public BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects) { BlockResultDTO s = null; try { s = web3InformationRetriever.getBlock(bnOrId) .map(b -> getBlockResult(b, fullTransactionObjects)) .orElse(null); return s; } finally { if (logger.isDebugEnabled()) { logger.debug("eth_getBlockByNumber({}, {}): {}", bnOrId, fullTransactionObjects, s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getBlockByNumber() { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); Block block1b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(2).parent(genesis).build(); block1b.setBitcoinMergedMiningHeader(new byte[]{0x01}); Block block2b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(11).parent(block1b).build(); block2b.setBitcoinMergedMiningHeader(new byte[] { 0x02 }); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(block1b)); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block2b)); BlockResultDTO bresult = web3.eth_getBlockByNumber("0x1", false); assertNotNull(bresult); String blockHash = "0x" + block1b.getHash(); org.junit.Assert.assertEquals(blockHash, bresult.getHash()); String bnOrId = "0x2"; bresult = web3.eth_getBlockByNumber("0x2", true); assertNotNull(bresult); blockHash = "0x" + block2b.getHash(); org.junit.Assert.assertEquals(blockHash, bresult.getHash()); String hexString = web3.rsk_getRawBlockHeaderByNumber(bnOrId).replace("0x",""); Keccak256 obtainedBlockHash = new Keccak256(HashUtil.keccak256(Hex.decode(hexString))); Assert.assertEquals(blockHash, obtainedBlockHash.toJsonString()); }
@Test public void getBlockByNumberRetrieveLatestBlock() { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).build(); block1.setBitcoinMergedMiningHeader(new byte[] { 0x01 }); assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); BlockResultDTO blockResult = web3.eth_getBlockByNumber("latest", false); assertNotNull(blockResult); String blockHash = TypeConverter.toJsonHex(block1.getHash().toString()); assertEquals(blockHash, blockResult.getHash()); }
@Test public void getBlockByNumberRetrieveEarliestBlock() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); String bnOrId = "earliest"; BlockResultDTO blockResult = web3.eth_getBlockByNumber(bnOrId, false); assertNotNull(blockResult); String blockHash = genesis.getHashJsonString(); org.junit.Assert.assertEquals(blockHash, blockResult.getHash()); String hexString = web3.rsk_getRawBlockHeaderByNumber(bnOrId).replace("0x",""); Keccak256 obtainedBlockHash = new Keccak256(HashUtil.keccak256(Hex.decode(hexString))); Assert.assertEquals(blockHash, obtainedBlockHash.toJsonString()); }
@Test public void getBlockByNumberBlockDoesNotExists() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); String bnOrId = "0x1234"; BlockResultDTO blockResult = web3.eth_getBlockByNumber(bnOrId, false); Assert.assertNull(blockResult); String hexString = web3.rsk_getRawBlockHeaderByNumber(bnOrId); Assert.assertNull(hexString); }
@Test(expected=org.ethereum.rpc.exception.RskJsonRpcRequestException.class) public void getBlockByNumberWhenNumberIsInvalidThrowsException() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); String bnOrId = "991234"; web3.eth_getBlockByNumber(bnOrId, false); }
@Test public void getBlockByNumberBlockWithUncles() { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()) .difficulty(20) .parent(genesis) .build(); block1.setBitcoinMergedMiningHeader(new byte[]{0x01}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); Block block1b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()) .difficulty(10) .parent(genesis) .build(); block1b.setBitcoinMergedMiningHeader(new byte[]{0x02}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(block1b)); Block block1c = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()) .difficulty(10) .parent(genesis) .build(); block1c.setBitcoinMergedMiningHeader(new byte[]{0x03}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(block1c)); ArrayList<BlockHeader> uncles = new ArrayList<>(); uncles.add(block1b.getHeader()); uncles.add(block1c.getHeader()); Block block2 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()) .difficulty(10) .parent(block1) .uncles(uncles) .build(); block2.setBitcoinMergedMiningHeader(new byte[]{0x04}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block2)); String block1HashString = "0x" + block1.getHash(); String block1bHashString = "0x" + block1b.getHash(); String block1cHashString = "0x" + block1c.getHash(); String block2HashString = "0x" + block2.getHash(); BlockResultDTO result = web3.eth_getBlockByNumber("0x02", false); Assert.assertEquals(block2HashString, result.getHash()); Assert.assertEquals(block1HashString, result.getParentHash()); Assert.assertTrue(result.getUncles().contains(block1bHashString)); Assert.assertTrue(result.getUncles().contains(block1cHashString)); Assert.assertEquals(TypeConverter.toQuantityJsonHex(30), result.getCumulativeDifficulty()); } |
Web3Impl implements Web3 { public BlockInformationResult[] eth_getBlocksByNumber(String number) { long blockNumber; try { blockNumber = TypeConverter.stringNumberAsBigInt(number).longValue(); } catch (NumberFormatException | StringIndexOutOfBoundsException e) { throw invalidParamError(String.format("invalid blocknumber %s", number)); } List<BlockInformationResult> result = new ArrayList<>(); List<BlockInformation> binfos = blockchain.getBlocksInformationByNumber(blockNumber); for (BlockInformation binfo : binfos) { result.add(getBlockInformationResult(binfo)); } return result.toArray(new BlockInformationResult[result.size()]); } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getBlocksByNumber() { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); Block block1b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(block1.getDifficulty().asBigInteger().longValue()-1).parent(genesis).build(); block1b.setBitcoinMergedMiningHeader(new byte[]{0x01}); Block block2b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(2).parent(block1b).build(); block2b.setBitcoinMergedMiningHeader(new byte[] { 0x02 }); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(block1b)); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block2b)); Web3.BlockInformationResult[] bresult = web3.eth_getBlocksByNumber("0x1"); String hashBlock1String = block1.getHashJsonString(); String hashBlock1bString = block1b.getHashJsonString(); assertNotNull(bresult); assertEquals(2, bresult.length); assertEquals(hashBlock1String, bresult[0].hash); assertEquals(hashBlock1bString, bresult[1].hash); } |
Web3Impl implements Web3 { @Override public BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects) { BlockResultDTO s = null; try { Block b = getBlockByJSonHash(blockHash); return s = (b == null ? null : getBlockResult(b, fullTransactionObjects)); } finally { if (logger.isDebugEnabled()) { logger.debug("eth_getBlockByHash({}, {}): {}", blockHash, fullTransactionObjects, s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getBlockByHash() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); block1.setBitcoinMergedMiningHeader(new byte[] { 0x01 }); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); Block block1b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(block1.getDifficulty().asBigInteger().longValue()-1).parent(genesis).build(); block1b.setBitcoinMergedMiningHeader(new byte[] { 0x01 }); Block block2b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).difficulty(2).parent(block1b).build(); block2b.setBitcoinMergedMiningHeader(new byte[] { 0x02 }); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(block1b)); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block2b)); String block1HashString = "0x" + block1.getHash(); String block1bHashString = "0x" + block1b.getHash(); String block2bHashString = "0x" + block2b.getHash(); BlockResultDTO bresult = web3.eth_getBlockByHash(block1HashString, false); assertNotNull(bresult); org.junit.Assert.assertEquals(block1HashString, bresult.getHash()); org.junit.Assert.assertEquals("0x", bresult.getExtraData()); org.junit.Assert.assertEquals(0, bresult.getTransactions().size()); org.junit.Assert.assertEquals(0, bresult.getUncles().size()); org.junit.Assert.assertEquals("0xa", bresult.getDifficulty()); org.junit.Assert.assertEquals("0xb", bresult.getTotalDifficulty()); bresult = web3.eth_getBlockByHash(block1bHashString, true); assertNotNull(bresult); org.junit.Assert.assertEquals(block1bHashString, bresult.getHash()); String hexString = web3.rsk_getRawBlockHeaderByHash(block1bHashString).replace("0x",""); Keccak256 blockHash = new Keccak256(HashUtil.keccak256(Hex.decode(hexString))); Assert.assertEquals(blockHash.toJsonString(), block1bHashString); bresult = web3.eth_getBlockByHash(block2bHashString, true); assertNotNull(bresult); org.junit.Assert.assertEquals(block2bHashString, bresult.getHash()); hexString = web3.rsk_getRawBlockHeaderByHash(block2bHashString).replace("0x",""); blockHash = new Keccak256(HashUtil.keccak256(Hex.decode(hexString))); Assert.assertEquals(blockHash.toJsonString(), block2bHashString); }
@Test public void getBlockByHashWithFullTransactionsAsResult() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(220000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(0)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).transactions(txs).build(); block1.setBitcoinMergedMiningHeader(new byte[]{0x01}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); String block1HashString = block1.getHashJsonString(); BlockResultDTO bresult = web3.eth_getBlockByHash(block1HashString, true); assertNotNull(bresult); org.junit.Assert.assertEquals(block1HashString, bresult.getHash()); org.junit.Assert.assertEquals(1, bresult.getTransactions().size()); org.junit.Assert.assertEquals(block1HashString, ((TransactionResultDTO) bresult.getTransactions().get(0)).blockHash); org.junit.Assert.assertEquals(0, bresult.getUncles().size()); org.junit.Assert.assertEquals("0x0", ((TransactionResultDTO) bresult.getTransactions().get(0)).value); }
@Test public void getBlockByHashWithTransactionsHashAsResult() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(220000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(0)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()).trieStore(world.getTrieStore()).parent(genesis).transactions(txs).build(); block1.setBitcoinMergedMiningHeader(new byte[] { 0x01 }); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); String block1HashString = block1.getHashJsonString(); BlockResultDTO bresult = web3.eth_getBlockByHash(block1HashString, false); assertNotNull(bresult); org.junit.Assert.assertEquals(block1HashString, bresult.getHash()); org.junit.Assert.assertEquals(1, bresult.getTransactions().size()); org.junit.Assert.assertEquals(tx.getHash().toJsonString(), bresult.getTransactions().get(0)); org.junit.Assert.assertEquals(0, bresult.getUncles().size()); }
@Test public void getBlockByHashBlockDoesNotExists() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); String blockHash = "0x1234000000000000000000000000000000000000000000000000000000000000"; BlockResultDTO blockResult = web3.eth_getBlockByHash(blockHash, false); Assert.assertNull(blockResult); String hexString = web3.rsk_getRawBlockHeaderByHash(blockHash); Assert.assertNull(hexString); }
@Test public void getBlockByHashBlockWithUncles() { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block block1 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()) .difficulty(20) .parent(genesis) .build(); block1.setBitcoinMergedMiningHeader(new byte[]{0x01}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block1)); Block block1b = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()) .difficulty(10) .parent(genesis) .build(); block1b.setBitcoinMergedMiningHeader(new byte[]{0x02}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(block1b)); Block block1c = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()) .difficulty(10) .parent(genesis) .build(); block1c.setBitcoinMergedMiningHeader(new byte[]{0x03}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(block1c)); ArrayList<BlockHeader> uncles = new ArrayList<>(); uncles.add(block1b.getHeader()); uncles.add(block1c.getHeader()); Block block2 = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()) .difficulty(10) .parent(block1) .uncles(uncles) .build(); block2.setBitcoinMergedMiningHeader(new byte[]{0x04}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(block2)); String block1HashString = "0x" + block1.getHash(); String block1bHashString = "0x" + block1b.getHash(); String block1cHashString = "0x" + block1c.getHash(); String block2HashString = "0x" + block2.getHash(); BlockResultDTO result = web3.eth_getBlockByHash(block2HashString, false); Assert.assertEquals(block2HashString, result.getHash()); Assert.assertEquals(block1HashString, result.getParentHash()); Assert.assertTrue(result.getUncles().contains(block1bHashString)); Assert.assertTrue(result.getUncles().contains(block1cHashString)); Assert.assertEquals(TypeConverter.toQuantityJsonHex(30), result.getCumulativeDifficulty()); } |
Web3Impl implements Web3 { @Override public BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx) { BlockResultDTO s = null; try { Block block = blockchain.getBlockByHash(stringHexToByteArray(blockHash)); if (block == null) { return null; } s = getUncleResultDTO(uncleIdx, block); return s; } finally { if (logger.isDebugEnabled()) { logger.debug("eth_getUncleByBlockHashAndIndex({}, {}): {}", blockHash, uncleIdx, s); } } } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void getUncleByBlockHashAndIndexBlockWithUncles() { World world = new World(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block blockA = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockA.setBitcoinMergedMiningHeader(new byte[]{0x01}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockA)); Block blockB = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockB.setBitcoinMergedMiningHeader(new byte[]{0x02}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(blockB)); Block blockC = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockC.setBitcoinMergedMiningHeader(new byte[]{0x03}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(blockC)); Block blockD = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(100).parent(blockA).build(); blockD.setBitcoinMergedMiningHeader(new byte[]{0x04}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockD)); List<BlockHeader> blockEUncles = Arrays.asList(blockB.getHeader(), blockC.getHeader()); Block blockE = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(blockA).uncles(blockEUncles).build(); blockE.setBitcoinMergedMiningHeader(new byte[]{0x05}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(blockE)); List<BlockHeader> blockFUncles = Arrays.asList(blockE.getHeader()); Block blockF = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(blockD).uncles(blockFUncles).build(); blockF.setBitcoinMergedMiningHeader(new byte[]{0x06}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockF)); String blockFhash = "0x" + blockF.getHash(); String blockEhash = "0x" + blockE.getHash(); String blockBhash = "0x" + blockB.getHash(); String blockChash = "0x" + blockC.getHash(); BlockResultDTO result = web3.eth_getUncleByBlockHashAndIndex(blockFhash, "0x00"); Assert.assertEquals(blockEhash, result.getHash()); Assert.assertEquals(2, result.getUncles().size()); Assert.assertTrue(result.getUncles().contains(blockBhash)); Assert.assertTrue(result.getUncles().contains(blockChash)); Assert.assertEquals(TypeConverter.toQuantityJsonHex(30), result.getCumulativeDifficulty()); }
@Test public void getUncleByBlockHashAndIndexBlockWithUnclesCorrespondingToAnUnknownBlock() { World world = new World(); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(10000)).build(); Web3Impl web3 = createWeb3(world); Block genesis = world.getBlockChain().getBestBlock(); Block blockA = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockA.setBitcoinMergedMiningHeader(new byte[]{0x01}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockA)); Block blockB = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockB.setBitcoinMergedMiningHeader(new byte[]{0x02}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(blockB)); Block blockC = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(genesis).build(); blockC.setBitcoinMergedMiningHeader(new byte[]{0x03}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, world.getBlockChain().tryToConnect(blockC)); Block blockD = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(100).parent(blockA).build(); blockD.setBitcoinMergedMiningHeader(new byte[]{0x04}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockD)); Transaction tx = new TransactionBuilder() .sender(acc1) .gasLimit(BigInteger.valueOf(100000)) .gasPrice(BigInteger.ONE) .build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx); List<BlockHeader> blockEUncles = Arrays.asList(blockB.getHeader(), blockC.getHeader()); Block blockE = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(blockA).uncles(blockEUncles) .transactions(txs).buildWithoutExecution(); blockE.setBitcoinMergedMiningHeader(new byte[]{0x05}); Assert.assertEquals(1, blockE.getTransactionsList().size()); Assert.assertFalse(Arrays.equals(blockC.getTxTrieRoot(), blockE.getTxTrieRoot())); List<BlockHeader> blockFUncles = Arrays.asList(blockE.getHeader()); Block blockF = new BlockBuilder(world.getBlockChain(), world.getBridgeSupportFactory(), world.getBlockStore()) .trieStore(world.getTrieStore()).difficulty(10).parent(blockD).uncles(blockFUncles).build(); blockF.setBitcoinMergedMiningHeader(new byte[]{0x06}); org.junit.Assert.assertEquals(ImportResult.IMPORTED_BEST, world.getBlockChain().tryToConnect(blockF)); String blockFhash = "0x" + blockF.getHash(); String blockEhash = "0x" + blockE.getHash(); BlockResultDTO result = web3.eth_getUncleByBlockHashAndIndex(blockFhash, "0x00"); Assert.assertEquals(blockEhash, result.getHash()); Assert.assertEquals(0, result.getUncles().size()); Assert.assertEquals(0, result.getTransactions().size()); Assert.assertEquals("0x" + ByteUtil.toHexString(blockE.getTxTrieRoot()), result.getTransactionsRoot()); } |
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); } | @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); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.