src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
BlockDifficulty implements Comparable<BlockDifficulty>, Serializable { public BlockDifficulty add(BlockDifficulty other) { return new BlockDifficulty(value.add(other.value)); } BlockDifficulty(BigInteger value); byte[] getBytes(); BigInteger asBigInteger(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); BlockDifficulty add(BlockDifficulty other); BlockDifficulty subtract(BlockDifficulty other); @Override int compareTo(@Nonnull BlockDifficulty other); static final BlockDifficulty ZERO; static final BlockDifficulty ONE; }
@Test public void addOneToZero() { BlockDifficulty d1 = new BlockDifficulty(BigInteger.ZERO); BlockDifficulty d2 = new BlockDifficulty(BigInteger.ONE); assertThat(d1.add(d2), is(d2)); } @Test public void addOneToOne() { BlockDifficulty d1 = new BlockDifficulty(BigInteger.ONE); BlockDifficulty d2 = new BlockDifficulty(BigInteger.ONE); assertThat(d1.add(d2), is(new BlockDifficulty(BigInteger.valueOf(2)))); } @Test public void addLargeValues() { BlockDifficulty d1 = new BlockDifficulty(BigInteger.valueOf(Long.MAX_VALUE)); BlockDifficulty d2 = new BlockDifficulty(BigInteger.valueOf(Integer.MAX_VALUE)); assertThat(d1.add(d2), is(new BlockDifficulty(new BigInteger("9223372039002259454")))); }
Web3Impl implements Web3 { @Override public String eth_protocolVersion() { return rsk_protocolVersion(); } 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_protocolVersion() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); String netVersion = web3.eth_protocolVersion(); assertTrue("RSK net version different than one", netVersion.compareTo("1") == 0); }
BlockDifficulty implements Comparable<BlockDifficulty>, Serializable { @Override public int compareTo(@Nonnull BlockDifficulty other) { return value.compareTo(other.value); } BlockDifficulty(BigInteger value); byte[] getBytes(); BigInteger asBigInteger(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); BlockDifficulty add(BlockDifficulty other); BlockDifficulty subtract(BlockDifficulty other); @Override int compareTo(@Nonnull BlockDifficulty other); static final BlockDifficulty ZERO; static final BlockDifficulty ONE; }
@Test public void testComparable() { BlockDifficulty zero = BlockDifficulty.ZERO; BlockDifficulty d1 = new BlockDifficulty(BigInteger.valueOf(Long.MAX_VALUE)); BlockDifficulty d2 = new BlockDifficulty(BigInteger.valueOf(Integer.MAX_VALUE)); assertThat(zero.compareTo(zero), is(0)); assertThat(d1.compareTo(d1), is(0)); assertThat(d2.compareTo(d2), is(0)); assertThat(zero.compareTo(d1), is(-1)); assertThat(zero.compareTo(d2), is(-1)); assertThat(d1.compareTo(zero), is(1)); assertThat(d2.compareTo(zero), is(1)); assertThat(d1.compareTo(d2), is(1)); assertThat(d2.compareTo(d1), is(-1)); }
Wallet { public List<byte[]> getAccountAddresses() { List<byte[]> addresses = new ArrayList<>(); Set<RskAddress> keys = new HashSet<>(); synchronized(accessLock) { for (RskAddress addr: this.initialAccounts) { addresses.add(addr.getBytes()); } for (byte[] address: keyDS.keys()) { keys.add(new RskAddress(address)); } keys.addAll(accounts.keySet()); keys.removeAll(this.initialAccounts); for (RskAddress addr: keys) { addresses.add(addr.getBytes()); } } return addresses; } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }
@Test public void getEmptyAccountList() { Wallet wallet = WalletFactory.createWallet(); List<byte[]> addresses = wallet.getAccountAddresses(); Assert.assertNotNull(addresses); Assert.assertTrue(addresses.isEmpty()); }
Wallet { public byte[] addAccountWithSeed(String seed) { return addAccountWithPrivateKey(Keccak256Helper.keccak256(seed.getBytes(StandardCharsets.UTF_8))); } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }
@Test public void addAccountWithSeed() { Wallet wallet = WalletFactory.createWallet(); byte[] address = wallet.addAccountWithSeed("seed"); Assert.assertNotNull(address); byte[] calculatedAddress = ECKey.fromPrivate(Keccak256Helper.keccak256("seed".getBytes())).getAddress(); Assert.assertArrayEquals(calculatedAddress, address); List<byte[]> addresses = wallet.getAccountAddresses(); Assert.assertNotNull(addresses); Assert.assertFalse(addresses.isEmpty()); Assert.assertEquals(1, addresses.size()); byte[] addr = addresses.get(0); Assert.assertNotNull(addr); Assert.assertArrayEquals(address, addr); }
Wallet { public boolean unlockAccount(RskAddress addr, String passphrase, long duration) { long ending = System.currentTimeMillis() + duration; boolean unlocked = unlockAccount(addr, passphrase); if (unlocked) { synchronized (accessLock) { unlocksTimeouts.put(addr, ending); } } return unlocked; } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }
@Test public void unlockNonexistentAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Assert.assertFalse(wallet.unlockAccount(addr, "passphrase")); }
Wallet { public boolean lockAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return false; } accounts.remove(addr); return true; } } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }
@Test public void lockAccount() { Wallet wallet = WalletFactory.createWallet(); byte[] address = wallet.addAccount("passphrase").getBytes(); Assert.assertNotNull(address); Assert.assertTrue(wallet.unlockAccount(new RskAddress(address), "passphrase")); Account account = wallet.getAccount(new RskAddress(address)); Assert.assertNotNull(account); Assert.assertArrayEquals(address, account.getAddress().getBytes()); Assert.assertTrue(wallet.lockAccount(new RskAddress(address))); Account account2 = wallet.getAccount(new RskAddress(address)); Assert.assertNull(account2); } @Test public void lockNonexistentAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Assert.assertFalse(wallet.lockAccount(addr)); }
Wallet { public Account getAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return null; } if (unlocksTimeouts.containsKey(addr)) { long ending = unlocksTimeouts.get(addr); long time = System.currentTimeMillis(); if (ending < time) { unlocksTimeouts.remove(addr); accounts.remove(addr); return null; } } return new Account(ECKey.fromPrivate(accounts.get(addr))); } } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }
@Test public void getUnknownAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Account account = wallet.getAccount(addr); Assert.assertNull(account); }
Wallet { public byte[] addAccountWithPrivateKey(byte[] privateKeyBytes) { Account account = new Account(ECKey.fromPrivate(privateKeyBytes)); synchronized (accessLock) { RskAddress addr = addAccount(account); if (!this.initialAccounts.contains(addr)) { this.initialAccounts.add(addr); } return addr.getBytes(); } } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }
@Test public void addAccountWithPrivateKey() { Wallet wallet = WalletFactory.createWallet(); byte[] privateKeyBytes = Keccak256Helper.keccak256("seed".getBytes()); byte[] address = wallet.addAccountWithPrivateKey(privateKeyBytes); Assert.assertNotNull(address); byte[] calculatedAddress = ECKey.fromPrivate(Keccak256Helper.keccak256("seed".getBytes())).getAddress(); Assert.assertArrayEquals(calculatedAddress, address); List<byte[]> addresses = wallet.getAccountAddresses(); Assert.assertNotNull(addresses); Assert.assertFalse(addresses.isEmpty()); Assert.assertEquals(1, addresses.size()); byte[] addr = addresses.get(0); Assert.assertNotNull(addr); Assert.assertArrayEquals(address, addr); }
SnapshotManager { @VisibleForTesting public List<Long> getSnapshots() { return this.snapshots; } SnapshotManager( Blockchain blockchain, BlockStore blockStore, TransactionPool transactionPool, MinerServer minerServer); int takeSnapshot(); boolean resetSnapshots(); boolean revertToSnapshot(int snapshotId); @VisibleForTesting List<Long> getSnapshots(); }
@Test public void createWithNoSnapshot() { Assert.assertNotNull(manager.getSnapshots()); Assert.assertTrue(manager.getSnapshots().isEmpty()); }
SnapshotManager { public boolean revertToSnapshot(int snapshotId) { if (snapshotId <= 0 || snapshotId > this.snapshots.size()) { return false; } long newBestBlockNumber = this.snapshots.get(snapshotId - 1); this.snapshots = this.snapshots.stream().limit(snapshotId).collect(Collectors.toList()); long currentBestBlockNumber = blockchain.getBestBlock().getNumber(); if (newBestBlockNumber >= currentBestBlockNumber) { return true; } Block block = blockStore.getChainBlockByNumber(newBestBlockNumber); BlockDifficulty difficulty = blockStore.getTotalDifficultyForHash(block.getHash().getBytes()); blockchain.setStatus(block, difficulty); transactionPool.processBest(block); transactionPool.removeTransactions(transactionPool.getPendingTransactions()); transactionPool.removeTransactions(transactionPool.getQueuedTransactions()); for (long nb = blockchain.getBestBlock().getNumber() + 1; nb <= currentBestBlockNumber; nb++) { blockchain.removeBlocksByNumber(nb); } minerServer.buildBlockToMine(block, false); return true; } SnapshotManager( Blockchain blockchain, BlockStore blockStore, TransactionPool transactionPool, MinerServer minerServer); int takeSnapshot(); boolean resetSnapshots(); boolean revertToSnapshot(int snapshotId); @VisibleForTesting List<Long> getSnapshots(); }
@Test public void revertToNegativeSnapshot() { Assert.assertFalse(manager.revertToSnapshot(-1)); } @Test public void revertToNonExistentSnapshot() { Assert.assertFalse(manager.revertToSnapshot(0)); Assert.assertFalse(manager.revertToSnapshot(1)); Assert.assertFalse(manager.revertToSnapshot(10)); } @Test public void revertToSnapshot() { addBlocks(10); BlockChainStatus status = blockchain.getStatus(); int snapshotId = manager.takeSnapshot(); addBlocks(20); Assert.assertEquals(30, blockchain.getStatus().getBestBlockNumber()); Assert.assertTrue(manager.revertToSnapshot(snapshotId)); BlockChainStatus newStatus = blockchain.getStatus(); Assert.assertEquals(status.getBestBlockNumber(), newStatus.getBestBlockNumber()); Assert.assertEquals(status.getTotalDifficulty(), newStatus.getTotalDifficulty()); Assert.assertEquals(status.getBestBlock().getHash(), newStatus.getBestBlock().getHash()); for (int k = 11; k <= 30; k++) Assert.assertTrue(blockchain.getBlocksByNumber(k).isEmpty()); }
ReversibleTransactionExecutor { public ProgramResult executeTransaction( Block executionBlock, RskAddress coinbase, byte[] gasPrice, byte[] gasLimit, byte[] toAddress, byte[] value, byte[] data, RskAddress fromAddress) { return executeTransaction_workaround( repositoryLocator.snapshotAt(executionBlock.getHeader()), executionBlock, coinbase, gasPrice, gasLimit, toAddress, value, data, fromAddress ); } ReversibleTransactionExecutor( RepositoryLocator repositoryLocator, TransactionExecutorFactory transactionExecutorFactory); ProgramResult executeTransaction( Block executionBlock, RskAddress coinbase, byte[] gasPrice, byte[] gasLimit, byte[] toAddress, byte[] value, byte[] data, RskAddress fromAddress); @Deprecated ProgramResult executeTransaction_workaround( RepositorySnapshot snapshot, Block executionBlock, RskAddress coinbase, byte[] gasPrice, byte[] gasLimit, byte[] toAddress, byte[] value, byte[] data, RskAddress fromAddress); }
@Test public void executeTransactionHello() { TestContract hello = TestContract.hello(); CallTransaction.Function helloFn = hello.functions.get("hello"); RskAddress contractAddress = contractRunner.addContract(hello.runtimeBytecode); RskAddress from = TestUtils.randomAddress(); byte[] gasPrice = Hex.decode("00"); byte[] value = Hex.decode("00"); byte[] gasLimit = Hex.decode("f424"); Block bestBlock = factory.getBlockchain().getBestBlock(); ProgramResult result = reversibleTransactionExecutor.executeTransaction( bestBlock, bestBlock.getCoinbase(), gasPrice, gasLimit, contractAddress.getBytes(), value, helloFn.encode(), from ); Assert.assertNull(result.getException()); Assert.assertArrayEquals( new String[]{"chinchilla"}, helloFn.decodeResult(result.getHReturn())); } @Test public void executeTransactionGreeterOtherSender() { TestContract greeter = TestContract.greeter(); CallTransaction.Function greeterFn = greeter.functions.get("greet"); RskAddress contractAddress = contractRunner.addContract(greeter.runtimeBytecode); RskAddress from = new RskAddress("0000000000000000000000000000000000000023"); byte[] gasPrice = Hex.decode("00"); byte[] value = Hex.decode("00"); byte[] gasLimit = Hex.decode("f424"); Block bestBlock = factory.getBlockchain().getBestBlock(); ProgramResult result = reversibleTransactionExecutor.executeTransaction( bestBlock, bestBlock.getCoinbase(), gasPrice, gasLimit, contractAddress.getBytes(), value, greeterFn.encode("greet me"), from ); Assert.assertTrue(result.isRevert()); } @Test public void executeTransactionCountCallsMultipleTimes() { TestContract countcalls = TestContract.countcalls(); CallTransaction.Function callsFn = countcalls.functions.get("calls"); RskAddress contractAddress = contractRunner.addContract(countcalls.runtimeBytecode); RskAddress from = new RskAddress("0000000000000000000000000000000000000023"); byte[] gasPrice = Hex.decode("00"); byte[] value = Hex.decode("00"); byte[] gasLimit = Hex.decode("f424"); Block bestBlock = factory.getBlockchain().getBestBlock(); ProgramResult result = reversibleTransactionExecutor.executeTransaction( bestBlock, bestBlock.getCoinbase(), gasPrice, gasLimit, contractAddress.getBytes(), value, callsFn.encodeSignature(), from ); Assert.assertNull(result.getException()); Assert.assertArrayEquals( new String[]{"calls: 1"}, callsFn.decodeResult(result.getHReturn())); ProgramResult result2 = reversibleTransactionExecutor.executeTransaction( bestBlock, bestBlock.getCoinbase(), gasPrice, gasLimit, contractAddress.getBytes(), value, callsFn.encodeSignature(), from ); Assert.assertNull(result2.getException()); Assert.assertArrayEquals( new String[]{"calls: 1"}, callsFn.decodeResult(result2.getHReturn())); }
ConsensusValidationMainchainViewImpl implements ConsensusValidationMainchainView { @Override public synchronized List<BlockHeader> get(Keccak256 startingHashToGetMainchainFrom, int height) { List<BlockHeader> headers = new ArrayList<>(); Keccak256 currentHash = startingHashToGetMainchainFrom; for(int i = 0; i < height; i++) { Block block = blockStore.getBlockByHash(currentHash.getBytes()); BlockHeader header; if (block != null) { header = block.getHeader(); } else { if(pendingHeadersByHash == null) { logger.error("Pending headers by hash has not been set."); return new ArrayList<>(); } header = pendingHeadersByHash.get(currentHash); } if(header == null) { return new ArrayList<>(); } headers.add(header); currentHash = header.getParentHash(); } return headers; } ConsensusValidationMainchainViewImpl(BlockStore blockStore); void setPendingHeaders(Map<Keccak256, BlockHeader> pendingHeadersByHash); @Override synchronized List<BlockHeader> get(Keccak256 startingHashToGetMainchainFrom, int height); }
@Test public void getWithHeightZeroReturnsEmpty() { BlockStore blockStore = mock(BlockStore.class); ConsensusValidationMainchainView view = new ConsensusValidationMainchainViewImpl(blockStore); List<BlockHeader> result = view.get(new Keccak256(getRandomHash()), 0); assertNotNull(result); assertThat(result.size(), is(0)); } @Test public void getThatFindsAllBlocksOnBlockStore() { BlockStore blockStore = createBlockStore(10); ConsensusValidationMainchainView view = new ConsensusValidationMainchainViewImpl(blockStore); Block bestBlock = blockStore.getBestBlock(); List<BlockHeader> result = view.get(bestBlock.getHash(), 5); assertNotNull(result); assertThat(result.size(), is(5)); assertThat(result.get(0).getHash(), is(bestBlock.getHash())); byte[] bestBlockParentHash = bestBlock.getParentHash().getBytes(); assertThat(result.get(1).getHash(), is(blockStore.getBlockByHash(bestBlockParentHash).getHash())); byte[] blockOneParentHash = result.get(1).getParentHash().getBytes(); assertThat(result.get(2).getHash(), is(blockStore.getBlockByHash(blockOneParentHash).getHash())); byte[] blockTwoParentHash = result.get(2).getParentHash().getBytes(); assertThat(result.get(3).getHash(), is(blockStore.getBlockByHash(blockTwoParentHash).getHash())); byte[] blockThreeParentHash = result.get(3).getParentHash().getBytes(); assertThat(result.get(4).getHash(), is(blockStore.getBlockByHash(blockThreeParentHash).getHash())); } @Test public void getAllBlocksOnBlockStoreAreAllRequestedBlocks() { BlockStore blockStore = createBlockStore(5); ConsensusValidationMainchainView view = new ConsensusValidationMainchainViewImpl(blockStore); Block bestBlock = blockStore.getBestBlock(); List<BlockHeader> result = view.get(bestBlock.getHash(), 5); assertNotNull(result); assertThat(result.size(), is(5)); assertThat(result.get(0).getHash(), is(bestBlock.getHash())); byte[] bestBlockParentHash = bestBlock.getParentHash().getBytes(); assertThat(result.get(1).getHash(), is(blockStore.getBlockByHash(bestBlockParentHash).getHash())); byte[] blockOneParentHash = result.get(1).getParentHash().getBytes(); assertThat(result.get(2).getHash(), is(blockStore.getBlockByHash(blockOneParentHash).getHash())); byte[] blockTwoParentHash = result.get(2).getParentHash().getBytes(); assertThat(result.get(3).getHash(), is(blockStore.getBlockByHash(blockTwoParentHash).getHash())); byte[] blockThreeParentHash = result.get(3).getParentHash().getBytes(); assertThat(result.get(4).getHash(), is(blockStore.getBlockByHash(blockThreeParentHash).getHash())); }
BlockchainBranchComparator { public BlockFork calculateFork(Block fromBlock, Block toBlock) { List<Block> oldBlocks = new LinkedList<>(); List<Block> newBlocks = new LinkedList<>(); Block oldBlock = fromBlock; Block newBlock = toBlock; if (oldBlock.isParentOf(newBlock)) { newBlocks.add(newBlock); return new BlockFork(oldBlock, oldBlocks, newBlocks); } while (newBlock.getNumber() > oldBlock.getNumber()) { newBlocks.add(0, newBlock); newBlock = blockStore.getBlockByHash(newBlock.getParentHash().getBytes()); } while (oldBlock.getNumber() > newBlock.getNumber()) { oldBlocks.add(0, oldBlock); oldBlock = blockStore.getBlockByHash(oldBlock.getParentHash().getBytes()); } while (!oldBlock.getHash().equals(newBlock.getHash())) { newBlocks.add(0, newBlock); newBlock = blockStore.getBlockByHash(newBlock.getParentHash().getBytes()); oldBlocks.add(0, oldBlock); oldBlock = blockStore.getBlockByHash(oldBlock.getParentHash().getBytes()); } return new BlockFork(oldBlock, oldBlocks, newBlocks); } BlockchainBranchComparator(BlockStore blockStore); BlockFork calculateFork(Block fromBlock, Block toBlock); }
@Test public void calculateParentChild() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block = blockGenerator.createChildBlock(genesis); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(block, TEST_DIFFICULTY, true); BlockchainBranchComparator comparator = new BlockchainBranchComparator(store); BlockFork fork = comparator.calculateFork(genesis, block); Assert.assertSame(genesis, fork.getCommonAncestor()); Assert.assertTrue(fork.getOldBlocks().isEmpty()); Assert.assertFalse(fork.getNewBlocks().isEmpty()); Assert.assertEquals(1, fork.getNewBlocks().size()); Assert.assertSame(block, fork.getNewBlocks().get(0)); } @Test public void calculateForkLengthTwo() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block parent = blockGenerator.createChildBlock(genesis); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(parent, TEST_DIFFICULTY, true); List<Block> oldBranch = makeChain(parent, 2, store, blockGenerator); List<Block> newBranch = makeChain(parent, 2, store, blockGenerator); BlockchainBranchComparator comparator = new BlockchainBranchComparator(store); BlockFork fork = comparator.calculateFork(oldBranch.get(1), newBranch.get(1)); Assert.assertEquals(parent.getHash(), fork.getCommonAncestor().getHash()); Assert.assertFalse(fork.getOldBlocks().isEmpty()); Assert.assertEquals(2, fork.getOldBlocks().size()); Assert.assertEquals(oldBranch.get(0).getHash(), fork.getOldBlocks().get(0).getHash()); Assert.assertEquals(oldBranch.get(1).getHash(), fork.getOldBlocks().get(1).getHash()); Assert.assertFalse(fork.getNewBlocks().isEmpty()); Assert.assertEquals(2, fork.getNewBlocks().size()); Assert.assertEquals(newBranch.get(0).getHash(), fork.getNewBlocks().get(0).getHash()); Assert.assertEquals(newBranch.get(1).getHash(), fork.getNewBlocks().get(1).getHash()); } @Test public void calculateForkLengthTwoOldThreeNew() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block parent = blockGenerator.createChildBlock(genesis); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(parent, TEST_DIFFICULTY, true); List<Block> oldBranch = makeChain(parent, 2, store, blockGenerator); List<Block> newBranch = makeChain(parent, 3, store, blockGenerator); BlockchainBranchComparator comparator = new BlockchainBranchComparator(store); BlockFork fork = comparator.calculateFork(oldBranch.get(1), newBranch.get(2)); Assert.assertEquals(parent.getHash(), fork.getCommonAncestor().getHash()); Assert.assertFalse(fork.getOldBlocks().isEmpty()); Assert.assertEquals(2, fork.getOldBlocks().size()); Assert.assertEquals(oldBranch.get(0).getHash(), fork.getOldBlocks().get(0).getHash()); Assert.assertEquals(oldBranch.get(1).getHash(), fork.getOldBlocks().get(1).getHash()); Assert.assertFalse(fork.getNewBlocks().isEmpty()); Assert.assertEquals(3, fork.getNewBlocks().size()); Assert.assertEquals(newBranch.get(0).getHash(), fork.getNewBlocks().get(0).getHash()); Assert.assertEquals(newBranch.get(1).getHash(), fork.getNewBlocks().get(1).getHash()); Assert.assertEquals(newBranch.get(2).getHash(), fork.getNewBlocks().get(2).getHash()); } @Test public void calculateForkLengthThreeOldTwoNew() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block parent = blockGenerator.createChildBlock(genesis); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(parent, TEST_DIFFICULTY, true); List<Block> oldBranch = makeChain(parent, 3, store, blockGenerator); List<Block> newBranch = makeChain(parent, 2, store, blockGenerator); BlockchainBranchComparator comparator = new BlockchainBranchComparator(store); BlockFork fork = comparator.calculateFork(oldBranch.get(2), newBranch.get(1)); Assert.assertEquals(parent.getHash(), fork.getCommonAncestor().getHash()); Assert.assertFalse(fork.getOldBlocks().isEmpty()); Assert.assertEquals(3, fork.getOldBlocks().size()); Assert.assertEquals(oldBranch.get(0).getHash(), fork.getOldBlocks().get(0).getHash()); Assert.assertEquals(oldBranch.get(1).getHash(), fork.getOldBlocks().get(1).getHash()); Assert.assertEquals(oldBranch.get(2).getHash(), fork.getOldBlocks().get(2).getHash()); Assert.assertFalse(fork.getNewBlocks().isEmpty()); Assert.assertEquals(2, fork.getNewBlocks().size()); Assert.assertEquals(newBranch.get(0).getHash(), fork.getNewBlocks().get(0).getHash()); Assert.assertEquals(newBranch.get(1).getHash(), fork.getNewBlocks().get(1).getHash()); }
FamilyUtils { public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); } static Set<Keccak256> getAncestors(BlockStore blockStore, Block block, int limitNum); static Set<Keccak256> getAncestors(BlockStore blockStore, long blockNumber, Keccak256 parentHash, int limitNum); static Set<Keccak256> getUsedUncles(BlockStore blockStore, Block block, int limitNum); static Set<Keccak256> getUsedUncles(BlockStore blockStore, long blockNumber, Keccak256 parentHash, int limitNum); static List<BlockHeader> getUnclesHeaders(BlockStore store, Block block, int levels); static List<BlockHeader> getUnclesHeaders(@Nonnull BlockStore store, long blockNumber, Keccak256 parentHash, int levels); static Set<Keccak256> getUncles(BlockStore store, Block block, int levels); static Set<Keccak256> getUncles(BlockStore store, long blockNumber, Keccak256 parentHash, int levels); static Set<Keccak256> getFamily(BlockStore store, Block block, int levels); static Set<Keccak256> getFamily(BlockStore store, long blockNumber, Keccak256 parentHash, int levels); }
@Test public void getFamilyGetParent() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(block1, TEST_DIFFICULTY, true); Set<Keccak256> family = FamilyUtils.getFamily(store, block1, 6); Assert.assertNotNull(family); Assert.assertFalse(family.isEmpty()); Assert.assertEquals(1, family.size()); Assert.assertTrue(family.contains(genesis.getHash())); } @Test public void getEmptyFamilyForGenesis() { BlockStore store = createBlockStore(); Block genesis = new BlockGenerator().getGenesisBlock(); store.saveBlock(genesis, TEST_DIFFICULTY, true); Set<Keccak256> family = FamilyUtils.getFamily(store, genesis, 6); Assert.assertNotNull(family); Assert.assertTrue(family.isEmpty()); } @Test public void getFamilyGetAncestorsUpToLevel() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); Block block2 = blockGenerator.createChildBlock(block1); Block block3 = blockGenerator.createChildBlock(block2); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(block1, TEST_DIFFICULTY, true); store.saveBlock(block2, TEST_DIFFICULTY, true); store.saveBlock(block3, TEST_DIFFICULTY, true); Set<Keccak256> family = FamilyUtils.getFamily(store, block3, 2); Assert.assertNotNull(family); Assert.assertFalse(family.isEmpty()); Assert.assertEquals(2, family.size()); Assert.assertFalse(family.contains(genesis.getHash())); Assert.assertFalse(family.contains(block3.getHash())); Assert.assertTrue(family.contains(block1.getHash())); Assert.assertTrue(family.contains(block2.getHash())); } @Test public void getFamilyGetAncestorsWithUncles() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); Block uncle11 = blockGenerator.createChildBlock(genesis); Block uncle12 = blockGenerator.createChildBlock(genesis); Block block2 = blockGenerator.createChildBlock(block1); Block uncle21 = blockGenerator.createChildBlock(block1); Block uncle22 = blockGenerator.createChildBlock(block1); Block block3 = blockGenerator.createChildBlock(block2); Block uncle31 = blockGenerator.createChildBlock(block2); Block uncle32 = blockGenerator.createChildBlock(block2); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(block1, TEST_DIFFICULTY, true); store.saveBlock(uncle11, TEST_DIFFICULTY, false); store.saveBlock(uncle12, TEST_DIFFICULTY, false); store.saveBlock(block2, TEST_DIFFICULTY, true); store.saveBlock(uncle21, TEST_DIFFICULTY, false); store.saveBlock(uncle22, TEST_DIFFICULTY, false); store.saveBlock(block3, TEST_DIFFICULTY, true); store.saveBlock(uncle31, TEST_DIFFICULTY, false); store.saveBlock(uncle32, TEST_DIFFICULTY, false); Set<Keccak256> family = FamilyUtils.getFamily(store, block3, 2); Assert.assertNotNull(family); Assert.assertFalse(family.isEmpty()); Assert.assertEquals(4, family.size()); Assert.assertFalse(family.contains(genesis.getHash())); Assert.assertTrue(family.contains(block1.getHash())); Assert.assertFalse(family.contains(uncle11.getHash())); Assert.assertFalse(family.contains(uncle12.getHash())); Assert.assertTrue(family.contains(block2.getHash())); Assert.assertTrue(family.contains(uncle21.getHash())); Assert.assertTrue(family.contains(uncle22.getHash())); Assert.assertFalse(family.contains(block3.getHash())); Assert.assertFalse(family.contains(uncle31.getHash())); Assert.assertFalse(family.contains(uncle32.getHash())); family = FamilyUtils.getFamily(store, block3, 3); Assert.assertNotNull(family); Assert.assertFalse(family.isEmpty()); Assert.assertEquals(7, family.size()); Assert.assertTrue(family.contains(genesis.getHash())); Assert.assertTrue(family.contains(block1.getHash())); Assert.assertTrue(family.contains(uncle11.getHash())); Assert.assertTrue(family.contains(uncle12.getHash())); Assert.assertTrue(family.contains(block2.getHash())); Assert.assertTrue(family.contains(uncle21.getHash())); Assert.assertTrue(family.contains(uncle22.getHash())); Assert.assertFalse(family.contains(block3.getHash())); Assert.assertFalse(family.contains(uncle31.getHash())); Assert.assertFalse(family.contains(uncle32.getHash())); }
FamilyUtils { public static List<BlockHeader> getUnclesHeaders(BlockStore store, Block block, int levels) { return getUnclesHeaders(store, block.getNumber(), block.getParentHash(), levels); } static Set<Keccak256> getAncestors(BlockStore blockStore, Block block, int limitNum); static Set<Keccak256> getAncestors(BlockStore blockStore, long blockNumber, Keccak256 parentHash, int limitNum); static Set<Keccak256> getUsedUncles(BlockStore blockStore, Block block, int limitNum); static Set<Keccak256> getUsedUncles(BlockStore blockStore, long blockNumber, Keccak256 parentHash, int limitNum); static List<BlockHeader> getUnclesHeaders(BlockStore store, Block block, int levels); static List<BlockHeader> getUnclesHeaders(@Nonnull BlockStore store, long blockNumber, Keccak256 parentHash, int levels); static Set<Keccak256> getUncles(BlockStore store, Block block, int levels); static Set<Keccak256> getUncles(BlockStore store, long blockNumber, Keccak256 parentHash, int levels); static Set<Keccak256> getFamily(BlockStore store, Block block, int levels); static Set<Keccak256> getFamily(BlockStore store, long blockNumber, Keccak256 parentHash, int levels); }
@Test public void getUnclesHeaders() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); Block uncle11 = blockGenerator.createChildBlock(genesis); Block uncle111 = blockGenerator.createChildBlock(uncle11); Block uncle12 = blockGenerator.createChildBlock(genesis); Block uncle121 = blockGenerator.createChildBlock(uncle12); Block block2 = blockGenerator.createChildBlock(block1); Block uncle21 = blockGenerator.createChildBlock(block1); Block uncle22 = blockGenerator.createChildBlock(block1); Block block3 = blockGenerator.createChildBlock(block2); Block uncle31 = blockGenerator.createChildBlock(block2); Block uncle32 = blockGenerator.createChildBlock(block2); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(block1, TEST_DIFFICULTY, true); store.saveBlock(uncle11, TEST_DIFFICULTY, false); store.saveBlock(uncle12, TEST_DIFFICULTY, false); store.saveBlock(uncle111, TEST_DIFFICULTY, false); store.saveBlock(uncle121, TEST_DIFFICULTY, false); store.saveBlock(block2, TEST_DIFFICULTY, true); store.saveBlock(uncle21, TEST_DIFFICULTY, false); store.saveBlock(uncle22, TEST_DIFFICULTY, false); store.saveBlock(block3, TEST_DIFFICULTY, true); store.saveBlock(uncle31, TEST_DIFFICULTY, false); store.saveBlock(uncle32, TEST_DIFFICULTY, false); List<BlockHeader> list = FamilyUtils.getUnclesHeaders(store, block3, 3); Assert.assertNotNull(list); Assert.assertFalse(list.isEmpty()); Assert.assertEquals(4, list.size()); Assert.assertTrue(containsHash(uncle11.getHash(), list)); Assert.assertTrue(containsHash(uncle12.getHash(), list)); Assert.assertTrue(containsHash(uncle21.getHash(), list)); Assert.assertTrue(containsHash(uncle22.getHash(), list)); }
FamilyUtils { public static Set<Keccak256> getUncles(BlockStore store, Block block, int levels) { return getUncles(store, block.getNumber(), block.getParentHash(), levels); } static Set<Keccak256> getAncestors(BlockStore blockStore, Block block, int limitNum); static Set<Keccak256> getAncestors(BlockStore blockStore, long blockNumber, Keccak256 parentHash, int limitNum); static Set<Keccak256> getUsedUncles(BlockStore blockStore, Block block, int limitNum); static Set<Keccak256> getUsedUncles(BlockStore blockStore, long blockNumber, Keccak256 parentHash, int limitNum); static List<BlockHeader> getUnclesHeaders(BlockStore store, Block block, int levels); static List<BlockHeader> getUnclesHeaders(@Nonnull BlockStore store, long blockNumber, Keccak256 parentHash, int levels); static Set<Keccak256> getUncles(BlockStore store, Block block, int levels); static Set<Keccak256> getUncles(BlockStore store, long blockNumber, Keccak256 parentHash, int levels); static Set<Keccak256> getFamily(BlockStore store, Block block, int levels); static Set<Keccak256> getFamily(BlockStore store, long blockNumber, Keccak256 parentHash, int levels); }
@Test public void getUncles() { BlockStore store = createBlockStore(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); Block block1 = blockGenerator.createChildBlock(genesis); Block uncle11 = blockGenerator.createChildBlock(genesis); Block uncle12 = blockGenerator.createChildBlock(genesis); Block block2 = blockGenerator.createChildBlock(block1); Block uncle21 = blockGenerator.createChildBlock(block1); Block uncle22 = blockGenerator.createChildBlock(block1); Block block3 = blockGenerator.createChildBlock(block2); Block uncle31 = blockGenerator.createChildBlock(block2); Block uncle32 = blockGenerator.createChildBlock(block2); store.saveBlock(genesis, TEST_DIFFICULTY, true); store.saveBlock(block1, TEST_DIFFICULTY, true); store.saveBlock(uncle11, TEST_DIFFICULTY, false); store.saveBlock(uncle12, TEST_DIFFICULTY, false); store.saveBlock(block2, TEST_DIFFICULTY, true); store.saveBlock(uncle21, TEST_DIFFICULTY, false); store.saveBlock(uncle22, TEST_DIFFICULTY, false); store.saveBlock(block3, TEST_DIFFICULTY, true); store.saveBlock(uncle31, TEST_DIFFICULTY, false); store.saveBlock(uncle32, TEST_DIFFICULTY, false); Set<Keccak256> family = FamilyUtils.getUncles(store, block3, 3); Assert.assertNotNull(family); Assert.assertFalse(family.isEmpty()); Assert.assertEquals(4, family.size()); Assert.assertFalse(family.contains(genesis.getHash())); Assert.assertFalse(family.contains(block1.getHash())); Assert.assertTrue(family.contains(uncle11.getHash())); Assert.assertTrue(family.contains(uncle12.getHash())); Assert.assertFalse(family.contains(block2.getHash())); Assert.assertTrue(family.contains(uncle21.getHash())); Assert.assertTrue(family.contains(uncle22.getHash())); Assert.assertFalse(family.contains(block3.getHash())); Assert.assertFalse(family.contains(uncle31.getHash())); Assert.assertFalse(family.contains(uncle32.getHash())); }
GarbageCollector implements InternalService { private void collect(long untilBlock) { BlockHeader untilHeader = blockStore.getChainBlockByNumber(untilBlock).getHeader(); multiTrieStore.collect(repositoryLocator.snapshotAt(untilHeader).getRoot()); } GarbageCollector(CompositeEthereumListener emitter, int blocksPerEpoch, int numberOfEpochs, MultiTrieStore multiTrieStore, BlockStore blockStore, RepositoryLocator repositoryLocator); @Override void start(); @Override void stop(); }
@Test public void collectsOnBlocksPerEpochModulo() { for (int i = 100; i < 105; i++) { Block block = block(i); listener.onBestBlock(block, null); } verify(multiTrieStore, never()).collect(any()); byte[] stateRoot = new byte[] {0x42, 0x43, 0x02}; withSnapshotStateRootAtBlockNumber(85, stateRoot); Block block = block(105); listener.onBestBlock(block, null); verify(multiTrieStore).collect(stateRoot); } @Test public void collectsOnBlocksPerEpochModuloAndMinimumOfStatesToKeep() { for (int i = 0; i < 21; i++) { Block block = block(i); listener.onBestBlock(block, null); } verify(multiTrieStore, never()).collect(any()); byte[] stateRoot = new byte[] {0x42, 0x43, 0x02}; withSnapshotStateRootAtBlockNumber(1, stateRoot); Block block = block(21); listener.onBestBlock(block, null); verify(multiTrieStore).collect(stateRoot); }
RLP { public static byte[] encodeLength(int length, int offset) { if (length < SIZE_THRESHOLD) { byte firstByte = (byte) (length + offset); return new byte[]{firstByte}; } else if (length < MAX_ITEM_LENGTH) { byte[] binaryLength; if (length > 0xFF) { binaryLength = intToBytesNoLeadZeroes(length); } else { binaryLength = new byte[]{(byte) length}; } byte firstByte = (byte) (binaryLength.length + offset + SIZE_THRESHOLD - 1); return concatenate(new byte[]{firstByte}, binaryLength); } else { throw new RuntimeException("Input too long"); } } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int index); static byte[] decodeIP4Bytes(byte[] data, int index); static int getFirstListElement(byte[] payload, int pos); static int getNextElementIndex(byte[] payload, int pos); static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, Queue<Integer> index); @Nonnull static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData); static RLPElement decodeFirstElement(@CheckForNull byte[] msgData, int position); static RLPList decodeList(byte[] msgData); @Nullable static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos); @Nonnull static RskAddress parseRskAddress(@Nullable byte[] bytes); @Nonnull static Coin parseCoin(@Nullable byte[] bytes); @Nullable static Coin parseCoinNonNullZero(byte[] bytes); @Nullable static Coin parseSignedCoinNonNullZero(byte[] bytes); static Coin parseCoinNullZero(@Nullable byte[] bytes); @Nullable static BlockDifficulty parseBlockDifficulty(@Nullable byte[] bytes); static byte[] encode(Object input); static byte[] encodeLength(int length, int offset); static byte[] encodeByte(byte singleByte); static byte[] encodeShort(short singleShort); static byte[] encodeInt(int singleInt); static byte[] encodeString(String srcString); static byte[] encodeBigInteger(BigInteger srcBigInteger); static byte[] encodeRskAddress(RskAddress addr); static byte[] encodeCoin(@Nullable Coin coin); static byte[] encodeCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeSignedCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeCoinNullZero(Coin coin); static byte[] encodeBlockDifficulty(BlockDifficulty difficulty); static byte[] encodeElement(@Nullable byte[] srcData); static byte[] encodeListHeader(int size); static byte[] encodeSet(Set<ByteArrayWrapper> data); static byte[] encodeList(byte[]... elements); static byte[] encodedEmptyList(); static byte[] encodedEmptyByteArray(); }
@Test public void testEncodeLength() { int length = 1; int offset = 128; byte[] encodedLength = encodeLength(length, offset); String expected = "81"; assertEquals(expected, ByteUtil.toHexString(encodedLength)); length = 56; offset = 192; encodedLength = encodeLength(length, offset); expected = "f838"; assertEquals(expected, ByteUtil.toHexString(encodedLength)); } @Test @Ignore public void unsupportedLength() { int length = 56; int offset = 192; byte[] encodedLength; double maxLength = Math.pow(256, 8); try { encodedLength = encodeLength((int) maxLength, offset); System.out.println("length: " + length + ", offset: " + offset + ", encoded: " + Arrays.toString(encodedLength)); fail("Expecting RuntimeException: 'Input too long'"); } catch (RuntimeException e) { } }
BlockExecutor { @VisibleForTesting public BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs) { return execute(block, parent, discardInvalidTxs, false); } BlockExecutor( ActivationConfig activationConfig, RepositoryLocator repositoryLocator, StateRootHandler stateRootHandler, TransactionExecutorFactory transactionExecutorFactory); BlockResult executeAndFill(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillAll(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillReal(Block block, BlockHeader parent); @VisibleForTesting boolean executeAndValidate(Block block, BlockHeader parent); boolean validate(Block block, BlockResult result); @VisibleForTesting BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs); BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); void traceBlock( ProgramTraceProcessor programTraceProcessor, int vmTraceOptions, Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); static void maintainPrecompiledContractStorageRoots(Repository track, ActivationConfig.ForBlock activations); @VisibleForTesting static byte[] calculateLogsBloom(List<TransactionReceipt> receipts); }
@Test public void executeBlockWithoutTransaction() { Block parent = blockchain.getBestBlock(); Block block = new BlockGenerator().createChildBlock(parent); BlockResult result = executor.execute(block, parent.getHeader(), false); Assert.assertNotNull(result); Assert.assertNotNull(result.getTransactionReceipts()); Assert.assertTrue(result.getTransactionReceipts().isEmpty()); Assert.assertArrayEquals(repository.getRoot(), parent.getStateRoot()); Assert.assertArrayEquals(repository.getRoot(), result.getFinalState().getHash().getBytes()); } @Test public void executeBlockWithTxThatMakesBlockInvalidSenderHasNoBalance() { TrieStore trieStore = new TrieStoreImpl(new HashMapDB()); Repository repository = new MutableRepository(new MutableTrieImpl(trieStore, new Trie(trieStore))); Repository track = repository.startTracking(); Account account = createAccount("acctest1", track, Coin.valueOf(30000)); Account account2 = createAccount("acctest2", track, Coin.valueOf(10L)); Account account3 = createAccount("acctest3", track, Coin.ZERO); track.commit(); Assert.assertFalse(Arrays.equals(EMPTY_TRIE_HASH, repository.getRoot())); BlockExecutor executor = buildBlockExecutor(trieStore); Transaction tx = createTransaction( account, account2, BigInteger.TEN, repository.getNonce(account.getAddress()) ); Transaction tx2 = createTransaction( account3, account2, BigInteger.TEN, repository.getNonce(account3.getAddress()) ); List<Transaction> txs = new ArrayList<>(); txs.add(tx); txs.add(tx2); List<BlockHeader> uncles = new ArrayList<>(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); genesis.setStateRoot(repository.getRoot()); Block block = blockGenerator.createChildBlock(genesis, txs, uncles, 1, null); BlockResult result = executor.execute(block, genesis.getHeader(), false); Assert.assertSame(BlockResult.INTERRUPTED_EXECUTION_BLOCK_RESULT, result); }
BlockExecutor { public BlockResult executeAndFill(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, true, false); fill(block, result); return result; } BlockExecutor( ActivationConfig activationConfig, RepositoryLocator repositoryLocator, StateRootHandler stateRootHandler, TransactionExecutorFactory transactionExecutorFactory); BlockResult executeAndFill(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillAll(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillReal(Block block, BlockHeader parent); @VisibleForTesting boolean executeAndValidate(Block block, BlockHeader parent); boolean validate(Block block, BlockResult result); @VisibleForTesting BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs); BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); void traceBlock( ProgramTraceProcessor programTraceProcessor, int vmTraceOptions, Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); static void maintainPrecompiledContractStorageRoots(Repository track, ActivationConfig.ForBlock activations); @VisibleForTesting static byte[] calculateLogsBloom(List<TransactionReceipt> receipts); }
@Test public void executeAndFillBlockWithTxToExcludeBecauseSenderHasNoBalance() { TrieStore trieStore = new TrieStoreImpl(new HashMapDB()); Repository repository = new MutableRepository(new MutableTrieImpl(trieStore, new Trie(trieStore))); Repository track = repository.startTracking(); Account account = createAccount("acctest1", track, Coin.valueOf(30000)); Account account2 = createAccount("acctest2", track, Coin.valueOf(10L)); Account account3 = createAccount("acctest3", track, Coin.ZERO); track.commit(); Assert.assertFalse(Arrays.equals(EMPTY_TRIE_HASH, repository.getRoot())); BlockExecutor executor = buildBlockExecutor(trieStore); Transaction tx = createTransaction( account, account2, BigInteger.TEN, repository.getNonce(account.getAddress()) ); Transaction tx2 = createTransaction( account3, account2, BigInteger.TEN, repository.getNonce(account3.getAddress()) ); List<Transaction> txs = new ArrayList<>(); txs.add(tx); txs.add(tx2); List<BlockHeader> uncles = new ArrayList<>(); BlockGenerator blockGenerator = new BlockGenerator(); Block genesis = blockGenerator.getGenesisBlock(); genesis.setStateRoot(repository.getRoot()); Block block = blockGenerator.createChildBlock(genesis, txs, uncles, 1, null); executor.executeAndFill(block, genesis.getHeader()); Assert.assertEquals(1, block.getTransactionsList().size()); Assert.assertEquals(tx, block.getTransactionsList().get(0)); Assert.assertArrayEquals( calculateTxTrieRoot(Collections.singletonList(tx), block.getNumber()), block.getTxTrieRoot() ); Assert.assertEquals(3141592, new BigInteger(1, block.getGasLimit()).longValue()); }
BlockExecutor { @VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); } BlockExecutor( ActivationConfig activationConfig, RepositoryLocator repositoryLocator, StateRootHandler stateRootHandler, TransactionExecutorFactory transactionExecutorFactory); BlockResult executeAndFill(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillAll(Block block, BlockHeader parent); @VisibleForTesting void executeAndFillReal(Block block, BlockHeader parent); @VisibleForTesting boolean executeAndValidate(Block block, BlockHeader parent); boolean validate(Block block, BlockResult result); @VisibleForTesting BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs); BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); void traceBlock( ProgramTraceProcessor programTraceProcessor, int vmTraceOptions, Block block, BlockHeader parent, boolean discardInvalidTxs, boolean ignoreReadyToExecute); static void maintainPrecompiledContractStorageRoots(Repository track, ActivationConfig.ForBlock activations); @VisibleForTesting static byte[] calculateLogsBloom(List<TransactionReceipt> receipts); }
@Test public void validateBlock() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); Assert.assertTrue(executor.executeAndValidate(block, parent.getHeader())); } @Test public void invalidBlockBadStateRoot() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); byte[] stateRoot = block.getStateRoot(); stateRoot[0] = (byte) ((stateRoot[0] + 1) % 256); Assert.assertFalse(executor.executeAndValidate(block, parent.getHeader())); } @Test public void invalidBlockBadReceiptsRoot() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); byte[] receiptsRoot = block.getReceiptsRoot(); receiptsRoot[0] = (byte) ((receiptsRoot[0] + 1) % 256); Assert.assertFalse(executor.executeAndValidate(block, parent.getHeader())); } @Test public void invalidBlockBadGasUsed() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); block.getHeader().setGasUsed(0); Assert.assertFalse(executor.executeAndValidate(block, parent.getHeader())); } @Test public void invalidBlockBadPaidFees() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); block.getHeader().setPaidFees(Coin.ZERO); Assert.assertFalse(executor.executeAndValidate(block, parent.getHeader())); } @Test public void invalidBlockBadLogsBloom() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); byte[] logBloom = block.getLogBloom(); logBloom[0] = (byte) ((logBloom[0] + 1) % 256); Assert.assertFalse(executor.executeAndValidate(block, parent.getHeader())); }
BlockHashesHelper { public static Trie calculateReceiptsTrieRootFor(List<TransactionReceipt> receipts) { Trie receiptsTrie = new Trie(); for (int i = 0; i < receipts.size(); i++) { receiptsTrie = receiptsTrie.put(RLP.encodeInt(i), receipts.get(i).getEncoded()); } return receiptsTrie; } private BlockHashesHelper(); static byte[] calculateReceiptsTrieRoot(List<TransactionReceipt> receipts, boolean isRskip126Enabled); static Trie calculateReceiptsTrieRootFor(List<TransactionReceipt> receipts); static List<Trie> calculateReceiptsTrieRootFor(Block block, ReceiptStore receiptStore, Keccak256 txHash); static byte[] getTxTrieRoot(List<Transaction> transactions, boolean isRskip126Enabled); }
@Test public void calculateReceiptsTrieRootForOK() { World world = new World(); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx1 = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); Account acc3 = new AccountBuilder(world).name("acc3").balance(Coin.valueOf(2000000)).build(); Account acc4 = new AccountBuilder().name("acc4").build(); Transaction tx2 = new TransactionBuilder().sender(acc3).receiver(acc4).value(BigInteger.valueOf(500000)).build(); Account acc5 = new AccountBuilder(world).name("acc5").balance(Coin.valueOf(2000000)).build(); Account acc6 = new AccountBuilder().name("acc6").build(); Transaction tx3 = new TransactionBuilder().sender(acc5).receiver(acc6).value(BigInteger.valueOf(800000)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx1); txs.add(tx2); txs.add(tx3); Block block = mock(Block.class); when(block.getTransactionsList()).thenReturn(txs); when(block.getHash()).thenReturn(new Keccak256(Hex.decode("0246c165ac839255aab76c1bc3df7842673ee3673e20dd908bba60862cf41326"))); ReceiptStore receiptStore = mock(ReceiptStore.class); byte[] rskBlockHash = new byte[]{0x2}; when(receiptStore.get(tx1.getHash(), block.getHash())).thenReturn(Optional.of(new TransactionInfo(new TransactionReceipt(), rskBlockHash, 0))); when(receiptStore.get(tx2.getHash(), block.getHash())).thenReturn(Optional.of(new TransactionInfo(new TransactionReceipt(), rskBlockHash, 0))); when(receiptStore.get(tx3.getHash(), block.getHash())).thenReturn(Optional.of(new TransactionInfo(new TransactionReceipt(), rskBlockHash, 0))); List<Trie> trie = BlockHashesHelper.calculateReceiptsTrieRootFor(block, receiptStore, tx1.getHash()); assertNotNull(trie); assertEquals(trie.size(), 2); } @Test(expected = BlockHashesHelperException.class) public void calculateReceiptsTrieRootForException() { World world = new 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 block = mock(Block.class); when(block.getTransactionsList()).thenReturn(txs); when(block.getHash()).thenReturn(new Keccak256(Hex.decode("0246c165ac839255aab76c1bc3df7842673ee3673e20dd908bba60862cf41326"))); ReceiptStore receiptStore = mock(ReceiptStore.class); Keccak256 hashTx = tx.getHash(); List<Trie> trie = BlockHashesHelper.calculateReceiptsTrieRootFor(block, receiptStore, hashTx); } @Test public void calculateReceiptsTrieRootForDifferentTxHash() { World world = new World(); Account acc1 = new AccountBuilder(world).name("acc1").balance(Coin.valueOf(2000000)).build(); Account acc2 = new AccountBuilder().name("acc2").build(); Transaction tx1 = new TransactionBuilder().sender(acc1).receiver(acc2).value(BigInteger.valueOf(1000000)).build(); Account acc3 = new AccountBuilder(world).name("acc3").balance(Coin.valueOf(2000000)).build(); Account acc4 = new AccountBuilder().name("acc4").build(); Transaction tx2 = new TransactionBuilder().sender(acc3).receiver(acc4).value(BigInteger.valueOf(500000)).build(); Account acc5 = new AccountBuilder(world).name("acc5").balance(Coin.valueOf(2000000)).build(); Account acc6 = new AccountBuilder().name("acc6").build(); Transaction tx3 = new TransactionBuilder().sender(acc5).receiver(acc6).value(BigInteger.valueOf(800000)).build(); List<Transaction> txs = new ArrayList<>(); txs.add(tx1); txs.add(tx2); Block block = mock(Block.class); when(block.getTransactionsList()).thenReturn(txs); when(block.getHash()).thenReturn(new Keccak256(Hex.decode("0246c165ac839255aab76c1bc3df7842673ee3673e20dd908bba60862cf41326"))); ReceiptStore receiptStore = mock(ReceiptStore.class); byte[] rskBlockHash = new byte[]{0x2}; when(receiptStore.get(tx1.getHash(), block.getHash())).thenReturn(Optional.of(new TransactionInfo(new TransactionReceipt(), rskBlockHash, 0))); when(receiptStore.get(tx2.getHash(), block.getHash())).thenReturn(Optional.of(new TransactionInfo(new TransactionReceipt(), rskBlockHash, 0))); when(receiptStore.get(tx3.getHash(), block.getHash())).thenReturn(Optional.of(new TransactionInfo(new TransactionReceipt(), rskBlockHash, 0))); List<Trie> trie = BlockHashesHelper.calculateReceiptsTrieRootFor(block, receiptStore, tx3.getHash()); assertNull(trie); }
BlockChainImpl implements Blockchain { private void onBestBlock(Block block, BlockResult result) { if (result != null && listener != null){ listener.onBestBlock(block, result.getTransactionReceipts()); } } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }
@Test public void onBestBlockTest() { Block genesis = blockChain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); Block block1 = blockGenerator.createChildBlock(genesis,0,2l); Block block1b = blockGenerator.createChildBlock(genesis,0,1l); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block1)); Assert.assertEquals(block1.getHash(), listener.getBestBlock().getHash()); Assert.assertEquals(listener.getBestBlock().getHash(), listener.getLatestBlock().getHash()); Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, blockChain.tryToConnect(block1b)); Assert.assertNotEquals(listener.getBestBlock().getHash(), listener.getLatestBlock().getHash()); Assert.assertEquals(block1.getHash(), listener.getBestBlock().getHash()); Assert.assertEquals(block1b.getHash(), listener.getLatestBlock().getHash()); }
BlockChainImpl implements Blockchain { @Override public ImportResult tryToConnect(Block block) { this.lock.readLock().lock(); try { if (block == null) { return ImportResult.INVALID_BLOCK; } if (!block.isSealed()) { panicProcessor.panic("unsealedblock", String.format("Unsealed block %s %s", block.getNumber(), block.getHash())); block.seal(); } try { org.slf4j.MDC.put("blockHash", block.getHash().toHexString()); org.slf4j.MDC.put("blockHeight", Long.toString(block.getNumber())); logger.trace("Try connect block hash: {}, number: {}", block.getPrintableHash(), block.getNumber()); synchronized (connectLock) { logger.trace("Start try connect"); long saveTime = System.nanoTime(); ImportResult result = internalTryToConnect(block); long totalTime = System.nanoTime() - saveTime; String timeInSeconds = FormatUtils.formatNanosecondsToSeconds(totalTime); if (BlockUtils.tooMuchProcessTime(totalTime)) { logger.warn("block: num: [{}] hash: [{}], processed after: [{}]seconds, result {}", block.getNumber(), block.getPrintableHash(), timeInSeconds, result); } else { logger.info("block: num: [{}] hash: [{}], processed after: [{}]seconds, result {}", block.getNumber(), block.getPrintableHash(), timeInSeconds, result); } return result; } } catch (Throwable t) { logger.error("Unexpected error: ", t); return ImportResult.INVALID_BLOCK; } finally { org.slf4j.MDC.remove("blockHash"); org.slf4j.MDC.remove("blockHeight"); } } finally { this.lock.readLock().unlock(); } } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }
@Test public void nullBlockAsInvalidBlock() { Assert.assertEquals(ImportResult.INVALID_BLOCK, blockChain.tryToConnect(null)); }
BlockChainImpl implements Blockchain { @Override public List<Block> getBlocksByNumber(long number) { return blockStore.getChainBlocksByNumber(number); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }
@Test public void getBlocksByNumber() { Block genesis = blockChain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); Block block1 = blockGenerator.createChildBlock(genesis,0,2); Block block1b = blockGenerator.createChildBlock(genesis,0,1); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block1)); Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, blockChain.tryToConnect(block1b)); List<Block> blocks = blockChain.getBlocksByNumber(1); Assert.assertNotNull(blocks); Assert.assertFalse(blocks.isEmpty()); Assert.assertEquals(2, blocks.size()); Assert.assertEquals(blocks.get(0).getHash(), block1.getHash()); Assert.assertEquals(blocks.get(1).getHash(), block1b.getHash()); blocks = blockChain.getBlocksByNumber(42); Assert.assertNotNull(blocks); Assert.assertTrue(blocks.isEmpty()); }
BlockChainImpl implements Blockchain { @Override public Block getBlockByNumber(long number) { return blockStore.getChainBlockByNumber(number); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }
@Test public void getBlockByNumber() { Block genesis = blockChain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); Block block1 = blockGenerator.createChildBlock(genesis); Block block2 = blockGenerator.createChildBlock(block1); Block block3 = blockGenerator.createChildBlock(block2); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block1)); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block2)); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block3)); Block block = blockChain.getBlockByNumber(0); Assert.assertNotNull(block); Assert.assertEquals(0, block.getNumber()); Assert.assertEquals(genesis.getHash(), block.getHash()); block = blockChain.getBlockByNumber(1); Assert.assertNotNull(block); Assert.assertEquals(1, block.getNumber()); Assert.assertEquals(block1.getHash(), block.getHash()); block = blockChain.getBlockByNumber(2); Assert.assertNotNull(block); Assert.assertEquals(2, block.getNumber()); Assert.assertEquals(block2.getHash(), block.getHash()); block = blockChain.getBlockByNumber(3); Assert.assertNotNull(block); Assert.assertEquals(3, block.getNumber()); Assert.assertEquals(block3.getHash(), block.getHash()); block = blockChain.getBlockByNumber(4); Assert.assertNull(block); }
BlockChainImpl implements Blockchain { @Override public Block getBestBlock() { return this.status.getBestBlock(); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }
@Test public void switchToOtherChainInvalidBadBlockBadReceiptsRoot() { Block genesis = blockChain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); Block block1 = blockGenerator.createChildBlock(genesis); Block block1b = blockGenerator.createChildBlock(genesis); if (FastByteComparisons.compareTo(block1.getHash().getBytes(), 0, 32, block1b.getHash().getBytes(), 0, 32) < 0) { switchToOtherChainInvalidBadBlockBadReceiptsRootHelper(blockChain, genesis, block1, block1b); } else { switchToOtherChainInvalidBadBlockBadReceiptsRootHelper(blockChain, genesis, block1b, block1); } } @Test public void validateMinedBlockOne() { Block genesis = blockChain.getBestBlock(); Block block = new BlockGenerator().createChildBlock(genesis); Assert.assertTrue(blockExecutor.executeAndValidate(block, genesis.getHeader())); } @Test public void validateMinedBlockSeven() { Block genesis = blockChain.getBestBlock(); BlockGenerator blockGenerator = new BlockGenerator(); Block block1 = blockGenerator.createChildBlock(genesis); Block block2 = blockGenerator.createChildBlock(block1); Block block3 = blockGenerator.createChildBlock(block2); Block block4 = blockGenerator.createChildBlock(block3); Block block5 = blockGenerator.createChildBlock(block4); Block block6 = blockGenerator.createChildBlock(block5); Block block7 = blockGenerator.createChildBlock(block6); Assert.assertTrue(blockExecutor.executeAndValidate(block1, genesis.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block2, block1.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block3, block2.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block4, block3.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block5, block4.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block6, block5.getHeader())); Assert.assertTrue(blockExecutor.executeAndValidate(block7, block6.getHeader())); }
BlockChainImpl implements Blockchain { @Override public Block getBlockByHash(byte[] hash) { return blockStore.getBlockByHash(hash); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }
@Test public void getUnknownBlockByHash() { Assert.assertNull(blockChain.getBlockByHash(new BlockGenerator().getBlock(1).getHash().getBytes())); }
BlockChainImpl implements Blockchain { @Override public TransactionInfo getTransactionInfo(byte[] hash) { TransactionInfo txInfo = receiptStore.get(hash); if (txInfo == null) { return null; } Transaction tx = this.getBlockByHash(txInfo.getBlockHash()).getTransactionsList().get(txInfo.getIndex()); txInfo.setTransaction(tx); return txInfo; } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }
@Test public void getUnknownTransactionInfoAsNull() { Assert.assertNull(blockChain.getTransactionInfo(new byte[] { 0x01 })); } @Test public void getTransactionInfo() { Block block = getBlockWithOneTransaction(); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block)); Transaction tx = block.getTransactionsList().get(0); Assert.assertNotNull(blockChain.getTransactionInfo(tx.getHash().getBytes())); }
BlockUtils { public static boolean blockInSomeBlockChain(Block block, Blockchain blockChain) { return blockInSomeBlockChain(block.getHash(), block.getNumber(), blockChain); } private BlockUtils(); static boolean tooMuchProcessTime(long nanoseconds); static boolean blockInSomeBlockChain(Block block, Blockchain blockChain); static Set<Keccak256> unknownDirectAncestorsHashes(Block block, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Set<Keccak256> hashesToProcess, Blockchain blockChain, NetBlockStore store, boolean withUncles); static void addBlockToList(List<Block> blocks, Block block); static List<Block> sortBlocksByNumber(List<Block> blocks); }
@Test public void blockInSomeBlockChain() { BlockChainBuilder blockChainBuilder = new BlockChainBuilder(); BlockChainImpl blockChain = blockChainBuilder.build(); org.ethereum.db.BlockStore blockStore = blockChainBuilder.getBlockStore(); Block genesis = blockChain.getBestBlock(); Block block1 = new BlockBuilder(null, null, null).parent(genesis).build(); Block block1b = new BlockBuilder(null, null, null).parent(genesis).build(); Block block2 = new BlockBuilder(null, null, null).parent(block1).build(); Block block3 = new BlockBuilder(null, null, null).parent(block2).build(); blockStore.saveBlock(block3, new BlockDifficulty(BigInteger.ONE), false); blockChain.tryToConnect(block1); blockChain.tryToConnect(block1b); Assert.assertTrue(BlockUtils.blockInSomeBlockChain(genesis, blockChain)); Assert.assertTrue(BlockUtils.blockInSomeBlockChain(block1, blockChain)); Assert.assertTrue(BlockUtils.blockInSomeBlockChain(block1b, blockChain)); Assert.assertFalse(BlockUtils.blockInSomeBlockChain(block2, blockChain)); Assert.assertTrue(BlockUtils.blockInSomeBlockChain(block3, blockChain)); }
BlockUtils { public static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store) { Set<Keccak256> hashes = Collections.singleton(blockHash); return unknownAncestorsHashes(hashes, blockChain, store, true); } private BlockUtils(); static boolean tooMuchProcessTime(long nanoseconds); static boolean blockInSomeBlockChain(Block block, Blockchain blockChain); static Set<Keccak256> unknownDirectAncestorsHashes(Block block, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Set<Keccak256> hashesToProcess, Blockchain blockChain, NetBlockStore store, boolean withUncles); static void addBlockToList(List<Block> blocks, Block block); static List<Block> sortBlocksByNumber(List<Block> blocks); }
@Test public void unknowAncestorsHashes() { BlockChainImpl blockChain = new BlockChainBuilder().build(); NetBlockStore store = new NetBlockStore(); Block genesis = blockChain.getBestBlock(); Block block1 = new BlockBuilder(null, null, null).difficulty(2l).parent(genesis).build(); Block block1b = new BlockBuilder(null, null, null).difficulty(1l).parent(genesis).build(); Block block2 = new BlockBuilder(null, null, null).parent(block1).build(); Block block3 = new BlockBuilder(null, null, null).parent(block2).build(); store.saveBlock(block3); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block1)); Assert.assertEquals(ImportResult.IMPORTED_NOT_BEST, blockChain.tryToConnect(block1b)); Set<Keccak256> hashes = BlockUtils.unknownAncestorsHashes(genesis.getHash(), blockChain, store); Assert.assertNotNull(hashes); Assert.assertTrue(hashes.isEmpty()); hashes = BlockUtils.unknownAncestorsHashes(block1.getHash(), blockChain, store); Assert.assertNotNull(hashes); Assert.assertTrue(hashes.isEmpty()); hashes = BlockUtils.unknownAncestorsHashes(block1b.getHash(), blockChain, store); Assert.assertNotNull(hashes); Assert.assertTrue(hashes.isEmpty()); hashes = BlockUtils.unknownAncestorsHashes(block2.getHash(), blockChain, store); Assert.assertNotNull(hashes); Assert.assertFalse(hashes.isEmpty()); Assert.assertEquals(1, hashes.size()); Assert.assertTrue(hashes.contains(block2.getHash())); hashes = BlockUtils.unknownAncestorsHashes(block3.getHash(), blockChain, store); Assert.assertNotNull(hashes); Assert.assertFalse(hashes.isEmpty()); Assert.assertEquals(1, hashes.size()); Assert.assertTrue(hashes.contains(block2.getHash())); } @Test public void unknowAncestorsHashesUsingUncles() { BlockChainBuilder blockChainBuilder = new BlockChainBuilder(); BlockChainImpl blockChain = blockChainBuilder.build(); Genesis genesis = (Genesis) blockChain.getBestBlock(); NetBlockStore store = new NetBlockStore(); BlockBuilder blockBuilder = new BlockBuilder(blockChain, null, blockChainBuilder.getBlockStore() ).trieStore(blockChainBuilder.getTrieStore()); blockBuilder.parent(blockChain.getBestBlock()); Block block1 = blockBuilder.parent(genesis).build(); Block block1b = blockBuilder.parent(genesis).build(); Block block2 = blockBuilder.parent(block1).build(); Block uncle1 = blockBuilder.parent(block1).build(); Block uncle2 = blockBuilder.parent(block1).build(); List<BlockHeader> uncles = new ArrayList<>(); uncles.add(uncle1.getHeader()); uncles.add(uncle2.getHeader()); Block block3 = blockBuilder.parent(block2).uncles(uncles).build(); store.saveBlock(block3); blockChain.tryToConnect(genesis); blockChain.tryToConnect(block1); blockChain.tryToConnect(block1b); Set<Keccak256> hashes = BlockUtils.unknownAncestorsHashes(genesis.getHash(), blockChain, store); Assert.assertNotNull(hashes); Assert.assertTrue(hashes.isEmpty()); hashes = BlockUtils.unknownAncestorsHashes(block1.getHash(), blockChain, store); Assert.assertNotNull(hashes); Assert.assertTrue(hashes.isEmpty()); hashes = BlockUtils.unknownAncestorsHashes(block1b.getHash(), blockChain, store); Assert.assertNotNull(hashes); Assert.assertTrue(hashes.isEmpty()); hashes = BlockUtils.unknownAncestorsHashes(block2.getHash(), blockChain, store); Assert.assertNotNull(hashes); Assert.assertFalse(hashes.isEmpty()); Assert.assertEquals(1, hashes.size()); Assert.assertTrue(hashes.contains(block2.getHash())); hashes = BlockUtils.unknownAncestorsHashes(block3.getHash(), blockChain, store); Assert.assertNotNull(hashes); Assert.assertFalse(hashes.isEmpty()); Assert.assertEquals(3, hashes.size()); Assert.assertTrue(hashes.contains(block2.getHash())); Assert.assertTrue(hashes.contains(uncle1.getHash())); Assert.assertTrue(hashes.contains(uncle2.getHash())); }
BlockUtils { public static boolean tooMuchProcessTime(long nanoseconds) { return nanoseconds > MAX_BLOCK_PROCESS_TIME_NANOSECONDS; } private BlockUtils(); static boolean tooMuchProcessTime(long nanoseconds); static boolean blockInSomeBlockChain(Block block, Blockchain blockChain); static Set<Keccak256> unknownDirectAncestorsHashes(Block block, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Set<Keccak256> hashesToProcess, Blockchain blockChain, NetBlockStore store, boolean withUncles); static void addBlockToList(List<Block> blocks, Block block); static List<Block> sortBlocksByNumber(List<Block> blocks); }
@Test public void tooMuchProcessTime() { Assert.assertFalse(BlockUtils.tooMuchProcessTime(0)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(1000)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(1_000_000L)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(1_000_000_000L)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(60_000_000_000L)); Assert.assertTrue(BlockUtils.tooMuchProcessTime(60_000_000_001L)); Assert.assertTrue(BlockUtils.tooMuchProcessTime(1_000_000_000_000L)); }
TransactionPoolImpl implements TransactionPool { @Override public PendingState getPendingState() { return getPendingState(getCurrentRepository()); } TransactionPoolImpl( RskSystemProperties config, RepositoryLocator repositoryLocator, BlockStore blockStore, BlockFactory blockFactory, EthereumListener listener, TransactionExecutorFactory transactionExecutorFactory, SignatureCache signatureCache, int outdatedThreshold, int outdatedTimeout); @Override void start(); @Override void stop(); boolean hasCleanerFuture(); void cleanUp(); int getOutdatedThreshold(); int getOutdatedTimeout(); Block getBestBlock(); @Override PendingState getPendingState(); @Override synchronized List<Transaction> addTransactions(final List<Transaction> txs); @Override synchronized TransactionPoolAddResult addTransaction(final Transaction tx); @Override synchronized void processBest(Block newBlock); @VisibleForTesting void acceptBlock(Block block); @VisibleForTesting void retractBlock(Block block); @VisibleForTesting void removeObsoleteTransactions(long currentBlock, int depth, int timeout); @VisibleForTesting synchronized void removeObsoleteTransactions(long timeSeconds); @Override synchronized void removeTransactions(List<Transaction> txs); @Override synchronized List<Transaction> getPendingTransactions(); @Override synchronized List<Transaction> getQueuedTransactions(); }
@Test public void usingAccountsWithInitialBalance() { createTestAccounts(2, Coin.valueOf(10L)); PendingState pendingState = transactionPool.getPendingState(); Assert.assertNotNull(pendingState); Account account1 = createAccount(1); Account account2 = createAccount(2); Assert.assertEquals(BigInteger.TEN, pendingState.getBalance(account1.getAddress()).asBigInteger()); Assert.assertEquals(BigInteger.TEN, pendingState.getBalance(account2.getAddress()).asBigInteger()); }
TransactionPoolImpl implements TransactionPool { @Override public synchronized List<Transaction> getPendingTransactions() { removeObsoleteTransactions(this.outdatedThreshold, this.outdatedTimeout); return Collections.unmodifiableList(pendingTransactions.getTransactions()); } TransactionPoolImpl( RskSystemProperties config, RepositoryLocator repositoryLocator, BlockStore blockStore, BlockFactory blockFactory, EthereumListener listener, TransactionExecutorFactory transactionExecutorFactory, SignatureCache signatureCache, int outdatedThreshold, int outdatedTimeout); @Override void start(); @Override void stop(); boolean hasCleanerFuture(); void cleanUp(); int getOutdatedThreshold(); int getOutdatedTimeout(); Block getBestBlock(); @Override PendingState getPendingState(); @Override synchronized List<Transaction> addTransactions(final List<Transaction> txs); @Override synchronized TransactionPoolAddResult addTransaction(final Transaction tx); @Override synchronized void processBest(Block newBlock); @VisibleForTesting void acceptBlock(Block block); @VisibleForTesting void retractBlock(Block block); @VisibleForTesting void removeObsoleteTransactions(long currentBlock, int depth, int timeout); @VisibleForTesting synchronized void removeObsoleteTransactions(long timeSeconds); @Override synchronized void removeTransactions(List<Transaction> txs); @Override synchronized List<Transaction> getPendingTransactions(); @Override synchronized List<Transaction> getQueuedTransactions(); }
@Test public void getEmptyPendingTransactionList() { List<Transaction> transactions = transactionPool.getPendingTransactions(); Assert.assertNotNull(transactions); Assert.assertTrue(transactions.isEmpty()); } @Test public void getEmptyTransactionList() { List<Transaction> transactions = transactionPool.getPendingTransactions(); Assert.assertNotNull(transactions); Assert.assertTrue(transactions.isEmpty()); }
TransactionPoolImpl implements TransactionPool { @Override public synchronized TransactionPoolAddResult addTransaction(final Transaction tx) { TransactionPoolAddResult internalResult = this.internalAddTransaction(tx); List<Transaction> pendingTransactionsAdded = new ArrayList<>(); if (!internalResult.transactionsWereAdded()) { return internalResult; } else if(internalResult.pendingTransactionsWereAdded()) { pendingTransactionsAdded.add(tx); pendingTransactionsAdded.addAll(this.addSuccessors(tx)); } this.emitEvents(pendingTransactionsAdded); return TransactionPoolAddResult.ok(internalResult.getQueuedTransactionsAdded(), pendingTransactionsAdded); } TransactionPoolImpl( RskSystemProperties config, RepositoryLocator repositoryLocator, BlockStore blockStore, BlockFactory blockFactory, EthereumListener listener, TransactionExecutorFactory transactionExecutorFactory, SignatureCache signatureCache, int outdatedThreshold, int outdatedTimeout); @Override void start(); @Override void stop(); boolean hasCleanerFuture(); void cleanUp(); int getOutdatedThreshold(); int getOutdatedTimeout(); Block getBestBlock(); @Override PendingState getPendingState(); @Override synchronized List<Transaction> addTransactions(final List<Transaction> txs); @Override synchronized TransactionPoolAddResult addTransaction(final Transaction tx); @Override synchronized void processBest(Block newBlock); @VisibleForTesting void acceptBlock(Block block); @VisibleForTesting void retractBlock(Block block); @VisibleForTesting void removeObsoleteTransactions(long currentBlock, int depth, int timeout); @VisibleForTesting synchronized void removeObsoleteTransactions(long timeSeconds); @Override synchronized void removeTransactions(List<Transaction> txs); @Override synchronized List<Transaction> getPendingTransactions(); @Override synchronized List<Transaction> getQueuedTransactions(); }
@Test public void checkTxWithSameNonceIsRejected() { Coin balance = Coin.valueOf(1000000); createTestAccounts(2, balance); Transaction tx = createSampleTransaction(1, 0, 1000, 0); Transaction tx2 = createSampleTransaction(1, 0, 2000, 0); transactionPool.addTransaction(tx); TransactionPoolAddResult result = transactionPool.addTransaction(tx2); Assert.assertFalse(result.transactionsWereAdded()); Assert.assertEquals("gas price not enough to bump transaction", result.getErrorMessage()); } @Test public void checkRemascTxIsRejected() { RemascTransaction tx = new RemascTransaction(10); TransactionPoolAddResult result = transactionPool.addTransaction(tx); Assert.assertFalse(result.transactionsWereAdded()); Assert.assertEquals("transaction is a remasc transaction", result.getErrorMessage()); } @Test public void aNewTxIsAddedInTxPoolAndShouldBeAddedInCache(){ Coin balance = Coin.valueOf(1000000); createTestAccounts(2, balance); Account account1 = createAccount(1); Transaction tx = createSampleTransaction(1, 2, 1000, 0); transactionPool.addTransaction(tx); Assert.assertTrue(signatureCache.containsTx(tx)); Assert.assertArrayEquals(signatureCache.getSender(tx).getBytes(), account1.getAddress().getBytes()); } @Test public void twoTxsAreAddedInTxPoolAndShouldBeAddedInCache(){ Coin balance = Coin.valueOf(1000000); Account account1 = createAccount(1); createTestAccounts(2, balance); Transaction tx1 = createSampleTransaction(1, 2, 1000, 0); Transaction tx2 = createSampleTransaction(1, 2, 1000, 1); transactionPool.addTransaction(tx1); transactionPool.addTransaction(tx2); Assert.assertTrue(signatureCache.containsTx(tx1)); Assert.assertTrue(signatureCache.containsTx(tx2)); Assert.assertArrayEquals(signatureCache.getSender(tx1).getBytes(), account1.getAddress().getBytes()); Assert.assertArrayEquals(signatureCache.getSender(tx2).getBytes(), account1.getAddress().getBytes()); } @Test public void invalidTxsIsSentAndShouldntBeInCache(){ Coin balance = Coin.valueOf(0); createTestAccounts(2, balance); Transaction tx1 = createSampleTransaction(1, 2, 1000, 1); transactionPool.addTransaction(tx1); Assert.assertFalse(signatureCache.containsTx(tx1)); } @Test public void remascTxIsReceivedAndShouldntBeInCache() { RemascTransaction tx = new RemascTransaction(10); transactionPool.addTransaction(tx); Assert.assertFalse(signatureCache.containsTx(tx)); verify(signatureCache, times(0)).storeSender(tx); signatureCache.storeSender(tx); Assert.assertFalse(signatureCache.containsTx(tx)); } @Test public void firstTxIsRemovedWhenTheCacheLimitSizeIsExceeded() { Coin balance = Coin.valueOf(1000000); createTestAccounts(6005, balance); Transaction tx = createSampleTransaction(1, 2, 1, 0); transactionPool.addTransaction(tx); for (int i = 0; i < MAX_CACHE_SIZE; i++) { if (i == MAX_CACHE_SIZE - 1) { Assert.assertTrue(signatureCache.containsTx(tx)); } Transaction sampleTransaction = createSampleTransaction(i+2, 2, 1, 1); TransactionPoolAddResult result = transactionPool.addTransaction(sampleTransaction); Assert.assertTrue(result.transactionsWereAdded()); } Assert.assertFalse(signatureCache.containsTx(tx)); }
SelectionRule { public static boolean isThisBlockHashSmaller(byte[] thisBlockHash, byte[] compareBlockHash) { return FastByteComparisons.compareTo( thisBlockHash, BYTE_ARRAY_OFFSET, BYTE_ARRAY_LENGTH, compareBlockHash, BYTE_ARRAY_OFFSET, BYTE_ARRAY_LENGTH) < 0; } static boolean shouldWeAddThisBlock( BlockDifficulty blockDifficulty, BlockDifficulty currentDifficulty, Block block, Block currentBlock); static boolean isBrokenSelectionRule( BlockHeader processingBlockHeader, List<Sibling> siblings); static boolean isThisBlockHashSmaller(byte[] thisBlockHash, byte[] compareBlockHash); }
@Test public void smallerBlockHashTest() { byte[] lowerHash = new byte[]{0}; byte[] biggerHash = new byte[]{1}; assertTrue(SelectionRule.isThisBlockHashSmaller(lowerHash, biggerHash)); assertFalse(SelectionRule.isThisBlockHashSmaller(biggerHash, lowerHash)); }
SelectionRule { public static boolean shouldWeAddThisBlock( BlockDifficulty blockDifficulty, BlockDifficulty currentDifficulty, Block block, Block currentBlock) { int compareDifficulties = blockDifficulty.compareTo(currentDifficulty); if (compareDifficulties > 0) { return true; } if (compareDifficulties < 0) { return false; } Coin pfm = currentBlock.getHeader().getPaidFees().multiply(PAID_FEES_MULTIPLIER_CRITERIA); if (block.getHeader().getPaidFees().compareTo(pfm) > 0) { return true; } Coin blockFeesCriteria = block.getHeader().getPaidFees().multiply(PAID_FEES_MULTIPLIER_CRITERIA); return currentBlock.getHeader().getPaidFees().compareTo(blockFeesCriteria) < 0 && isThisBlockHashSmaller(block.getHash().getBytes(), currentBlock.getHash().getBytes()); } static boolean shouldWeAddThisBlock( BlockDifficulty blockDifficulty, BlockDifficulty currentDifficulty, Block block, Block currentBlock); static boolean isBrokenSelectionRule( BlockHeader processingBlockHeader, List<Sibling> siblings); static boolean isThisBlockHashSmaller(byte[] thisBlockHash, byte[] compareBlockHash); }
@Test public void addBlockTest() { Blockchain blockchain = createBlockchain(); BlockGenerator blockGenerator = new BlockGenerator(); Block lowDifficultyBlock = blockGenerator.createChildBlock(blockchain.getBestBlock(), 0, 1); Block highDifficultyBlock = blockGenerator.createChildBlock(lowDifficultyBlock, 0, 5); Block highDifficultyBlockWithMoreFees = blockGenerator.createChildBlock(lowDifficultyBlock, 10L, new ArrayList<>(), highDifficultyBlock.getDifficulty().getBytes()); assertFalse(SelectionRule.shouldWeAddThisBlock(lowDifficultyBlock.getDifficulty(), highDifficultyBlock.getDifficulty(), lowDifficultyBlock, highDifficultyBlock)); assertTrue(SelectionRule.shouldWeAddThisBlock(highDifficultyBlock.getDifficulty(), lowDifficultyBlock.getDifficulty(), highDifficultyBlock, lowDifficultyBlock)); assertTrue(SelectionRule.shouldWeAddThisBlock(highDifficultyBlockWithMoreFees.getDifficulty(), highDifficultyBlock.getDifficulty(), highDifficultyBlockWithMoreFees, highDifficultyBlock)); }
BlockChainFlusher implements InternalService { private void flush() { if (nFlush == 0) { flushAll(); } nFlush++; nFlush = nFlush % flushNumberOfBlocks; } BlockChainFlusher( int flushNumberOfBlocks, CompositeEthereumListener emitter, TrieStore trieStore, BlockStore blockStore, ReceiptStore receiptStore); @Override void start(); @Override void stop(); }
@Test public void flushesAfterNInvocations() { for (int i = 0; i < 6; i++) { listener.onBestBlock(null, null); } verify(trieStore, never()).flush(); verify(blockStore, never()).flush(); verify(receiptStore, never()).flush(); listener.onBestBlock(null, null); verify(trieStore).flush(); verify(blockStore).flush(); verify(receiptStore).flush(); }
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } MiningMainchainViewImpl(BlockStore blockStore, int height); void addBest(BlockHeader bestHeader); @Override List<BlockHeader> get(); }
@Test public void creationIsCorrect() { BlockStore blockStore = createBlockStore(3); MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( blockStore, 448); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); Block bestBlock = blockStore.getBestBlock(); assertThat(result.get(0).getNumber(), is(2L)); assertThat(result.get(0).getHash(), is(bestBlock.getHash())); Block bestBlockParent = blockStore.getBlockByHash(bestBlock.getParentHash().getBytes()); assertThat(result.get(1).getNumber(), is(1L)); assertThat(result.get(1).getHash(), is(bestBlockParent.getHash())); Block genesisBlock = blockStore.getBlockByHash(bestBlockParent.getParentHash().getBytes()); assertThat(result.get(2).getNumber(), is(0L)); assertThat(result.get(2).getHash(), is(genesisBlock.getHash())); } @Test public void createWithLessBlocksThanMaxHeight() { MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( createBlockStore(10), 11); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(10)); } @Test public void createWithBlocksEqualToMaxHeight() { MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( createBlockStore(4), 4); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(4)); } @Test public void createWithMoreBlocksThanMaxHeight() { MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( createBlockStore(8), 6); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(6)); } @Test public void createWithOnlyGenesisAndHeightOne() { BlockStore blockStore = createBlockStore(1); Block genesis = blockStore.getChainBlockByNumber(0L); when(blockStore.getBestBlock()).thenReturn(genesis); MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( blockStore, 1); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(1)); assertThat(result.get(0).isGenesis(), is(true)); } @Test public void createWithOnlyGenesisAndHeightGreaterThanOne() { BlockStore blockStore = createBlockStore(1); Block genesis = blockStore.getChainBlockByNumber(0L); when(blockStore.getBestBlock()).thenReturn(genesis); MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( blockStore, 10); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(1)); assertThat(result.get(0).isGenesis(), is(true)); }
RLP { public static byte[] encodeListHeader(int size) { if (size == 0) { return new byte[]{(byte) OFFSET_SHORT_LIST}; } int totalLength = size; byte[] header; if (totalLength < SIZE_THRESHOLD) { header = new byte[1]; header[0] = (byte) (OFFSET_SHORT_LIST + totalLength); } else { int tmpLength = totalLength; byte byteNum = 0; while (tmpLength != 0) { ++byteNum; tmpLength = tmpLength >> 8; } tmpLength = totalLength; byte[] lenBytes = new byte[byteNum]; for (int i = 0; i < byteNum; ++i) { lenBytes[byteNum - 1 - i] = (byte) ((tmpLength >> (8 * i)) & 0xFF); } header = new byte[1 + lenBytes.length]; header[0] = (byte) (OFFSET_LONG_LIST + byteNum); System.arraycopy(lenBytes, 0, header, 1, lenBytes.length); } return header; } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int index); static byte[] decodeIP4Bytes(byte[] data, int index); static int getFirstListElement(byte[] payload, int pos); static int getNextElementIndex(byte[] payload, int pos); static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, Queue<Integer> index); @Nonnull static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData); static RLPElement decodeFirstElement(@CheckForNull byte[] msgData, int position); static RLPList decodeList(byte[] msgData); @Nullable static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos); @Nonnull static RskAddress parseRskAddress(@Nullable byte[] bytes); @Nonnull static Coin parseCoin(@Nullable byte[] bytes); @Nullable static Coin parseCoinNonNullZero(byte[] bytes); @Nullable static Coin parseSignedCoinNonNullZero(byte[] bytes); static Coin parseCoinNullZero(@Nullable byte[] bytes); @Nullable static BlockDifficulty parseBlockDifficulty(@Nullable byte[] bytes); static byte[] encode(Object input); static byte[] encodeLength(int length, int offset); static byte[] encodeByte(byte singleByte); static byte[] encodeShort(short singleShort); static byte[] encodeInt(int singleInt); static byte[] encodeString(String srcString); static byte[] encodeBigInteger(BigInteger srcBigInteger); static byte[] encodeRskAddress(RskAddress addr); static byte[] encodeCoin(@Nullable Coin coin); static byte[] encodeCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeSignedCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeCoinNullZero(Coin coin); static byte[] encodeBlockDifficulty(BlockDifficulty difficulty); static byte[] encodeElement(@Nullable byte[] srcData); static byte[] encodeListHeader(int size); static byte[] encodeSet(Set<ByteArrayWrapper> data); static byte[] encodeList(byte[]... elements); static byte[] encodedEmptyList(); static byte[] encodedEmptyByteArray(); }
@Test public void testEncodeListHeader(){ byte[] header = encodeListHeader(10); String expected_1 = "ca"; assertEquals(expected_1, ByteUtil.toHexString(header)); header = encodeListHeader(1000); String expected_2 = "f903e8"; assertEquals(expected_2, ByteUtil.toHexString(header)); header = encodeListHeader(1000000000); String expected_3 = "fb3b9aca00"; assertEquals(expected_3, ByteUtil.toHexString(header)); }
Uint24 implements Comparable<Uint24> { public int intValue() { return intValue; } Uint24(int intValue); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(Uint24 o); @Override String toString(); static Uint24 decode(byte[] bytes, int offset); static final int SIZE; static final int BYTES; static final Uint24 ZERO; static final Uint24 MAX_VALUE; }
@Test(expected = IllegalArgumentException.class) public void instantiateMaxPlusOne() { new Uint24(Uint24.MAX_VALUE.intValue() + 1); }
Uint24 implements Comparable<Uint24> { public static Uint24 decode(byte[] bytes, int offset) { int intValue = (bytes[offset + 2] & 0xFF) + ((bytes[offset + 1] & 0xFF) << 8) + ((bytes[offset ] & 0xFF) << 16); return new Uint24(intValue); } Uint24(int intValue); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(Uint24 o); @Override String toString(); static Uint24 decode(byte[] bytes, int offset); static final int SIZE; static final int BYTES; static final Uint24 ZERO; static final Uint24 MAX_VALUE; }
@Test public void decodeOffsettedValue() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2, (byte) 0xf4, 0x04, 0x55}; Uint24 decoded = Uint24.decode(bytes, 2); assertThat(decoded, is(new Uint24(15922180))); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void decodeSmallArray() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2}; Uint24.decode(bytes, 2); }
Uint8 { public byte asByte() { return (byte) intValue; } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }
@Test public void asByteReturnsByteValue() { Uint8 fortyTwo = new Uint8(42); assertThat(fortyTwo.asByte(), is((byte)42)); }
Uint8 { public int intValue() { return intValue; } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }
@Test(expected = IllegalArgumentException.class) public void instantiateMaxPlusOne() { new Uint8((Uint8.MAX_VALUE.intValue() + 1)); }
RLP { public static byte[] encodeSet(Set<ByteArrayWrapper> data) { int dataLength = 0; Set<byte[]> encodedElements = new HashSet<>(); for (ByteArrayWrapper element : data) { byte[] encodedElement = RLP.encodeElement(element.getData()); dataLength += encodedElement.length; encodedElements.add(encodedElement); } byte[] listHeader = encodeListHeader(dataLength); byte[] output = new byte[listHeader.length + dataLength]; System.arraycopy(listHeader, 0, output, 0, listHeader.length); int cummStart = listHeader.length; for (byte[] element : encodedElements) { System.arraycopy(element, 0, output, cummStart, element.length); cummStart += element.length; } return output; } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int index); static byte[] decodeIP4Bytes(byte[] data, int index); static int getFirstListElement(byte[] payload, int pos); static int getNextElementIndex(byte[] payload, int pos); static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, Queue<Integer> index); @Nonnull static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData); static RLPElement decodeFirstElement(@CheckForNull byte[] msgData, int position); static RLPList decodeList(byte[] msgData); @Nullable static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos); @Nonnull static RskAddress parseRskAddress(@Nullable byte[] bytes); @Nonnull static Coin parseCoin(@Nullable byte[] bytes); @Nullable static Coin parseCoinNonNullZero(byte[] bytes); @Nullable static Coin parseSignedCoinNonNullZero(byte[] bytes); static Coin parseCoinNullZero(@Nullable byte[] bytes); @Nullable static BlockDifficulty parseBlockDifficulty(@Nullable byte[] bytes); static byte[] encode(Object input); static byte[] encodeLength(int length, int offset); static byte[] encodeByte(byte singleByte); static byte[] encodeShort(short singleShort); static byte[] encodeInt(int singleInt); static byte[] encodeString(String srcString); static byte[] encodeBigInteger(BigInteger srcBigInteger); static byte[] encodeRskAddress(RskAddress addr); static byte[] encodeCoin(@Nullable Coin coin); static byte[] encodeCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeSignedCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeCoinNullZero(Coin coin); static byte[] encodeBlockDifficulty(BlockDifficulty difficulty); static byte[] encodeElement(@Nullable byte[] srcData); static byte[] encodeListHeader(int size); static byte[] encodeSet(Set<ByteArrayWrapper> data); static byte[] encodeList(byte[]... elements); static byte[] encodedEmptyList(); static byte[] encodedEmptyByteArray(); }
@Test public void testEncodeSet_2(){ Set<ByteArrayWrapper> data = new HashSet<>(); byte[] setEncoded = encodeSet(data); assertEquals("c0", ByteUtil.toHexString(setEncoded)); }
Uint8 { public static Uint8 decode(byte[] bytes, int offset) { int intValue = bytes[offset] & 0xFF; return new Uint8(intValue); } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }
@Test public void decodeOffsettedValue() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf3, (byte) 0xf4, 0x04, 0x55}; Uint8 decoded = Uint8.decode(bytes, 2); assertThat(decoded, is(new Uint8(243))); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void decodeSmallArray() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2}; Uint8.decode(bytes, 3); }
RskAddress { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } RskAddress otherSender = (RskAddress) other; return Arrays.equals(bytes, otherSender.bytes); } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); static RskAddress nullAddress(); byte[] getBytes(); String toHexString(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); static final int LENGTH_IN_BYTES; static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR; }
@Test public void testEquals() { RskAddress senderA = new RskAddress("0000000000000000000000000000000001000006"); RskAddress senderB = new RskAddress("0000000000000000000000000000000001000006"); RskAddress senderC = new RskAddress("0000000000000000000000000000000001000008"); RskAddress senderD = RskAddress.nullAddress(); RskAddress senderE = new RskAddress("0x00002000f000000a000000330000000001000006"); Assert.assertEquals(senderA, senderB); Assert.assertNotEquals(senderA, senderC); Assert.assertNotEquals(senderA, senderD); Assert.assertNotEquals(senderA, senderE); }
RskAddress { public static RskAddress nullAddress() { return NULL_ADDRESS; } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); static RskAddress nullAddress(); byte[] getBytes(); String toHexString(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); static final int LENGTH_IN_BYTES; static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR; }
@Test public void zeroAddress() { RskAddress senderA = new RskAddress("0000000000000000000000000000000000000000"); RskAddress senderB = new RskAddress("0x0000000000000000000000000000000000000000"); RskAddress senderC = new RskAddress(new byte[20]); Assert.assertEquals(senderA, senderB); Assert.assertEquals(senderB, senderC); Assert.assertNotEquals(RskAddress.nullAddress(), senderC); } @Test public void nullAddress() { Assert.assertArrayEquals(RskAddress.nullAddress().getBytes(), new byte[0]); }
RskAddress { public String toJsonString() { if (NULL_ADDRESS.equals(this)) { return null; } return TypeConverter.toUnformattedJsonHex(this.getBytes()); } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); static RskAddress nullAddress(); byte[] getBytes(); String toHexString(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); String toJsonString(); static final int LENGTH_IN_BYTES; static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR; }
@Test public void jsonString_otherAddress() { String address = "0x0000000000000000000000000000000000000001"; RskAddress rskAddress = new RskAddress(address); Assert.assertEquals(address, rskAddress.toJsonString()); }
Coin implements Comparable<Coin> { public byte[] getBytes() { return value.toByteArray(); } Coin(byte[] value); Coin(BigInteger value); byte[] getBytes(); BigInteger asBigInteger(); Coin negate(); Coin add(Coin val); Coin subtract(Coin val); Coin multiply(BigInteger val); Coin divide(BigInteger val); Coin[] divideAndRemainder(BigInteger val); co.rsk.bitcoinj.core.Coin toBitcoin(); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(@Nonnull Coin other); @Override String toString(); static Coin valueOf(long val); static Coin fromBitcoin(co.rsk.bitcoinj.core.Coin val); static final Coin ZERO; }
@Test public void zeroGetBytes() { assertThat(Coin.ZERO.getBytes(), is(new byte[]{0})); }
TrieKeySlice { public TrieKeySlice leftPad(int paddingLength) { if (paddingLength == 0) { return this; } int currentLength = length(); byte[] paddedExpandedKey = new byte[currentLength + paddingLength]; System.arraycopy(expandedKey, offset, paddedExpandedKey, paddingLength, currentLength); return new TrieKeySlice(paddedExpandedKey, 0, paddedExpandedKey.length); } private TrieKeySlice(byte[] expandedKey, int offset, int limit); int length(); byte get(int i); byte[] encode(); TrieKeySlice slice(int from, int to); TrieKeySlice commonPath(TrieKeySlice other); TrieKeySlice rebuildSharedPath(byte implicitByte, TrieKeySlice childSharedPath); TrieKeySlice leftPad(int paddingLength); static TrieKeySlice fromKey(byte[] key); static TrieKeySlice fromEncoded(byte[] src, int offset, int keyLength, int encodedLength); static TrieKeySlice empty(); }
@Test public void leftPad() { int paddedLength = 8; TrieKeySlice initialKey = TrieKeySlice.fromKey(new byte[]{(byte) 0xff}); TrieKeySlice leftPaddedKey = initialKey.leftPad(paddedLength); Assert.assertThat(leftPaddedKey.length(), is(initialKey.length() + paddedLength)); Assert.assertArrayEquals( PathEncoder.encode(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }), leftPaddedKey.encode() ); }
TrieStoreImpl implements TrieStore { @Override public void save(Trie trie) { save(trie, true); } TrieStoreImpl(KeyValueDataSource store); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] hash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); }
@Test public void saveTrieNode() { Trie trie = new Trie(store).put("foo", "bar".getBytes()); store.save(trie); verify(map, times(1)).put(trie.getHash().getBytes(), trie.toMessage()); verify(map, times(1)).get(trie.getHash().getBytes()); verifyNoMoreInteractions(map); } @Test public void saveFullTrie() { Trie trie = new Trie(store).put("foo", "bar".getBytes()); store.save(trie); verify(map, times(1)).put(trie.getHash().getBytes(), trie.toMessage()); verify(map, times(1)).get(trie.getHash().getBytes()); verifyNoMoreInteractions(map); } @Test public void saveFullTrieWithLongValue() { Trie trie = new Trie(store).put("foo", TrieValueTest.makeValue(100)); store.save(trie); verify(map, times(1)).put(trie.getHash().getBytes(), trie.toMessage()); verify(map, times(1)).put(trie.getValueHash().getBytes(), trie.getValue()); verify(map, times(1)).get(trie.getHash().getBytes()); verifyNoMoreInteractions(map); } @Test public void saveFullTrieWithTwoLongValues() { Trie trie = new Trie(store) .put("foo", TrieValueTest.makeValue(100)) .put("bar", TrieValueTest.makeValue(200)); store.save(trie); verify(map, times(trie.trieSize())).put(any(), any()); verify(map, times(1)).get(trie.getHash().getBytes()); verify(map, times(1)).get(trie.getHash().getBytes()); verifyNoMoreInteractions(map); } @Test public void saveFullTrieTwice() { Trie trie = new Trie(store).put("foo", "bar".getBytes()); store.save(trie); verify(map, times(1)).put(trie.getHash().getBytes(), trie.toMessage()); verify(map, times(1)).get(trie.getHash().getBytes()); verify(map, times(1)).get(trie.getHash().getBytes()); verifyNoMoreInteractions(map); store.save(trie); verify(map, times(1)).put(trie.getHash().getBytes(), trie.toMessage()); verify(map, times(1)).get(trie.getHash().getBytes()); verifyNoMoreInteractions(map); } @Test public void saveFullTrieUpdateAndSaveAgainUsingBinaryTrie() { Trie trie = new Trie(store).put("foo", "bar".getBytes()); store.save(trie); Keccak256 hash1 = trie.getHash(); verify(map, times(trie.trieSize())).put(any(), any()); trie = trie.put("foo", "bar2".getBytes()); store.save(trie); Keccak256 hash2 = trie.getHash(); verify(map, times(trie.trieSize() + 1)).put(any(), any()); verify(map, times(1)).get(hash1.getBytes()); verify(map, times(1)).get(hash2.getBytes()); verifyNoMoreInteractions(map); } @Test public void saveFullTrieUpdateAndSaveAgain() { Trie trie = new Trie(store).put("foo", "bar".getBytes()); store.save(trie); verify(map, times(trie.trieSize())).put(any(), any()); trie = trie.put("foo", "bar2".getBytes()); store.save(trie); verify(map, times(trie.trieSize() + 1)).put(any(), any()); verify(map, times(2)).get(any()); verifyNoMoreInteractions(map); }
TrieStoreImpl implements TrieStore { @Override public Optional<Trie> retrieve(byte[] hash) { byte[] message = this.store.get(hash); if (message == null) { return Optional.empty(); } Trie trie = Trie.fromMessage(message, this); savedTries.add(trie); return Optional.of(trie); } TrieStoreImpl(KeyValueDataSource store); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] hash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); }
@Test public void retrieveTrieNotFound() { Assert.assertFalse(store.retrieve(new byte[] { 0x01, 0x02, 0x03, 0x04 }).isPresent()); }
TrieConverter { public byte[] getOrchidAccountTrieRoot(Trie src) { Metric metric = profiler.start(Profiler.PROFILING_TYPE.TRIE_CONVERTER_GET_ACCOUNT_ROOT); byte[] trieRoot = cacheHashes.computeIfAbsent(src.getHash(), k -> { Trie trie = getOrchidAccountTrieRoot(src.getSharedPath(), src, true); return trie == null ? HashUtil.EMPTY_TRIE_HASH : trie.getHashOrchid(true).getBytes(); }); profiler.stop(metric); return trieRoot; } TrieConverter(); byte[] getOrchidAccountTrieRoot(Trie src); }
@Test public void getOrchidAccountTrieRootWithCompressedStorageKeys() { TrieStore trieStore = new TrieStoreImpl(new HashMapDB()); Repository repository = new MutableRepository(new MutableTrieImpl(trieStore, new Trie(trieStore))); Repository track = repository.startTracking(); TestUtils.getRandom().setSeed(0); int maxAccounts = 10; int maxStorageRows = 5; for (int i = 0; i < maxAccounts; i++) { RskAddress addr = TestUtils.randomAddress(); track.createAccount(addr); AccountState a = track.getAccountState(addr); a.setNonce(TestUtils.randomBigInteger(4)); a.addToBalance(TestUtils.randomCoin(18, 1000)); track.updateAccountState(addr, a); if (i >= maxAccounts / 2) { track.setupContract(addr); for (int s = 0; s < maxStorageRows / 2; s++) { track.addStorageBytes(addr, TestUtils.randomDataWord(), TestUtils.randomBytes(TestUtils.getRandom().nextInt(40) + 1)); } for (int s = 0; s < maxStorageRows / 2; s++) { track.addStorageBytes(addr, DataWord.valueOf(TestUtils.randomBytes(20)), TestUtils.randomBytes(TestUtils.getRandom().nextInt(40) + 1)); } track.saveCode(addr, randomCode(60)); } } track.commit(); TrieConverter tc = new TrieConverter(); byte[] oldRoot = tc.getOrchidAccountTrieRoot(repository.getTrie()); Trie atrie = deserialize(SERIALIZED_ORCHID_TRIESTORE_WITH_LEADING_ZEROES_STORAGE_KEYS); Assert.assertThat(ByteUtil.toHexString(oldRoot), is(atrie.getHashOrchid(true).toHexString())); } @Test public void test1Simple() { TrieStore trieStore = new TrieStoreImpl(new HashMapDB()); Repository repository = new MutableRepository(new MutableTrieImpl(trieStore, new Trie(trieStore))); Repository track = repository.startTracking(); TestUtils.getRandom().setSeed(0); int maxAccounts = 10; int maxStorageRows = 5; for (int i = 0; i < maxAccounts; i++) { RskAddress addr = TestUtils.randomAddress(); track.createAccount(addr); AccountState a = track.getAccountState(addr); a.setNonce(TestUtils.randomBigInteger(4)); a.addToBalance(TestUtils.randomCoin(18, 1000)); track.updateAccountState(addr, a); if (i >= maxAccounts / 2) { track.setupContract(addr); for (int s = 0; s < maxStorageRows; s++) { track.addStorageBytes(addr, TestUtils.randomDataWord(), TestUtils.randomBytes(TestUtils.getRandom().nextInt(40) + 1)); } track.saveCode(addr, randomCode(60)); } } track.commit(); TrieConverter tc = new TrieConverter(); byte[] oldRoot = tc.getOrchidAccountTrieRoot(repository.getTrie()); Trie atrie = deserialize(SERIALIZED_ORCHID_TRIESTORE_SIMPLE); Assert.assertThat(ByteUtil.toHexString(oldRoot), is(atrie.getHashOrchid(true).toHexString())); }
PathEncoder { @Nonnull public static byte[] encode(byte[] path) { if (path == null) { throw new IllegalArgumentException("path"); } return encodeBinaryPath(path); } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }
@Test public void encodeNullBinaryPath() { try { PathEncoder.encode(null); Assert.fail(); } catch (Exception ex) { Assert.assertTrue(ex instanceof IllegalArgumentException); } } @Test public void encodeBinaryPathOneByte() { byte[] path = new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x6d }, encoded); } @Test public void encodeBinaryPathNineBits() { byte[] path = new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x6d, (byte)0x80 }, encoded); } @Test public void encodeBinaryPathOneAndHalfByte() { byte[] path = new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x6d, 0x50 }, encoded); }
PathEncoder { @Nonnull private static byte[] encodeBinaryPath(byte[] path) { int lpath = path.length; int lencoded = calculateEncodedLength(lpath); byte[] encoded = new byte[lencoded]; int nbyte = 0; for (int k = 0; k < lpath; k++) { int offset = k % 8; if (k > 0 && offset == 0) { nbyte++; } if (path[k] == 0) { continue; } encoded[nbyte] |= 0x80 >> offset; } return encoded; } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }
@Test public void encodeBinaryPath() { byte[] path = new byte[] { 0x00, 0x01, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x60 }, encoded); }
Web3Impl implements Web3 { @Override public String net_peerCount() { String s = null; try { int n = channelManager.getActivePeers().size(); return s = TypeConverter.toQuantityJsonHex(n); } finally { if (logger.isDebugEnabled()) { logger.debug("net_peerCount(): {}", 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 net_peerCount() throws Exception { Web3Impl web3 = createWeb3(); String peerCount = web3.net_peerCount(); Assert.assertEquals("Different number of peers than expected", "0x0", peerCount); }
PathEncoder { @Nonnull public static byte[] decode(byte[] encoded, int length) { if (encoded == null) { throw new IllegalArgumentException("encoded"); } return decodeBinaryPath(encoded, length); } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }
@Test public void decodeNullBinaryPath() { try { PathEncoder.decode(null, 0); Assert.fail(); } catch (Exception ex) { Assert.assertTrue(ex instanceof IllegalArgumentException); } } @Test public void decodeBinaryPathOneByte() { byte[] encoded = new byte[] { 0x6d }; byte[] path = PathEncoder.decode(encoded, 8); Assert.assertNotNull(path); Assert.assertArrayEquals(new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01 }, path); } @Test public void decodeBinaryPathNineBits() { byte[] encoded = new byte[] { 0x6d, (byte)0x80 }; byte[] path = PathEncoder.decode(encoded, 9); Assert.assertNotNull(path); Assert.assertArrayEquals(new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01 }, path); } @Test public void decodeBinaryPathOneAndHalfByte() { byte[] encoded = new byte[] { 0x6d, 0x50 }; byte[] path = PathEncoder.decode(encoded, 12); Assert.assertNotNull(path); Assert.assertArrayEquals(new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01 }, path); }
PathEncoder { @Nonnull private static byte[] decodeBinaryPath(byte[] encoded, int bitlength) { byte[] path = new byte[bitlength]; for (int k = 0; k < bitlength; k++) { int nbyte = k / 8; int offset = k % 8; if (((encoded[nbyte] >> (7 - offset)) & 0x01) != 0) { path[k] = 1; } } return path; } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedLength(int keyLength); }
@Test public void decodeBinaryPath() { byte[] encoded = new byte[] { 0x60 }; byte[] path = PathEncoder.decode(encoded, 3); Assert.assertNotNull(path); Assert.assertArrayEquals(new byte[] { 0x00, 0x01, 0x01 }, path); }
MultiTrieStore implements TrieStore { @Override public void save(Trie trie) { getCurrentStore().save(trie); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }
@Test public void callsSaveOnlyOnNewestStore() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); Trie trie = mock(Trie.class); store.save(trie); verify(store1, never()).save(trie); verify(store2, never()).save(trie); verify(store3).save(trie); }
MultiTrieStore implements TrieStore { @Override public void flush() { epochs.forEach(TrieStore::flush); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }
@Test public void callsFlushOnAllStores() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); store.flush(); verify(store1).flush(); verify(store2).flush(); verify(store3).flush(); }
MultiTrieStore implements TrieStore { @Override public void dispose() { epochs.forEach(TrieStore::dispose); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }
@Test public void callsDisposeOnAllStores() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); store.dispose(); verify(store1).dispose(); verify(store2).dispose(); verify(store3).dispose(); }
MultiTrieStore implements TrieStore { @Override public byte[] retrieveValue(byte[] hash) { for (TrieStore epochTrieStore : epochs) { byte[] value = epochTrieStore.retrieveValue(hash); if (value != null) { return value; } } return null; } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); void collect(byte[] oldestTrieHashToKeep); }
@Test public void retrievesValueFromNewestStoreWithValue() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("47")).thenReturn(store2); when(storeFactory.newInstance("48")).thenReturn(store3); MultiTrieStore store = new MultiTrieStore(49, 3, storeFactory, null); byte[] testValue = new byte[] {0x32, 0x42}; byte[] hashToRetrieve = new byte[] {0x2, 0x4}; when(store2.retrieveValue(hashToRetrieve)).thenReturn(testValue); byte[] retrievedValue = store.retrieveValue(hashToRetrieve); assertArrayEquals(testValue, retrievedValue); verify(store1, never()).retrieveValue(hashToRetrieve); verify(store2).retrieveValue(hashToRetrieve); verify(store3).retrieveValue(hashToRetrieve); }
BitSet { public boolean get(int position) { if (position < 0 || position >= this.size) { throw new IndexOutOfBoundsException(String.format("Index: %s, Size: %s", position, this.size)); } int offset = position / 8; int bitoffset = position % 8; return (this.bytes[offset] & 0xff & (1 << bitoffset)) != 0; } BitSet(int size); void set(int position); boolean get(int position); int size(); }
@Test public void exceptionIfGetWithNegativePosition() { BitSet set = new BitSet(17); try { set.get(-1); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: -1, Size: 17", ex.getMessage()); } } @Test public void exceptionIfGetWithOutOfBoundPosition() { BitSet set = new BitSet(17); try { set.get(17); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: 17, Size: 17", ex.getMessage()); } }
BitSet { public void set(int position) { if (position < 0 || position >= this.size) { throw new IndexOutOfBoundsException(String.format("Index: %s, Size: %s", position, this.size)); } int offset = position / 8; int bitoffset = position % 8; this.bytes[offset] |= 1 << bitoffset; } BitSet(int size); void set(int position); boolean get(int position); int size(); }
@Test public void exceptionIfSetWithNegativePosition() { BitSet set = new BitSet(17); try { set.set(-1); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: -1, Size: 17", ex.getMessage()); } } @Test public void exceptionIfSetWithOutOfBoundPosition() { BitSet set = new BitSet(17); try { set.set(17); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: 17, Size: 17", ex.getMessage()); } }
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("extractPublicKeyFromExtendedPublicKey", fn.name); Assert.assertEquals(1, fn.inputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("bytes").getName(), fn.outputs[0].type.getName()); }
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public boolean isEnabled() { return true; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public Object execute(Object[] arguments) { if (arguments == null) { throw new NativeContractIllegalArgumentException(String.format(INVALID_EXTENDED_PUBLIC_KEY, null)); } String xpub = (String) arguments[0]; NetworkParameters params = helper.validateAndExtractNetworkFromExtendedPublicKey(xpub); DeterministicKey key; try { key = DeterministicKey.deserializeB58(xpub, params); } catch (IllegalArgumentException e) { throw new NativeContractIllegalArgumentException(String.format(INVALID_EXTENDED_PUBLIC_KEY, xpub), e); } return key.getPubKeyPoint().getEncoded(true); } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void executes() { Assert.assertEquals( "02be517550b9e3be7fe42c80932d51e88e698663b4926e598b269d050e87e34d8c", ByteUtil.toHexString((byte[]) method.execute(new Object[]{ "xpub661MyMwAqRbcFMGNG2YcHvj3x63bAZN9U5cKikaiQ4zu2D1cvpnZYyXNR9nH62sGp4RR39Ui7SVQSq1PY4JbPuEuu5prVJJC3d5Pogft712", }))); } @Test public void validatesExtendedPublicKeyFormat() { try { method.execute(new Object[]{ "this-is-not-an-xpub", }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Invalid extended public key")); } } @Test public void failsUponInvalidPublicKey() { try { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1s", }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Invalid extended public key")); } } @Test public void failsUponNull() { try { method.execute(null); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Invalid extended public key")); } }
RLP { @Nullable public static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos) { if (msgData == null) { return null; } return RLP.decodeFirstElement(msgData, startPos); } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int index); static byte[] decodeIP4Bytes(byte[] data, int index); static int getFirstListElement(byte[] payload, int pos); static int getNextElementIndex(byte[] payload, int pos); static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, Queue<Integer> index); @Nonnull static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData); static RLPElement decodeFirstElement(@CheckForNull byte[] msgData, int position); static RLPList decodeList(byte[] msgData); @Nullable static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos); @Nonnull static RskAddress parseRskAddress(@Nullable byte[] bytes); @Nonnull static Coin parseCoin(@Nullable byte[] bytes); @Nullable static Coin parseCoinNonNullZero(byte[] bytes); @Nullable static Coin parseSignedCoinNonNullZero(byte[] bytes); static Coin parseCoinNullZero(@Nullable byte[] bytes); @Nullable static BlockDifficulty parseBlockDifficulty(@Nullable byte[] bytes); static byte[] encode(Object input); static byte[] encodeLength(int length, int offset); static byte[] encodeByte(byte singleByte); static byte[] encodeShort(short singleShort); static byte[] encodeInt(int singleInt); static byte[] encodeString(String srcString); static byte[] encodeBigInteger(BigInteger srcBigInteger); static byte[] encodeRskAddress(RskAddress addr); static byte[] encodeCoin(@Nullable Coin coin); static byte[] encodeCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeSignedCoinNonNullZero(@CheckForNull Coin coin); static byte[] encodeCoinNullZero(Coin coin); static byte[] encodeBlockDifficulty(BlockDifficulty difficulty); static byte[] encodeElement(@Nullable byte[] srcData); static byte[] encodeListHeader(int size); static byte[] encodeSet(Set<ByteArrayWrapper> data); static byte[] encodeList(byte[]... elements); static byte[] encodedEmptyList(); static byte[] encodedEmptyByteArray(); }
@Test public void partialDataParseTest() { String hex = "000080c180000000000000000000000042699b1104e93abf0008be55f912c2ff"; RLPList el = (RLPList) decode2OneItem(Hex.decode(hex), 3); assertEquals(1, el.size()); }
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 11_300L; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void gasIsCorrect() { Assert.assertEquals(11_300, method.getGas(new Object[]{ "xpub661MyMwAqRbcFMGNG2YcHvj3x63bAZN9U5cKikaiQ4zu2D1cvpnZYyXNR9nH62sGp4RR39Ui7SVQSq1PY4JbPuEuu5prVJJC3d5Pogft712" }, new byte[]{})); }
GetMultisigScriptHash extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("getMultisigScriptHash", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("int256").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getType("bytes[]").getName(), fn.inputs[1].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("bytes").getName(), fn.outputs[0].type.getName()); }
GetMultisigScriptHash extends NativeMethod { @Override public boolean isEnabled() { return true; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
GetMultisigScriptHash extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
GetMultisigScriptHash extends NativeMethod { @Override public Object execute(Object[] arguments) { if (arguments == null || arguments[0] == null) { throw new NativeContractIllegalArgumentException(REQUIRED_SIGNATURE_NULL_OR_ZERO); } int minimumSignatures = ((BigInteger) arguments[0]).intValueExact(); Object[] publicKeys = (Object[]) arguments[1]; if (minimumSignatures <= 0) { throw new NativeContractIllegalArgumentException(REQUIRED_SIGNATURE_NULL_OR_ZERO); } if (publicKeys == null || publicKeys.length < MINIMUM_REQUIRED_KEYS) { throw new NativeContractIllegalArgumentException(PUBLIC_KEYS_NULL_OR_ONE); } if (publicKeys.length < minimumSignatures) { throw new NativeContractIllegalArgumentException(String.format( INVALID_REQUIRED_SIGNATURE_AND_PUBLIC_KEYS_PAIR, publicKeys.length, minimumSignatures )); } if (publicKeys.length > MAXIMUM_ALLOWED_KEYS) { throw new NativeContractIllegalArgumentException(String.format( "Given public keys (%d) are more than the maximum allowed signatures (%d)", publicKeys.length, MAXIMUM_ALLOWED_KEYS )); } List<BtcECKey> btcPublicKeys = new ArrayList<>(); Arrays.stream(publicKeys).forEach(o -> { byte[] publicKey = (byte[]) o; if (publicKey.length != COMPRESSED_PUBLIC_KEY_LENGTH && publicKey.length != UNCOMPRESSED_PUBLIC_KEY_LENGTH) { throw new NativeContractIllegalArgumentException(String.format( "Invalid public key length: %d", publicKey.length )); } try { BtcECKey btcPublicKey = BtcECKey.fromPublicOnly(publicKey); if (publicKey.length == UNCOMPRESSED_PUBLIC_KEY_LENGTH) { btcPublicKey = BtcECKey.fromPublicOnly(btcPublicKey.getPubKeyPoint().getEncoded(true)); } btcPublicKeys.add(btcPublicKey); } catch (IllegalArgumentException e) { throw new NativeContractIllegalArgumentException(String.format( "Invalid public key format: %s", ByteUtil.toHexString(publicKey) ), e); } }); Script multisigScript = ScriptBuilder.createP2SHOutputScript(minimumSignatures, btcPublicKeys); return multisigScript.getPubKeyHash(); } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }
@Test public void executesWithAllCompressed() { Assert.assertEquals( "51f103320b435b5fe417b3f3e0f18972ccc710a0", ByteUtil.toHexString((byte[]) method.execute(new Object[]{ BigInteger.valueOf(8L), new byte[][] { Hex.decode("03b53899c390573471ba30e5054f78376c5f797fda26dde7a760789f02908cbad2"), Hex.decode("027319afb15481dbeb3c426bcc37f9a30e7f51ceff586936d85548d9395bcc2344"), Hex.decode("0355a2e9bf100c00fc0a214afd1bf272647c7824eb9cb055480962f0c382596a70"), Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7"), Hex.decode("0294c817150f78607566e961b3c71df53a22022a80acbb982f83c0c8baac040adc"), Hex.decode("0372cd46831f3b6afd4c044d160b7667e8ebf659d6cb51a825a3104df6ee0638c6"), Hex.decode("0340df69f28d69eef60845da7d81ff60a9060d4da35c767f017b0dd4e20448fb44"), Hex.decode("02ac1901b6fba2c1dbd47d894d2bd76c8ba1d296d65f6ab47f1c6b22afb53e73eb"), Hex.decode("031aabbeb9b27258f98c2bf21f36677ae7bae09eb2d8c958ef41a20a6e88626d26"), Hex.decode("0245ef34f5ee218005c9c21227133e8568a4f3f11aeab919c66ff7b816ae1ffeea"), Hex.decode("02550cc87fa9061162b1dd395a16662529c9d8094c0feca17905a3244713d65fe8"), Hex.decode("02481f02b7140acbf3fcdd9f72cf9a7d9484d8125e6df7c9451cfa55ba3b077265"), Hex.decode("03f909ae15558c70cc751aff9b1f495199c325b13a9e5b934fd6299cd30ec50be8"), Hex.decode("02c6018fcbd3e89f3cf9c7f48b3232ea3638eb8bf217e59ee290f5f0cfb2fb9259"), Hex.decode("03b65694ccccda83cbb1e56b31308acd08e993114c33f66a456b627c2c1c68bed6") } }))); } @Test public void executesWithMixed() { Assert.assertEquals( "51f103320b435b5fe417b3f3e0f18972ccc710a0", ByteUtil.toHexString((byte[]) method.execute(new Object[]{ BigInteger.valueOf(8L), new byte[][] { Hex.decode("04b53899c390573471ba30e5054f78376c5f797fda26dde7a760789f02908cbad2aafaaa2611606699ec4f82777a268b708dab346de4880cd223969f7bbe5422bf"), Hex.decode("027319afb15481dbeb3c426bcc37f9a30e7f51ceff586936d85548d9395bcc2344"), Hex.decode("0355a2e9bf100c00fc0a214afd1bf272647c7824eb9cb055480962f0c382596a70"), Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7"), Hex.decode("0494c817150f78607566e961b3c71df53a22022a80acbb982f83c0c8baac040adcb17171aa9ec8d8587098e0771f686ee61ac35279f9e5aadf9b06b738aa6d3720"), Hex.decode("0372cd46831f3b6afd4c044d160b7667e8ebf659d6cb51a825a3104df6ee0638c6"), Hex.decode("0440df69f28d69eef60845da7d81ff60a9060d4da35c767f017b0dd4e20448fb44e1abebaea4c3c57c6e9e39e205b4df046f7110a8d3477c0d8e26a28be9692c29"), Hex.decode("02ac1901b6fba2c1dbd47d894d2bd76c8ba1d296d65f6ab47f1c6b22afb53e73eb"), Hex.decode("031aabbeb9b27258f98c2bf21f36677ae7bae09eb2d8c958ef41a20a6e88626d26"), Hex.decode("0445ef34f5ee218005c9c21227133e8568a4f3f11aeab919c66ff7b816ae1ffeeae024d50312de76a7950f8c6268fbf454335cf252f961a67c47e67dc06fa590ba"), Hex.decode("02550cc87fa9061162b1dd395a16662529c9d8094c0feca17905a3244713d65fe8"), Hex.decode("02481f02b7140acbf3fcdd9f72cf9a7d9484d8125e6df7c9451cfa55ba3b077265"), Hex.decode("03f909ae15558c70cc751aff9b1f495199c325b13a9e5b934fd6299cd30ec50be8"), Hex.decode("02c6018fcbd3e89f3cf9c7f48b3232ea3638eb8bf217e59ee290f5f0cfb2fb9259"), Hex.decode("03b65694ccccda83cbb1e56b31308acd08e993114c33f66a456b627c2c1c68bed6") } }))); } @Test public void minimumSignaturesMustBePresent() { assertFails( () -> method.execute(new Object[]{ null, new Object[]{} }), "Minimum required signatures" ); } @Test public void minimumSignaturesMustBeGreaterThanZero() { assertFails( () -> method.execute(new Object[]{ BigInteger.ZERO, new Object[]{} }), "Minimum required signatures" ); } @Test public void mustProvideAtLeastTwoPublicKey() { assertFails( () -> method.execute(new Object[]{ BigInteger.ONE, new Object[]{} }), "At least 2 public keys" ); assertFails( () -> method.execute(new Object[]{ BigInteger.ONE, null }), "At least 2 public keys" ); assertFails( () -> method.execute(new Object[]{ BigInteger.ONE, new Object[]{Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7")} }), "At least 2 public keys" ); } @Test public void atLeastAsManyPublicKeyAsMinimumSignatures() { assertFails( () -> method.execute(new Object[]{ BigInteger.valueOf(3L), new Object[]{ Hex.decode("03b65694ccccda83cbb1e56b31308acd08e993114c33f66a456b627c2c1c68bed6"), Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7"), } }), "are less than the minimum required signatures" ); } @Test public void atMostFifteenPublicKeys() { byte[][] keys = new byte[16][]; for (int i = 0; i < 16; i++) { keys[i] = new BtcECKey().getPubKeyPoint().getEncoded(true); } assertFails( () -> method.execute(new Object[]{ BigInteger.valueOf(3L), keys }), "are more than the maximum allowed signatures" ); } @Test public void keyLengthIsValidated() { assertFails( () -> method.execute(new Object[]{ BigInteger.valueOf(1L), new Object[]{ Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7"), Hex.decode("aabbcc"), } }), "Invalid public key length" ); } @Test public void keyFormatIsValidated() { assertFails( () -> method.execute(new Object[]{ BigInteger.valueOf(1L), new Object[]{ Hex.decode("03566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7"), Hex.decode("08566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7"), } }), "Invalid public key format" ); }
ByteUtil { public static byte[] appendByte(byte[] bytes, byte b) { byte[] result = Arrays.copyOf(bytes, bytes.length + 1); result[result.length - 1] = b; 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 testAppendByte() { byte[] bytes = "tes".getBytes(); byte b = 0x74; Assert.assertArrayEquals("test".getBytes(), ByteUtil.appendByte(bytes, b)); }
GetMultisigScriptHash extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { Object[] keys = ((Object[]) parsedArguments[1]); if (keys == null || keys.length < 2) { return BASE_COST; } return BASE_COST + (keys.length - 2) * COST_PER_EXTRA_KEY; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] originalData); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); }
@Test public void gasIsBaseIfLessThanOrEqualstoTwoKeysPassed() { Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), null }, new byte[]{})); Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), new Object[]{ } }, new byte[]{})); Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), new Object[]{ Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7") } }, new byte[]{})); Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), new Object[]{ Hex.decode("02566d5ded7c7db1aa7ee4ef6f76989fb42527fcfdcddcd447d6793b7d869e46f7"), Hex.decode("aabbcc") } }, new byte[]{})); }
DeriveExtendedPublicKey extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("deriveExtendedPublicKey", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[1].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.outputs[0].type.getName()); }
DeriveExtendedPublicKey extends NativeMethod { @Override public boolean isEnabled() { return true; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
DeriveExtendedPublicKey extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
ByteUtil { public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) { if (b == null) { return EMPTY_BYTE_ARRAY; } byte[] bytes = new byte[numBytes]; byte[] biBytes = b.toByteArray(); int start = (biBytes.length == numBytes + 1) ? 1 : 0; int length = Math.min(biBytes.length, numBytes); System.arraycopy(biBytes, start, bytes, numBytes - length, length); 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 testBigIntegerToBytes() { byte[] expecteds = new byte[]{(byte) 0xff, (byte) 0xec, 0x78}; BigInteger b = BigInteger.valueOf(16772216); byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); } @Test public void testBigIntegerToBytesNegative() { byte[] expecteds = new byte[]{(byte) 0xff, 0x0, 0x13, (byte) 0x88}; BigInteger b = BigInteger.valueOf(-16772216); byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); } @Test public void testBigIntegerToBytesZero() { byte[] expecteds = new byte[]{0x00}; BigInteger b = BigInteger.ZERO; byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); }
DeriveExtendedPublicKey extends NativeMethod { @Override public Object execute(Object[] arguments) { if (arguments == null) { throw new NativeContractIllegalArgumentException("Must provide xpub and path arguments. None was provided"); } String xpub = (String) arguments[0]; String path = (String) arguments[1]; NetworkParameters params = helper.validateAndExtractNetworkFromExtendedPublicKey(xpub); DeterministicKey key; try { key = DeterministicKey.deserializeB58(xpub, params); } catch (IllegalArgumentException e) { throw new NativeContractIllegalArgumentException("Invalid extended public key", e); } if (path == null || path.length() == 0 || !isDecimal(path.substring(0,1)) || !isDecimal(path.substring(path.length()-1, path.length()))) { throwInvalidPath(path); } String[] pathChunks = path.split("/"); if (pathChunks.length > 10) { throw new NativeContractIllegalArgumentException("Path should contain 10 levels at most"); } if (Arrays.stream(pathChunks).anyMatch(s -> !isDecimal(s))) { throwInvalidPath(path); } List<ChildNumber> pathList; try { pathList = HDUtils.parsePath(path); } catch (NumberFormatException ex) { throw new NativeContractIllegalArgumentException(getInvalidPathErrorMessage(path), ex); } DeterministicKey derived = key; for (ChildNumber pathItem : pathList) { derived = HDKeyDerivation.deriveChildKey(derived, pathItem.getI()); } return derived.serializePubB58(params); } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void executes() { Assert.assertEquals( "tpubDCGMkPKredy7oh6zw8f4ExWFdTgQCrAHToF1ytny3gbVy9GkUNK2Nqh7NbKbh8dkd5VtjUiLJPkbEkeg29NVHwxYwzHJFt9SazGLZrrU4Y4", method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "2/3/4" })); Assert.assertEquals( "tpubDJ28nwFGUypUD6i8eGCQfMkwNGxzzabA5Mh7AcUdwm6ziFxCSWjy4HyhPXH5uU2ovdMMYLT9W3g3MrGo52TrprMvX8o1dzT2ZGz1pwCPTNv", method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "0/0/0/0/0/0" })); Assert.assertEquals( "tpubD8fY35uPCY1rUjMUZwhkGUFi33pwkffMEBaCsTSw1he2AbM6DMbPaRR2guvk5qTWDfE9ubFB5pzuUNnMtsqbCeKAAjfepSvEWyetyF9Q4fG", method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "2147483647" })); } @Test public void validatesExtendedPublicKeyFormat() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "this-is-not-an-xpub", "this-doesnt-matter" }); }, "Invalid extended public key"); } @Test public void ExtendedPublicKeyCannotBeNull() { assertFailsWithMessage(() -> { method.execute(new Object[]{ null, "M/0/1/2" }); }, "Invalid extended public key 'null"); } @Test public void pathCannotBeAnything() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "this-is-not-a-path" }); }, "Invalid path"); } @Test public void pathCannotBeNull() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", null }); }, "Invalid path"); } @Test public void pathCannotBeEmpty() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "" }); }, "Invalid path"); } @Test public void pathCannotContainALeadingM() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "M/0/1/2" }); }, "Invalid path"); } @Test public void pathCannotContainALeadingSlash() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "/0" }); }, "Invalid path"); } @Test public void pathCannotContainATrailingSlash() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "0/" }); }, "Invalid path"); } @Test public void pathCannotContainHardening() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "4'/5" }); }, "Invalid path"); } @Test public void pathCannotContainNegativeNumbers() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "0/-1" }); }, "Invalid path"); } @Test public void pathCannotContainPartsBiggerOrEqualThan2Pwr31() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "0/1/2/2147483648" }); }, "Invalid path"); } @Test public void pathCannotContainMoreThanTenParts() { assertFailsWithMessage(() -> { method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "0/1/2/3/4/5/6/7/8/9/10" }); }, "Path should contain 10 levels at most"); }
DeriveExtendedPublicKey extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 107_000L; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void gasIsCorrect() { Assert.assertEquals(107_000, method.getGas(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "2/3/4" }, new byte[]{})); }
HDWalletUtilsHelper { public NetworkParameters validateAndExtractNetworkFromExtendedPublicKey(String xpub) { if (xpub == null) { throw new NativeContractIllegalArgumentException(String.format("Invalid extended public key '%s'", xpub)); } if (xpub.startsWith("xpub")) { return NetworkParameters.fromID(NetworkParameters.ID_MAINNET); } else if (xpub.startsWith("tpub")) { return NetworkParameters.fromID(NetworkParameters.ID_TESTNET); } else { throw new NativeContractIllegalArgumentException(String.format("Invalid extended public key '%s'", xpub)); } } NetworkParameters validateAndExtractNetworkFromExtendedPublicKey(String xpub); }
@Test public void validateAndExtractNetworkFromExtendedPublicKeyMainnet() { Assert.assertEquals( NetworkParameters.fromID(NetworkParameters.ID_MAINNET), helper.validateAndExtractNetworkFromExtendedPublicKey("xpubSomethingSomething") ); } @Test public void validateAndExtractNetworkFromExtendedPublicKeyTestnet() { Assert.assertEquals( NetworkParameters.fromID(NetworkParameters.ID_TESTNET), helper.validateAndExtractNetworkFromExtendedPublicKey("tpubSomethingSomething") ); } @Test(expected = NativeContractIllegalArgumentException.class) public void validateAndExtractNetworkFromExtendedPublicKeyInvalid() { helper.validateAndExtractNetworkFromExtendedPublicKey("completelyInvalidStuff"); }
ToBase58Check extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("toBase58Check", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("bytes").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getType("int256").getName(), fn.inputs[1].type.getName()); Assert.assertEquals(1, fn.outputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.outputs[0].type.getName()); }
ToBase58Check extends NativeMethod { @Override public boolean isEnabled() { return true; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
ToBase58Check extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
ToBase58Check extends NativeMethod { @Override public Object execute(Object[] arguments) { if (arguments == null) { throw new NativeContractIllegalArgumentException(HASH_NOT_PRESENT); } byte[] hash = (byte[]) arguments[0]; if (hash == null) { throw new NativeContractIllegalArgumentException(HASH_NOT_PRESENT); } if (hash.length != 20) { throw new NativeContractIllegalArgumentException(String.format( HASH_INVALID, ByteUtil.toHexString(hash), hash.length )); } int version = ((BigInteger) arguments[1]).intValueExact(); if (version < 0 || version >= 256) { throw new NativeContractIllegalArgumentException(INVALID_VERSION); } return new ExtendedVersionedChecksummedBytes(version, hash).toBase58(); } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void executes() { Assert.assertEquals( "mgivuh9jErcGdRr81cJ3A7YfgbJV7WNyZV", method.execute(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(111L) })); } @Test public void validatesHashPresence() { try { method.execute(new Object[]{ Hex.decode("aabbcc"), BigInteger.valueOf(111L) }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Invalid hash160")); } } @Test public void validatesHashLength() { try { method.execute(new Object[]{ Hex.decode("aabbcc"), BigInteger.valueOf(111L) }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Invalid hash160")); } } @Test public void validatesVersion() { try { method.execute(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(-1L) }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("version must be a numeric value between 0 and 255")); } try { method.execute(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(256L) }); Assert.fail(); } catch (NativeContractIllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("version must be a numeric value between 0 and 255")); } }
ToBase58Check extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 13_000L; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @Override long getGas(Object[] parsedArguments, byte[] originalData); }
@Test public void gasIsCorrect() { Assert.assertEquals(13_000, method.getGas(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(111L) }, new byte[]{})); }
HDWalletUtils extends NativeContract { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.empty(); } HDWalletUtils(ActivationConfig config, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }
@Test public void hasNoDefaultMethod() { Assert.assertFalse(contract.getDefaultMethod().isPresent()); }
HDWalletUtils extends NativeContract { @Override public List<NativeMethod> getMethods() { return Arrays.asList( new ToBase58Check(getExecutionEnvironment()), new DeriveExtendedPublicKey(getExecutionEnvironment(), helper), new ExtractPublicKeyFromExtendedPublicKey(getExecutionEnvironment(), helper), new GetMultisigScriptHash(getExecutionEnvironment()) ); } HDWalletUtils(ActivationConfig config, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }
@Test public void hasFourMethods() { Assert.assertEquals(4, contract.getMethods().size()); }
BlockAccessor { public Optional<Block> getBlock(short blockDepth, ExecutionEnvironment environment) { if (blockDepth < 0) { throw new NativeContractIllegalArgumentException(String.format( "Invalid block depth '%d' (should be a non-negative value)", blockDepth )); } if (blockDepth >= maximumBlockDepth) { return Optional.empty(); } Block block = environment.getBlockStore().getBlockAtDepthStartingAt(blockDepth, environment.getBlock().getParentHash().getBytes()); if (block == null) { return Optional.empty(); } return Optional.of(block); } BlockAccessor(short maximumBlockDepth); Optional<Block> getBlock(short blockDepth, ExecutionEnvironment environment); }
@Test public void getBlockBeyondMaximumBlockDepth() { executionEnvironment = mock(ExecutionEnvironment.class); Assert.assertFalse(blockAccessor.getBlock(MAXIMUM_BLOCK_DEPTH, executionEnvironment).isPresent()); Assert.assertFalse(blockAccessor.getBlock((short) (MAXIMUM_BLOCK_DEPTH + 1), executionEnvironment).isPresent()); } @Test(expected = NativeContractIllegalArgumentException.class) public void getBlockWithNegativeDepth() { executionEnvironment = mock(ExecutionEnvironment.class); blockAccessor.getBlock(NEGATIVE_BLOCK_DEPTH, executionEnvironment); } @Test public void getGenesisBlock() { ExecutionEnvironment executionEnvironment = EnvironmentUtils.getEnvironmentWithBlockchainOfLength(1); Optional<Block> genesis = blockAccessor.getBlock(ZERO_BLOCK_DEPTH, executionEnvironment); Optional<Block> firstBlock = blockAccessor.getBlock(ONE_BLOCK_DEPTH, executionEnvironment); Assert.assertTrue(genesis.isPresent()); Assert.assertFalse(firstBlock.isPresent()); Assert.assertEquals(0, genesis.get().getNumber()); } @Test public void getTenBlocksFromTheTip() { ExecutionEnvironment executionEnvironment = EnvironmentUtils.getEnvironmentWithBlockchainOfLength(100); for(short i = 0; i < 10; i++) { Optional<Block> block = blockAccessor.getBlock(i, executionEnvironment); Assert.assertTrue(block.isPresent()); Assert.assertEquals(99 - i, block.get().getNumber()); } }
ByteUtil { @Nonnull public static String toHexString(@Nonnull byte[] data) { return Hex.toHexString(Objects.requireNonNull(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 testToHexString_ProducedHex() { byte[] data = new byte[] {(byte) 0xff, 0x0, 0x13, (byte) 0x88}; assertEquals(Hex.toHexString(data), ByteUtil.toHexString(data)); } @Test(expected = NullPointerException.class) public void testToHexString_NullPointerExceptionForNull() { assertEquals("", ByteUtil.toHexString(null)); }
BlockHeaderContract extends NativeContract { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.empty(); } BlockHeaderContract(ActivationConfig activationConfig, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }
@Test public void hasNoDefaultMethod() { Assert.assertFalse(contract.getDefaultMethod().isPresent()); }
BlockHeaderContract extends NativeContract { @Override public List<NativeMethod> getMethods() { return Arrays.asList( new GetCoinbaseAddress(getExecutionEnvironment(), this.blockAccessor), new GetBlockHash(getExecutionEnvironment(), this.blockAccessor), new GetMergedMiningTags(getExecutionEnvironment(), this.blockAccessor), new GetMinimumGasPrice(getExecutionEnvironment(), this.blockAccessor), new GetGasLimit(getExecutionEnvironment(), this.blockAccessor), new GetGasUsed(getExecutionEnvironment(), this.blockAccessor), new GetDifficulty(getExecutionEnvironment(), this.blockAccessor), new GetBitcoinHeader(getExecutionEnvironment(), this.blockAccessor), new GetUncleCoinbaseAddress(getExecutionEnvironment(), this.blockAccessor) ); } BlockHeaderContract(ActivationConfig activationConfig, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }
@Test public void hasNineMethods() { Assert.assertEquals(9, contract.getMethods().size()); }
NativeMethod { public ExecutionEnvironment getExecutionEnvironment() { return executionEnvironment; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }
@Test public void executionEnvironmentGetter() { Assert.assertEquals(executionEnvironment, method.getExecutionEnvironment()); }
NativeMethod { public long getGas(Object[] parsedArguments, byte[] originalData) { return originalData == null ? 0 : originalData.length * 2; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }
@Test public void getGasWithNullData() { Assert.assertEquals(0L, method.getGas(null, null)); } @Test public void getGasWithNonNullData() { Assert.assertEquals(6L, method.getGas(null, Hex.decode("aabbcc"))); Assert.assertEquals(10L, method.getGas(null, Hex.decode("aabbccddee"))); } @Test public void withArgumentsGetsGas() { Assert.assertEquals(6L, withArguments.getGas()); }
NativeMethod { public String getName() { return getFunction().name; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }
@Test public void getName() { function.name = "a-method-name"; Assert.assertEquals("a-method-name", method.getName()); }
NativeMethod { public abstract Object execute(Object[] arguments); NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalData); abstract boolean isEnabled(); abstract boolean onlyAllowsLocalCalls(); String getName(); }
@Test public void withArgumentsExecutesMethod() { Assert.assertEquals("execution-result", withArguments.execute()); }