target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@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")))); }
|
public BlockDifficulty add(BlockDifficulty other) { return new BlockDifficulty(value.add(other.value)); }
|
BlockDifficulty implements Comparable<BlockDifficulty>, Serializable { public BlockDifficulty add(BlockDifficulty other) { return new BlockDifficulty(value.add(other.value)); } }
|
BlockDifficulty implements Comparable<BlockDifficulty>, Serializable { public BlockDifficulty add(BlockDifficulty other) { return new BlockDifficulty(value.add(other.value)); } BlockDifficulty(BigInteger value); }
|
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); }
|
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 testEncodeBigInteger() { BigInteger test = new BigInteger("100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", 16); String expected = "a0100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"; byte[] encoderesult = encode(test); assertEquals(expected, ByteUtil.toHexString(encoderesult)); byte[] decodeResult = decode2(encoderesult).get(0).getRLPData(); assertEquals(test, BigIntegers.fromUnsignedByteArray(decodeResult)); }
|
public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } }
|
RLP { public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } } }
|
RLP { public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } } }
|
RLP { public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } } 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(); }
|
RLP { public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } } 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 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); }
|
@Override public String eth_protocolVersion() { return rsk_protocolVersion(); }
|
Web3Impl implements Web3 { @Override public String eth_protocolVersion() { return rsk_protocolVersion(); } }
|
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); }
|
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(); }
|
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 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)); }
|
@Override public int compareTo(@Nonnull BlockDifficulty other) { return value.compareTo(other.value); }
|
BlockDifficulty implements Comparable<BlockDifficulty>, Serializable { @Override public int compareTo(@Nonnull BlockDifficulty other) { return value.compareTo(other.value); } }
|
BlockDifficulty implements Comparable<BlockDifficulty>, Serializable { @Override public int compareTo(@Nonnull BlockDifficulty other) { return value.compareTo(other.value); } BlockDifficulty(BigInteger value); }
|
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); }
|
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 getEmptyAccountList() { Wallet wallet = WalletFactory.createWallet(); List<byte[]> addresses = wallet.getAccountAddresses(); Assert.assertNotNull(addresses); Assert.assertTrue(addresses.isEmpty()); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
public byte[] addAccountWithSeed(String seed) { return addAccountWithPrivateKey(Keccak256Helper.keccak256(seed.getBytes(StandardCharsets.UTF_8))); }
|
Wallet { public byte[] addAccountWithSeed(String seed) { return addAccountWithPrivateKey(Keccak256Helper.keccak256(seed.getBytes(StandardCharsets.UTF_8))); } }
|
Wallet { public byte[] addAccountWithSeed(String seed) { return addAccountWithPrivateKey(Keccak256Helper.keccak256(seed.getBytes(StandardCharsets.UTF_8))); } Wallet(KeyValueDataSource keyDS); }
|
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); }
|
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 unlockNonexistentAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Assert.assertFalse(wallet.unlockAccount(addr, "passphrase")); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
public boolean lockAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return false; } accounts.remove(addr); return true; } }
|
Wallet { public boolean lockAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return false; } accounts.remove(addr); return true; } } }
|
Wallet { public boolean lockAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return false; } accounts.remove(addr); return true; } } Wallet(KeyValueDataSource keyDS); }
|
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); }
|
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 lockNonexistentAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Assert.assertFalse(wallet.lockAccount(addr)); }
|
public boolean lockAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return false; } accounts.remove(addr); return true; } }
|
Wallet { public boolean lockAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return false; } accounts.remove(addr); return true; } } }
|
Wallet { public boolean lockAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return false; } accounts.remove(addr); return true; } } Wallet(KeyValueDataSource keyDS); }
|
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); }
|
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 getUnknownAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Account account = wallet.getAccount(addr); Assert.assertNull(account); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 createWithNoSnapshot() { Assert.assertNotNull(manager.getSnapshots()); Assert.assertTrue(manager.getSnapshots().isEmpty()); }
|
@VisibleForTesting public List<Long> getSnapshots() { return this.snapshots; }
|
SnapshotManager { @VisibleForTesting public List<Long> getSnapshots() { return this.snapshots; } }
|
SnapshotManager { @VisibleForTesting public List<Long> getSnapshots() { return this.snapshots; } SnapshotManager(
Blockchain blockchain,
BlockStore blockStore,
TransactionPool transactionPool,
MinerServer minerServer); }
|
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(); }
|
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 revertToNegativeSnapshot() { Assert.assertFalse(manager.revertToSnapshot(-1)); }
|
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 { 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 { 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); }
|
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(); }
|
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 testRlpEncode() { assertEquals(result01, ByteUtil.toHexString(encode(test01))); assertEquals(result02, ByteUtil.toHexString(encode(test02))); assertEquals(result03, ByteUtil.toHexString(encode(test03))); assertEquals(result04, ByteUtil.toHexString(encode(test04))); assertEquals(result05, ByteUtil.toHexString(encode(test05))); assertEquals(result06, ByteUtil.toHexString(encode(test06))); assertEquals(result07, ByteUtil.toHexString(encode(test07))); assertEquals(result08, ByteUtil.toHexString(encode(test08))); assertEquals(result09, ByteUtil.toHexString(encode(test09))); assertEquals(result10, ByteUtil.toHexString(encode(test10))); assertEquals(result11, ByteUtil.toHexString(encode(test11))); assertEquals(result12, ByteUtil.toHexString(encode(test12))); assertEquals(result13, ByteUtil.toHexString(encode(test13))); assertEquals(result14, ByteUtil.toHexString(encode(test14))); assertEquals(result15, ByteUtil.toHexString(encode(test15))); assertEquals(result16, ByteUtil.toHexString(encode(test16))); }
|
public static byte[] encode(Object input) { Value val = new Value(input); if (val.isList()) { List<Object> inputArray = val.asList(); if (inputArray.isEmpty()) { return encodeLength(inputArray.size(), OFFSET_SHORT_LIST); } byte[] output = ByteUtil.EMPTY_BYTE_ARRAY; for (Object object : inputArray) { output = concatenate(output, encode(object)); } byte[] prefix = encodeLength(output.length, OFFSET_SHORT_LIST); return concatenate(prefix, output); } else { byte[] inputAsBytes = toBytes(input); if (inputAsBytes.length == 1 && (inputAsBytes[0] & 0xff) < 0x80) { return inputAsBytes; } else { byte[] firstByte = encodeLength(inputAsBytes.length, OFFSET_SHORT_ITEM); return concatenate(firstByte, inputAsBytes); } } }
|
RLP { public static byte[] encode(Object input) { Value val = new Value(input); if (val.isList()) { List<Object> inputArray = val.asList(); if (inputArray.isEmpty()) { return encodeLength(inputArray.size(), OFFSET_SHORT_LIST); } byte[] output = ByteUtil.EMPTY_BYTE_ARRAY; for (Object object : inputArray) { output = concatenate(output, encode(object)); } byte[] prefix = encodeLength(output.length, OFFSET_SHORT_LIST); return concatenate(prefix, output); } else { byte[] inputAsBytes = toBytes(input); if (inputAsBytes.length == 1 && (inputAsBytes[0] & 0xff) < 0x80) { return inputAsBytes; } else { byte[] firstByte = encodeLength(inputAsBytes.length, OFFSET_SHORT_ITEM); return concatenate(firstByte, inputAsBytes); } } } }
|
RLP { public static byte[] encode(Object input) { Value val = new Value(input); if (val.isList()) { List<Object> inputArray = val.asList(); if (inputArray.isEmpty()) { return encodeLength(inputArray.size(), OFFSET_SHORT_LIST); } byte[] output = ByteUtil.EMPTY_BYTE_ARRAY; for (Object object : inputArray) { output = concatenate(output, encode(object)); } byte[] prefix = encodeLength(output.length, OFFSET_SHORT_LIST); return concatenate(prefix, output); } else { byte[] inputAsBytes = toBytes(input); if (inputAsBytes.length == 1 && (inputAsBytes[0] & 0xff) < 0x80) { return inputAsBytes; } else { byte[] firstByte = encodeLength(inputAsBytes.length, OFFSET_SHORT_ITEM); return concatenate(firstByte, inputAsBytes); } } } }
|
RLP { public static byte[] encode(Object input) { Value val = new Value(input); if (val.isList()) { List<Object> inputArray = val.asList(); if (inputArray.isEmpty()) { return encodeLength(inputArray.size(), OFFSET_SHORT_LIST); } byte[] output = ByteUtil.EMPTY_BYTE_ARRAY; for (Object object : inputArray) { output = concatenate(output, encode(object)); } byte[] prefix = encodeLength(output.length, OFFSET_SHORT_LIST); return concatenate(prefix, output); } else { byte[] inputAsBytes = toBytes(input); if (inputAsBytes.length == 1 && (inputAsBytes[0] & 0xff) < 0x80) { return inputAsBytes; } else { byte[] firstByte = encodeLength(inputAsBytes.length, OFFSET_SHORT_ITEM); return concatenate(firstByte, inputAsBytes); } } } 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(); }
|
RLP { public static byte[] encode(Object input) { Value val = new Value(input); if (val.isList()) { List<Object> inputArray = val.asList(); if (inputArray.isEmpty()) { return encodeLength(inputArray.size(), OFFSET_SHORT_LIST); } byte[] output = ByteUtil.EMPTY_BYTE_ARRAY; for (Object object : inputArray) { output = concatenate(output, encode(object)); } byte[] prefix = encodeLength(output.length, OFFSET_SHORT_LIST); return concatenate(prefix, output); } else { byte[] inputAsBytes = toBytes(input); if (inputAsBytes.length == 1 && (inputAsBytes[0] & 0xff) < 0x80) { return inputAsBytes; } else { byte[] firstByte = encodeLength(inputAsBytes.length, OFFSET_SHORT_ITEM); return concatenate(firstByte, inputAsBytes); } } } 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 revertToNonExistentSnapshot() { Assert.assertFalse(manager.revertToSnapshot(0)); Assert.assertFalse(manager.revertToSnapshot(1)); Assert.assertFalse(manager.revertToSnapshot(10)); }
|
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 { 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 { 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); }
|
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(); }
|
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 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()); }
|
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 { 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 { 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); }
|
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(); }
|
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 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())); }
|
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 { 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 { 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); }
|
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); }
|
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 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()); }
|
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 { 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 { 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); }
|
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); }
|
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 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())); }
|
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 { 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 { 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); }
|
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); }
|
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 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)); }
|
@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 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 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); }
|
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); }
|
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 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())); }
|
@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 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 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); }
|
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); }
|
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 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())); }
|
@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 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 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); }
|
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); }
|
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 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)); }
|
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 { 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 { 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); }
|
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); }
|
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 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()); }
|
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 { 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 { 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); }
|
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); }
|
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 testRlpDecode() { int pos = 0; String emptyString; byte[] decodedData; RLPList decodedList; emptyString = ByteUtil.toHexStringOrEmpty(decode2(Hex.decode(result01)).get(0).getRLPData()); assertEquals("", emptyString); emptyString = ByteUtil.toHexStringOrEmpty(decode2(Hex.decode(result02)).get(0).getRLPData()); assertEquals(test02, emptyString); decodedData = decode2(Hex.decode(result03)).get(0).getRLPData(); assertEquals(test03, bytesToAscii(decodedData)); decodedData = decode2(Hex.decode(result04)).get(0).getRLPData(); assertEquals(test04, bytesToAscii(decodedData)); decodedData = decode2(Hex.decode(result05)).get(0).getRLPData(); assertEquals(test05, bytesToAscii(decodedData)); decodedList = (RLPList) decode2(Hex.decode(result06)).get(0); assertEquals(test06[0], bytesToAscii(decodedList.get(0).getRLPData())); assertEquals(test06[1], bytesToAscii(decodedList.get(1).getRLPData())); decodedList = (RLPList) decode2(Hex.decode(result07)).get(0); assertEquals(test07[0], bytesToAscii(decodedList.get(0).getRLPData())); assertEquals(test07[1], bytesToAscii(decodedList.get(1).getRLPData())); assertEquals(test07[2], bytesToAscii(decodedList.get(2).getRLPData())); decodedData = decode2(Hex.decode(result08)).get(0).getRLPData(); assertEquals(test08, byteArrayToInt(decodedData)); decodedData = decode2(Hex.decode(result09)).get(0).getRLPData(); assertEquals(test09, byteArrayToInt(decodedData)); decodedData = decode2(Hex.decode(result10)).get(0).getRLPData(); assertEquals(test10, byteArrayToInt(decodedData)); decodedData = decode2(Hex.decode(result11)).get(0).getRLPData(); assertEquals(test11, byteArrayToInt(decodedData)); decodedData = decode2(Hex.decode(result12)).get(0).getRLPData(); assertTrue(test12.compareTo(BigIntegers.fromUnsignedByteArray(decodedData)) == 0); decodedData = decode2(Hex.decode(result13)).get(0).getRLPData(); assertTrue(test13.compareTo(BigIntegers.fromUnsignedByteArray(decodedData)) == 0); RLPList testObject1 = (RLPList) decode2(Hex.decode(result14)).get(0); assertTrue(Arrays.equals((byte[])expected14[0], testObject1.get(0).getRLPData())); assertTrue(Arrays.equals((byte[])expected14[1], testObject1.get(1).getRLPData())); assertTrue(((RLPList)testObject1.get(2)).size() == 0); RLPList testObject2 = (RLPList) decode2(Hex.decode(result15)).get(0); assertTrue(testObject2.size() == 2); assertTrue(((RLPList)testObject2.get(0)).size() == 2); assertTrue(((RLPList)testObject2.get(1)).size() == 0); assertTrue(((RLPList)((RLPList)testObject2.get(0)).get(0)).size() == 0); assertTrue(((RLPList)((RLPList)testObject2.get(0)).get(1)).size() == 0); RLPList testObject3 = (RLPList)decode2(Hex.decode(result16)).get(0); assertTrue(testObject3.size() == 3); assertTrue(Arrays.equals((byte[])expected16[0], testObject3.get(0).getRLPData())); assertTrue(((RLPList)testObject3.get(1)).size() == 1); assertTrue(Arrays.equals((byte[])((Object[])expected16[1])[0], ((RLPList)testObject3.get(1)).get(0).getRLPData())); assertTrue(Arrays.equals((byte[])expected16[2], testObject3.get(2).getRLPData())); }
|
@Nonnull public static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData) { ArrayList<RLPElement> elements = new ArrayList<>(); if (msgData == null) { return elements; } int tlength = msgData.length; int position = 0; while (position < tlength) { Pair<RLPElement, Integer> next = decodeElement(msgData, position); elements.add(next.getKey()); position = next.getValue(); } return elements; }
|
RLP { @Nonnull public static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData) { ArrayList<RLPElement> elements = new ArrayList<>(); if (msgData == null) { return elements; } int tlength = msgData.length; int position = 0; while (position < tlength) { Pair<RLPElement, Integer> next = decodeElement(msgData, position); elements.add(next.getKey()); position = next.getValue(); } return elements; } }
|
RLP { @Nonnull public static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData) { ArrayList<RLPElement> elements = new ArrayList<>(); if (msgData == null) { return elements; } int tlength = msgData.length; int position = 0; while (position < tlength) { Pair<RLPElement, Integer> next = decodeElement(msgData, position); elements.add(next.getKey()); position = next.getValue(); } return elements; } }
|
RLP { @Nonnull public static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData) { ArrayList<RLPElement> elements = new ArrayList<>(); if (msgData == null) { return elements; } int tlength = msgData.length; int position = 0; while (position < tlength) { Pair<RLPElement, Integer> next = decodeElement(msgData, position); elements.add(next.getKey()); position = next.getValue(); } return elements; } 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(); }
|
RLP { @Nonnull public static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData) { ArrayList<RLPElement> elements = new ArrayList<>(); if (msgData == null) { return elements; } int tlength = msgData.length; int position = 0; while (position < tlength) { Pair<RLPElement, Integer> next = decodeElement(msgData, position); elements.add(next.getKey()); position = next.getValue(); } return elements; } 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 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()); }
|
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 { 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 { 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); }
|
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); }
|
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 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()); }
|
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 { 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 { 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); }
|
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); }
|
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 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())); }
|
public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); }
|
FamilyUtils { public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); } }
|
FamilyUtils { public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); } }
|
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); }
|
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 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()); }
|
public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); }
|
FamilyUtils { public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); } }
|
FamilyUtils { public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); } }
|
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); }
|
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 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())); }
|
public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); }
|
FamilyUtils { public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); } }
|
FamilyUtils { public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); } }
|
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); }
|
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 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())); }
|
public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); }
|
FamilyUtils { public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); } }
|
FamilyUtils { public static Set<Keccak256> getFamily(BlockStore store, Block block, int levels) { return getFamily(store, block.getNumber(), block.getParentHash(), levels); } }
|
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); }
|
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 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)); }
|
public static List<BlockHeader> getUnclesHeaders(BlockStore store, Block block, int levels) { return getUnclesHeaders(store, block.getNumber(), block.getParentHash(), levels); }
|
FamilyUtils { public static List<BlockHeader> getUnclesHeaders(BlockStore store, Block block, int levels) { return getUnclesHeaders(store, block.getNumber(), block.getParentHash(), levels); } }
|
FamilyUtils { public static List<BlockHeader> getUnclesHeaders(BlockStore store, Block block, int levels) { return getUnclesHeaders(store, block.getNumber(), block.getParentHash(), levels); } }
|
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); }
|
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 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())); }
|
public static Set<Keccak256> getUncles(BlockStore store, Block block, int levels) { return getUncles(store, block.getNumber(), block.getParentHash(), levels); }
|
FamilyUtils { public static Set<Keccak256> getUncles(BlockStore store, Block block, int levels) { return getUncles(store, block.getNumber(), block.getParentHash(), levels); } }
|
FamilyUtils { public static Set<Keccak256> getUncles(BlockStore store, Block block, int levels) { return getUncles(store, block.getNumber(), block.getParentHash(), levels); } }
|
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); }
|
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 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); }
|
private void collect(long untilBlock) { BlockHeader untilHeader = blockStore.getChainBlockByNumber(untilBlock).getHeader(); multiTrieStore.collect(repositoryLocator.snapshotAt(untilHeader).getRoot()); }
|
GarbageCollector implements InternalService { private void collect(long untilBlock) { BlockHeader untilHeader = blockStore.getChainBlockByNumber(untilBlock).getHeader(); multiTrieStore.collect(repositoryLocator.snapshotAt(untilHeader).getRoot()); } }
|
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); }
|
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(); }
|
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 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); }
|
private void collect(long untilBlock) { BlockHeader untilHeader = blockStore.getChainBlockByNumber(untilBlock).getHeader(); multiTrieStore.collect(repositoryLocator.snapshotAt(untilHeader).getRoot()); }
|
GarbageCollector implements InternalService { private void collect(long untilBlock) { BlockHeader untilHeader = blockStore.getChainBlockByNumber(untilBlock).getHeader(); multiTrieStore.collect(repositoryLocator.snapshotAt(untilHeader).getRoot()); } }
|
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); }
|
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(); }
|
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 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)); }
|
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"); } }
|
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"); } } }
|
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"); } } }
|
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(); }
|
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 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()); }
|
@VisibleForTesting public BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs) { return execute(block, parent, discardInvalidTxs, false); }
|
BlockExecutor { @VisibleForTesting public BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs) { return execute(block, parent, discardInvalidTxs, false); } }
|
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); }
|
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); }
|
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 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()); }
|
public BlockResult executeAndFill(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, true, false); fill(block, result); return result; }
|
BlockExecutor { public BlockResult executeAndFill(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, true, false); fill(block, result); return 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); }
|
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); }
|
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 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); }
|
@VisibleForTesting public BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs) { return execute(block, parent, discardInvalidTxs, false); }
|
BlockExecutor { @VisibleForTesting public BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs) { return execute(block, parent, discardInvalidTxs, false); } }
|
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); }
|
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); }
|
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 validateBlock() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); Assert.assertTrue(executor.executeAndValidate(block, parent.getHeader())); }
|
@VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); }
|
BlockExecutor { @VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); } }
|
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); }
|
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); }
|
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 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())); }
|
@VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); }
|
BlockExecutor { @VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); } }
|
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); }
|
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); }
|
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 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())); }
|
@VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); }
|
BlockExecutor { @VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); } }
|
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); }
|
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); }
|
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 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())); }
|
@VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); }
|
BlockExecutor { @VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); } }
|
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); }
|
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); }
|
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 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())); }
|
@VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); }
|
BlockExecutor { @VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); } }
|
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); }
|
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); }
|
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 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())); }
|
@VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); }
|
BlockExecutor { @VisibleForTesting public boolean executeAndValidate(Block block, BlockHeader parent) { BlockResult result = execute(block, parent, false, false); return this.validate(block, result); } }
|
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); }
|
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); }
|
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 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); }
|
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; }
|
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; } }
|
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(); }
|
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); }
|
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 @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) { } }
|
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"); } }
|
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"); } } }
|
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"); } } }
|
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(); }
|
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(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); }
|
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; }
|
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; } }
|
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(); }
|
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); }
|
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 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); }
|
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; }
|
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; } }
|
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(); }
|
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); }
|
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 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()); }
|
private void onBestBlock(Block block, BlockResult result) { if (result != null && listener != null){ listener.onBestBlock(block, result.getTransactionReceipts()); } }
|
BlockChainImpl implements Blockchain { private void onBestBlock(Block block, BlockResult result) { if (result != null && listener != null){ listener.onBestBlock(block, result.getTransactionReceipts()); } } }
|
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); }
|
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(); }
|
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 nullBlockAsInvalidBlock() { Assert.assertEquals(ImportResult.INVALID_BLOCK, blockChain.tryToConnect(null)); }
|
@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 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 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); }
|
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(); }
|
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 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()); }
|
@Override public List<Block> getBlocksByNumber(long number) { return blockStore.getChainBlocksByNumber(number); }
|
BlockChainImpl implements Blockchain { @Override public List<Block> getBlocksByNumber(long number) { return blockStore.getChainBlocksByNumber(number); } }
|
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); }
|
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(); }
|
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 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); }
|
@Override public Block getBlockByNumber(long number) { return blockStore.getChainBlockByNumber(number); }
|
BlockChainImpl implements Blockchain { @Override public Block getBlockByNumber(long number) { return blockStore.getChainBlockByNumber(number); } }
|
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); }
|
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(); }
|
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 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); } }
|
@Override public Block getBestBlock() { return this.status.getBestBlock(); }
|
BlockChainImpl implements Blockchain { @Override public Block getBestBlock() { return this.status.getBestBlock(); } }
|
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); }
|
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(); }
|
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 getUnknownBlockByHash() { Assert.assertNull(blockChain.getBlockByHash(new BlockGenerator().getBlock(1).getHash().getBytes())); }
|
@Override public Block getBlockByHash(byte[] hash) { return blockStore.getBlockByHash(hash); }
|
BlockChainImpl implements Blockchain { @Override public Block getBlockByHash(byte[] hash) { return blockStore.getBlockByHash(hash); } }
|
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); }
|
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(); }
|
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 validateMinedBlockOne() { Block genesis = blockChain.getBestBlock(); Block block = new BlockGenerator().createChildBlock(genesis); Assert.assertTrue(blockExecutor.executeAndValidate(block, genesis.getHeader())); }
|
@Override public Block getBestBlock() { return this.status.getBestBlock(); }
|
BlockChainImpl implements Blockchain { @Override public Block getBestBlock() { return this.status.getBestBlock(); } }
|
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); }
|
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(); }
|
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 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())); }
|
@Override public Block getBestBlock() { return this.status.getBestBlock(); }
|
BlockChainImpl implements Blockchain { @Override public Block getBestBlock() { return this.status.getBestBlock(); } }
|
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); }
|
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(); }
|
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 encodeEdgeShortList() { String expectedOutput = "f7c0c0b4600160003556601359506301000000600035040f6018590060005660805460016080530160005760003560805760203560003557"; byte[] rlpKeysList = Hex.decode("c0"); byte[] rlpValuesList = Hex.decode("c0"); byte[] rlpCode = Hex.decode("b4600160003556601359506301000000600035040f6018590060005660805460016080530160005760003560805760203560003557"); byte[] output = encodeList(rlpKeysList, rlpValuesList, rlpCode); assertEquals(expectedOutput, ByteUtil.toHexString(output)); }
|
public static byte[] encodeList(byte[]... elements) { if (elements == null) { return new byte[]{(byte) OFFSET_SHORT_LIST}; } int totalLength = 0; for (byte[] element1 : elements) { totalLength += element1.length; } byte[] data; int copyPos; if (totalLength < SIZE_THRESHOLD) { data = new byte[1 + totalLength]; data[0] = (byte) (OFFSET_SHORT_LIST + totalLength); copyPos = 1; } 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); } data = new byte[1 + lenBytes.length + totalLength]; data[0] = (byte) (OFFSET_LONG_LIST + byteNum); System.arraycopy(lenBytes, 0, data, 1, lenBytes.length); copyPos = lenBytes.length + 1; } for (byte[] element : elements) { System.arraycopy(element, 0, data, copyPos, element.length); copyPos += element.length; } return data; }
|
RLP { public static byte[] encodeList(byte[]... elements) { if (elements == null) { return new byte[]{(byte) OFFSET_SHORT_LIST}; } int totalLength = 0; for (byte[] element1 : elements) { totalLength += element1.length; } byte[] data; int copyPos; if (totalLength < SIZE_THRESHOLD) { data = new byte[1 + totalLength]; data[0] = (byte) (OFFSET_SHORT_LIST + totalLength); copyPos = 1; } 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); } data = new byte[1 + lenBytes.length + totalLength]; data[0] = (byte) (OFFSET_LONG_LIST + byteNum); System.arraycopy(lenBytes, 0, data, 1, lenBytes.length); copyPos = lenBytes.length + 1; } for (byte[] element : elements) { System.arraycopy(element, 0, data, copyPos, element.length); copyPos += element.length; } return data; } }
|
RLP { public static byte[] encodeList(byte[]... elements) { if (elements == null) { return new byte[]{(byte) OFFSET_SHORT_LIST}; } int totalLength = 0; for (byte[] element1 : elements) { totalLength += element1.length; } byte[] data; int copyPos; if (totalLength < SIZE_THRESHOLD) { data = new byte[1 + totalLength]; data[0] = (byte) (OFFSET_SHORT_LIST + totalLength); copyPos = 1; } 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); } data = new byte[1 + lenBytes.length + totalLength]; data[0] = (byte) (OFFSET_LONG_LIST + byteNum); System.arraycopy(lenBytes, 0, data, 1, lenBytes.length); copyPos = lenBytes.length + 1; } for (byte[] element : elements) { System.arraycopy(element, 0, data, copyPos, element.length); copyPos += element.length; } return data; } }
|
RLP { public static byte[] encodeList(byte[]... elements) { if (elements == null) { return new byte[]{(byte) OFFSET_SHORT_LIST}; } int totalLength = 0; for (byte[] element1 : elements) { totalLength += element1.length; } byte[] data; int copyPos; if (totalLength < SIZE_THRESHOLD) { data = new byte[1 + totalLength]; data[0] = (byte) (OFFSET_SHORT_LIST + totalLength); copyPos = 1; } 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); } data = new byte[1 + lenBytes.length + totalLength]; data[0] = (byte) (OFFSET_LONG_LIST + byteNum); System.arraycopy(lenBytes, 0, data, 1, lenBytes.length); copyPos = lenBytes.length + 1; } for (byte[] element : elements) { System.arraycopy(element, 0, data, copyPos, element.length); copyPos += element.length; } return data; } 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(); }
|
RLP { public static byte[] encodeList(byte[]... elements) { if (elements == null) { return new byte[]{(byte) OFFSET_SHORT_LIST}; } int totalLength = 0; for (byte[] element1 : elements) { totalLength += element1.length; } byte[] data; int copyPos; if (totalLength < SIZE_THRESHOLD) { data = new byte[1 + totalLength]; data[0] = (byte) (OFFSET_SHORT_LIST + totalLength); copyPos = 1; } 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); } data = new byte[1 + lenBytes.length + totalLength]; data[0] = (byte) (OFFSET_LONG_LIST + byteNum); System.arraycopy(lenBytes, 0, data, 1, lenBytes.length); copyPos = lenBytes.length + 1; } for (byte[] element : elements) { System.arraycopy(element, 0, data, copyPos, element.length); copyPos += element.length; } return data; } 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 getUnknownTransactionInfoAsNull() { Assert.assertNull(blockChain.getTransactionInfo(new byte[] { 0x01 })); }
|
@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 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 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); }
|
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(); }
|
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 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())); }
|
@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 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 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); }
|
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(); }
|
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 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)); }
|
public static boolean blockInSomeBlockChain(Block block, Blockchain blockChain) { return blockInSomeBlockChain(block.getHash(), block.getNumber(), blockChain); }
|
BlockUtils { public static boolean blockInSomeBlockChain(Block block, Blockchain blockChain) { return blockInSomeBlockChain(block.getHash(), block.getNumber(), blockChain); } }
|
BlockUtils { public static boolean blockInSomeBlockChain(Block block, Blockchain blockChain) { return blockInSomeBlockChain(block.getHash(), block.getNumber(), blockChain); } private BlockUtils(); }
|
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); }
|
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 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())); }
|
public static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store) { Set<Keccak256> hashes = Collections.singleton(blockHash); return unknownAncestorsHashes(hashes, blockChain, store, true); }
|
BlockUtils { public static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store) { Set<Keccak256> hashes = Collections.singleton(blockHash); return unknownAncestorsHashes(hashes, blockChain, store, true); } }
|
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(); }
|
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); }
|
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 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())); }
|
public static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store) { Set<Keccak256> hashes = Collections.singleton(blockHash); return unknownAncestorsHashes(hashes, blockChain, store, true); }
|
BlockUtils { public static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store) { Set<Keccak256> hashes = Collections.singleton(blockHash); return unknownAncestorsHashes(hashes, blockChain, store, true); } }
|
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(); }
|
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); }
|
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 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)); }
|
public static boolean tooMuchProcessTime(long nanoseconds) { return nanoseconds > MAX_BLOCK_PROCESS_TIME_NANOSECONDS; }
|
BlockUtils { public static boolean tooMuchProcessTime(long nanoseconds) { return nanoseconds > MAX_BLOCK_PROCESS_TIME_NANOSECONDS; } }
|
BlockUtils { public static boolean tooMuchProcessTime(long nanoseconds) { return nanoseconds > MAX_BLOCK_PROCESS_TIME_NANOSECONDS; } private BlockUtils(); }
|
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); }
|
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 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()); }
|
@Override public PendingState getPendingState() { return getPendingState(getCurrentRepository()); }
|
TransactionPoolImpl implements TransactionPool { @Override public PendingState getPendingState() { return getPendingState(getCurrentRepository()); } }
|
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); }
|
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(); }
|
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 getEmptyPendingTransactionList() { List<Transaction> transactions = transactionPool.getPendingTransactions(); Assert.assertNotNull(transactions); Assert.assertTrue(transactions.isEmpty()); }
|
@Override public synchronized List<Transaction> getPendingTransactions() { removeObsoleteTransactions(this.outdatedThreshold, this.outdatedTimeout); return Collections.unmodifiableList(pendingTransactions.getTransactions()); }
|
TransactionPoolImpl implements TransactionPool { @Override public synchronized List<Transaction> getPendingTransactions() { removeObsoleteTransactions(this.outdatedThreshold, this.outdatedTimeout); return Collections.unmodifiableList(pendingTransactions.getTransactions()); } }
|
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); }
|
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(); }
|
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 getEmptyTransactionList() { List<Transaction> transactions = transactionPool.getPendingTransactions(); Assert.assertNotNull(transactions); Assert.assertTrue(transactions.isEmpty()); }
|
@Override public synchronized List<Transaction> getPendingTransactions() { removeObsoleteTransactions(this.outdatedThreshold, this.outdatedTimeout); return Collections.unmodifiableList(pendingTransactions.getTransactions()); }
|
TransactionPoolImpl implements TransactionPool { @Override public synchronized List<Transaction> getPendingTransactions() { removeObsoleteTransactions(this.outdatedThreshold, this.outdatedTimeout); return Collections.unmodifiableList(pendingTransactions.getTransactions()); } }
|
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); }
|
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(); }
|
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 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()); }
|
@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 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 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); }
|
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(); }
|
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 encodeBigIntegerEdge_1() { BigInteger integer = new BigInteger("80", 10); byte[] encodedData = encodeBigInteger(integer); System.out.println(ByteUtil.toHexString(encodedData)); }
|
public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } }
|
RLP { public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } } }
|
RLP { public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } } }
|
RLP { public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } } 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(); }
|
RLP { public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } } 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 checkRemascTxIsRejected() { RemascTransaction tx = new RemascTransaction(10); TransactionPoolAddResult result = transactionPool.addTransaction(tx); Assert.assertFalse(result.transactionsWereAdded()); Assert.assertEquals("transaction is a remasc transaction", result.getErrorMessage()); }
|
@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 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 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); }
|
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(); }
|
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 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()); }
|
@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 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 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); }
|
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(); }
|
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 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()); }
|
@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 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 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); }
|
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(); }
|
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 invalidTxsIsSentAndShouldntBeInCache(){ Coin balance = Coin.valueOf(0); createTestAccounts(2, balance); Transaction tx1 = createSampleTransaction(1, 2, 1000, 1); transactionPool.addTransaction(tx1); Assert.assertFalse(signatureCache.containsTx(tx1)); }
|
@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 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 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); }
|
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(); }
|
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 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)); }
|
@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 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 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); }
|
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(); }
|
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 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)); }
|
@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 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 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); }
|
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(); }
|
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 smallerBlockHashTest() { byte[] lowerHash = new byte[]{0}; byte[] biggerHash = new byte[]{1}; assertTrue(SelectionRule.isThisBlockHashSmaller(lowerHash, biggerHash)); assertFalse(SelectionRule.isThisBlockHashSmaller(biggerHash, lowerHash)); }
|
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; }
|
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; } }
|
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; } }
|
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); }
|
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 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)); }
|
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()); }
|
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()); } }
|
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()); } }
|
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); }
|
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 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(); }
|
private void flush() { if (nFlush == 0) { flushAll(); } nFlush++; nFlush = nFlush % flushNumberOfBlocks; }
|
BlockChainFlusher implements InternalService { private void flush() { if (nFlush == 0) { flushAll(); } nFlush++; nFlush = nFlush % flushNumberOfBlocks; } }
|
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); }
|
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(); }
|
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 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())); }
|
@Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } MiningMainchainViewImpl(BlockStore blockStore,
int height); }
|
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(); }
|
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 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)); }
|
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; }
|
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; } }
|
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; } }
|
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(); }
|
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 createWithLessBlocksThanMaxHeight() { MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( createBlockStore(10), 11); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(10)); }
|
@Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } MiningMainchainViewImpl(BlockStore blockStore,
int height); }
|
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(); }
|
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 createWithBlocksEqualToMaxHeight() { MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( createBlockStore(4), 4); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(4)); }
|
@Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } MiningMainchainViewImpl(BlockStore blockStore,
int height); }
|
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(); }
|
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 createWithMoreBlocksThanMaxHeight() { MiningMainchainViewImpl testBlockchain = new MiningMainchainViewImpl( createBlockStore(8), 6); List<BlockHeader> result = testBlockchain.get(); assertNotNull(result); assertThat(result.size(), is(6)); }
|
@Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } MiningMainchainViewImpl(BlockStore blockStore,
int height); }
|
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(); }
|
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 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)); }
|
@Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } MiningMainchainViewImpl(BlockStore blockStore,
int height); }
|
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(); }
|
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 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)); }
|
@Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } }
|
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } MiningMainchainViewImpl(BlockStore blockStore,
int height); }
|
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(); }
|
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(expected = IllegalArgumentException.class) public void instantiateMaxPlusOne() { new Uint24(Uint24.MAX_VALUE.intValue() + 1); }
|
public int intValue() { return intValue; }
|
Uint24 implements Comparable<Uint24> { public int intValue() { return intValue; } }
|
Uint24 implements Comparable<Uint24> { public int intValue() { return intValue; } Uint24(int intValue); }
|
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); }
|
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 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))); }
|
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 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 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); }
|
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); }
|
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(expected = ArrayIndexOutOfBoundsException.class) public void decodeSmallArray() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2}; Uint24.decode(bytes, 2); }
|
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 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 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); }
|
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); }
|
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 asByteReturnsByteValue() { Uint8 fortyTwo = new Uint8(42); assertThat(fortyTwo.asByte(), is((byte)42)); }
|
public byte asByte() { return (byte) intValue; }
|
Uint8 { public byte asByte() { return (byte) intValue; } }
|
Uint8 { public byte asByte() { return (byte) intValue; } Uint8(int intValue); }
|
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); }
|
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(expected = IllegalArgumentException.class) public void instantiateMaxPlusOne() { new Uint8((Uint8.MAX_VALUE.intValue() + 1)); }
|
public int intValue() { return intValue; }
|
Uint8 { public int intValue() { return intValue; } }
|
Uint8 { public int intValue() { return intValue; } Uint8(int intValue); }
|
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); }
|
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 public void testEncodeSet_2(){ Set<ByteArrayWrapper> data = new HashSet<>(); byte[] setEncoded = encodeSet(data); assertEquals("c0", ByteUtil.toHexString(setEncoded)); }
|
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; }
|
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; } }
|
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; } }
|
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(); }
|
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 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))); }
|
public static Uint8 decode(byte[] bytes, int offset) { int intValue = bytes[offset] & 0xFF; return new Uint8(intValue); }
|
Uint8 { public static Uint8 decode(byte[] bytes, int offset) { int intValue = bytes[offset] & 0xFF; return new Uint8(intValue); } }
|
Uint8 { public static Uint8 decode(byte[] bytes, int offset) { int intValue = bytes[offset] & 0xFF; return new Uint8(intValue); } Uint8(int intValue); }
|
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); }
|
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(expected = ArrayIndexOutOfBoundsException.class) public void decodeSmallArray() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2}; Uint8.decode(bytes, 3); }
|
public static Uint8 decode(byte[] bytes, int offset) { int intValue = bytes[offset] & 0xFF; return new Uint8(intValue); }
|
Uint8 { public static Uint8 decode(byte[] bytes, int offset) { int intValue = bytes[offset] & 0xFF; return new Uint8(intValue); } }
|
Uint8 { public static Uint8 decode(byte[] bytes, int offset) { int intValue = bytes[offset] & 0xFF; return new Uint8(intValue); } Uint8(int intValue); }
|
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); }
|
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 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); }
|
@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 { @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 { @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(); }
|
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(); }
|
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 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); }
|
public static RskAddress nullAddress() { return NULL_ADDRESS; }
|
RskAddress { public static RskAddress nullAddress() { return NULL_ADDRESS; } }
|
RskAddress { public static RskAddress nullAddress() { return NULL_ADDRESS; } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); }
|
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(); }
|
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 nullAddress() { Assert.assertArrayEquals(RskAddress.nullAddress().getBytes(), new byte[0]); }
|
public static RskAddress nullAddress() { return NULL_ADDRESS; }
|
RskAddress { public static RskAddress nullAddress() { return NULL_ADDRESS; } }
|
RskAddress { public static RskAddress nullAddress() { return NULL_ADDRESS; } RskAddress(DataWord address); RskAddress(String address); RskAddress(byte[] bytes); private RskAddress(); }
|
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(); }
|
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 jsonString_otherAddress() { String address = "0x0000000000000000000000000000000000000001"; RskAddress rskAddress = new RskAddress(address); Assert.assertEquals(address, rskAddress.toJsonString()); }
|
public String toJsonString() { if (NULL_ADDRESS.equals(this)) { return null; } return TypeConverter.toUnformattedJsonHex(this.getBytes()); }
|
RskAddress { public String toJsonString() { if (NULL_ADDRESS.equals(this)) { return null; } return TypeConverter.toUnformattedJsonHex(this.getBytes()); } }
|
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(); }
|
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(); }
|
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 zeroGetBytes() { assertThat(Coin.ZERO.getBytes(), is(new byte[]{0})); }
|
public byte[] getBytes() { return value.toByteArray(); }
|
Coin implements Comparable<Coin> { public byte[] getBytes() { return value.toByteArray(); } }
|
Coin implements Comparable<Coin> { public byte[] getBytes() { return value.toByteArray(); } Coin(byte[] value); Coin(BigInteger value); }
|
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); }
|
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 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() ); }
|
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); }
|
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); } }
|
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); }
|
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(); }
|
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 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); }
|
@Override public void save(Trie trie) { save(trie, true); }
|
TrieStoreImpl implements TrieStore { @Override public void save(Trie trie) { save(trie, true); } }
|
TrieStoreImpl implements TrieStore { @Override public void save(Trie trie) { save(trie, true); } TrieStoreImpl(KeyValueDataSource store); }
|
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(); }
|
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(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.