src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
BlockDifficulty implements Comparable<BlockDifficulty>, Serializable { public BlockDifficulty add(BlockDifficulty other) { return new BlockDifficulty(value.add(other.value)); } BlockDifficulty(BigInteger value); byte[] getBytes(); BigInteger asBigInteger(); @Override boolean equals(Object other); @Override int hashCode...
@Test public void addOneToZero() { BlockDifficulty d1 = new BlockDifficulty(BigInteger.ZERO); BlockDifficulty d2 = new BlockDifficulty(BigInteger.ONE); assertThat(d1.add(d2), is(d2)); } @Test public void addOneToOne() { BlockDifficulty d1 = new BlockDifficulty(BigInteger.ONE); BlockDifficulty d2 = new BlockDifficulty(B...
Web3Impl implements Web3 { @Override public String eth_protocolVersion() { return rsk_protocolVersion(); } protected Web3Impl( Ethereum eth, Blockchain blockchain, BlockStore blockStore, ReceiptStore receiptStore, RskSystemProperties config, Miner...
@Test public void eth_protocolVersion() throws Exception { World world = new World(); Web3Impl web3 = createWeb3(world); String netVersion = web3.eth_protocolVersion(); assertTrue("RSK net version different than one", netVersion.compareTo("1") == 0); }
BlockDifficulty implements Comparable<BlockDifficulty>, Serializable { @Override public int compareTo(@Nonnull BlockDifficulty other) { return value.compareTo(other.value); } BlockDifficulty(BigInteger value); byte[] getBytes(); BigInteger asBigInteger(); @Override boolean equals(Object other); @Override int hashCode()...
@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)); a...
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)); } ke...
@Test public void getEmptyAccountList() { Wallet wallet = WalletFactory.createWallet(); List<byte[]> addresses = wallet.getAccountAddresses(); Assert.assertNotNull(addresses); Assert.assertTrue(addresses.isEmpty()); }
Wallet { public byte[] addAccountWithSeed(String seed) { return addAccountWithPrivateKey(Keccak256Helper.keccak256(seed.getBytes(StandardCharsets.UTF_8))); } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String p...
@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, a...
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(KeyValueDataSou...
@Test public void unlockNonexistentAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Assert.assertFalse(wallet.unlockAccount(addr, "passphrase")); }
Wallet { public boolean lockAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return false; } accounts.remove(addr); return true; } } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress add...
@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...
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...
@Test public void getUnknownAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Account account = wallet.getAccount(addr); Assert.assertNull(account); }
Wallet { public byte[] addAccountWithPrivateKey(byte[] privateKeyBytes) { Account account = new Account(ECKey.fromPrivate(privateKeyBytes)); synchronized (accessLock) { RskAddress addr = addAccount(account); if (!this.initialAccounts.contains(addr)) { this.initialAccounts.add(addr); } return addr.getBytes(); } } Wallet...
@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(Keccak256Help...
SnapshotManager { @VisibleForTesting public List<Long> getSnapshots() { return this.snapshots; } SnapshotManager( Blockchain blockchain, BlockStore blockStore, TransactionPool transactionPool, MinerServer minerServer); int takeSnapshot(); boolean resetSnapshots(); boolean...
@Test public void createWithNoSnapshot() { Assert.assertNotNull(manager.getSnapshots()); Assert.assertTrue(manager.getSnapshots().isEmpty()); }
SnapshotManager { public boolean revertToSnapshot(int snapshotId) { if (snapshotId <= 0 || snapshotId > this.snapshots.size()) { return false; } long newBestBlockNumber = this.snapshots.get(snapshotId - 1); this.snapshots = this.snapshots.stream().limit(snapshotId).collect(Collectors.toList()); long currentBestBlockNum...
@Test public void revertToNegativeSnapshot() { Assert.assertFalse(manager.revertToSnapshot(-1)); } @Test public void revertToNonExistentSnapshot() { Assert.assertFalse(manager.revertToSnapshot(0)); Assert.assertFalse(manager.revertToSnapshot(1)); Assert.assertFalse(manager.revertToSnapshot(10)); } @Test public void rev...
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()), exe...
@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[...
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;...
@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)...
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(o...
@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_D...
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, ...
@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_D...
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(BlockS...
@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 = blockG...
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, ...
@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...
GarbageCollector implements InternalService { private void collect(long untilBlock) { BlockHeader untilHeader = blockStore.getChainBlockByNumber(untilBlock).getHeader(); multiTrieStore.collect(repositoryLocator.snapshotAt(untilHeader).getRoot()); } GarbageCollector(CompositeEthereumListener emitter, ...
@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...
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 ...
@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(expe...
BlockExecutor { @VisibleForTesting public BlockResult execute(Block block, BlockHeader parent, boolean discardInvalidTxs) { return execute(block, parent, discardInvalidTxs, false); } BlockExecutor( ActivationConfig activationConfig, RepositoryLocator repositoryLocator, StateRootHandl...
@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...
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...
@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("...
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, ...
@Test public void validateBlock() { TestObjects objects = generateBlockWithOneTransaction(); Block parent = objects.getParent(); Block block = objects.getBlock(); BlockExecutor executor = buildBlockExecutor(objects.getTrieStore()); Assert.assertTrue(executor.executeAndValidate(block, parent.getHeader())); } @Test publi...
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(); sta...
@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....
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, ...
@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.t...
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.getH...
@Test public void nullBlockAsInvalidBlock() { Assert.assertEquals(ImportResult.INVALID_BLOCK, blockChain.tryToConnect(null)); }
BlockChainImpl implements Blockchain { @Override public List<Block> getBlocksByNumber(long number) { return blockStore.getChainBlocksByNumber(number); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, ...
@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.t...
BlockChainImpl implements Blockchain { @Override public Block getBlockByNumber(long number) { return blockStore.getChainBlockByNumber(number); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, ...
@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.assertEq...
BlockChainImpl implements Blockchain { @Override public Block getBestBlock() { return this.status.getBestBlock(); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, ...
@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(blo...
BlockChainImpl implements Blockchain { @Override public Block getBlockByHash(byte[] hash) { return blockStore.getBlockByHash(hash); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumLi...
@Test public void getUnknownBlockByHash() { Assert.assertNull(blockChain.getBlockByHash(new BlockGenerator().getBlock(1).getHash().getBytes())); }
BlockChainImpl implements Blockchain { @Override public TransactionInfo getTransactionInfo(byte[] hash) { TransactionInfo txInfo = receiptStore.get(hash); if (txInfo == null) { return null; } Transaction tx = this.getBlockByHash(txInfo.getBlockHash()).getTransactionsList().get(txInfo.getIndex()); txInfo.setTransaction(...
@Test public void getUnknownTransactionInfoAsNull() { Assert.assertNull(blockChain.getTransactionInfo(new byte[] { 0x01 })); } @Test public void getTransactionInfo() { Block block = getBlockWithOneTransaction(); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block)); Transaction tx = block.getT...
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 blockCha...
@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, nu...
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 na...
@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, ...
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> unknownDirectAn...
@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.tooMuchP...
TransactionPoolImpl implements TransactionPool { @Override public PendingState getPendingState() { return getPendingState(getCurrentRepository()); } TransactionPoolImpl( RskSystemProperties config, RepositoryLocator repositoryLocator, BlockStore blockStore, BlockFactory b...
@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.ge...
TransactionPoolImpl implements TransactionPool { @Override public synchronized List<Transaction> getPendingTransactions() { removeObsoleteTransactions(this.outdatedThreshold, this.outdatedTimeout); return Collections.unmodifiableList(pendingTransactions.getTransactions()); } TransactionPoolImpl( RskSystemPr...
@Test public void getEmptyPendingTransactionList() { List<Transaction> transactions = transactionPool.getPendingTransactions(); Assert.assertNotNull(transactions); Assert.assertTrue(transactions.isEmpty()); } @Test public void getEmptyTransactionList() { List<Transaction> transactions = transactionPool.getPendingTransa...
TransactionPoolImpl implements TransactionPool { @Override public synchronized TransactionPoolAddResult addTransaction(final Transaction tx) { TransactionPoolAddResult internalResult = this.internalAddTransaction(tx); List<Transaction> pendingTransactionsAdded = new ArrayList<>(); if (!internalResult.transactionsWereAd...
@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 = transactionP...
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( BlockD...
@Test public void smallerBlockHashTest() { byte[] lowerHash = new byte[]{0}; byte[] biggerHash = new byte[]{1}; assertTrue(SelectionRule.isThisBlockHashSmaller(lowerHash, biggerHash)); assertFalse(SelectionRule.isThisBlockHashSmaller(biggerHash, lowerHash)); }
SelectionRule { public static boolean shouldWeAddThisBlock( BlockDifficulty blockDifficulty, BlockDifficulty currentDifficulty, Block block, Block currentBlock) { int compareDifficulties = blockDifficulty.compareTo(currentDifficulty); if (compareDifficulties > 0) { return true; } if (compareDifficulties < 0) { return f...
@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 h...
BlockChainFlusher implements InternalService { private void flush() { if (nFlush == 0) { flushAll(); } nFlush++; nFlush = nFlush % flushNumberOfBlocks; } BlockChainFlusher( int flushNumberOfBlocks, CompositeEthereumListener emitter, TrieStore trieStore, BlockStore blockSt...
@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...
MiningMainchainViewImpl implements MiningMainchainView { @Override public List<BlockHeader> get() { synchronized (internalBlockStoreReadWriteLock) { return Collections.unmodifiableList(mainchain); } } MiningMainchainViewImpl(BlockStore blockStore, int height); void addBest(BlockHeader...
@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).getNu...
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 byteNu...
@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); ...
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 fi...
@Test(expected = IllegalArgumentException.class) public void instantiateMaxPlusOne() { new Uint24(Uint24.MAX_VALUE.intValue() + 1); }
Uint24 implements Comparable<Uint24> { public static Uint24 decode(byte[] bytes, int offset) { int intValue = (bytes[offset + 2] & 0xFF) + ((bytes[offset + 1] & 0xFF) << 8) + ((bytes[offset ] & 0xFF) << 16); return new Uint24(intValue); } Uint24(int intValue); byte[] encode(); int intValue(); @Override boolean equals(O...
@Test public void decodeOffsettedValue() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2, (byte) 0xf4, 0x04, 0x55}; Uint24 decoded = Uint24.decode(bytes, 2); assertThat(decoded, is(new Uint24(15922180))); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void decodeSmallArray() { byte[] bytes = new b...
Uint8 { public byte asByte() { return (byte) intValue; } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }
@Test public void asByteReturnsByteValue() { Uint8 fortyTwo = new Uint8(42); assertThat(fortyTwo.asByte(), is((byte)42)); }
Uint8 { public int intValue() { return intValue; } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] bytes, int offset); static final int BYTES; static final Uint8 MAX_VALUE; }
@Test(expected = IllegalArgumentException.class) public void instantiateMaxPlusOne() { new Uint8((Uint8.MAX_VALUE.intValue() + 1)); }
RLP { public static byte[] encodeSet(Set<ByteArrayWrapper> data) { int dataLength = 0; Set<byte[]> encodedElements = new HashSet<>(); for (ByteArrayWrapper element : data) { byte[] encodedElement = RLP.encodeElement(element.getData()); dataLength += encodedElement.length; encodedElements.add(encodedElement); } byte[] l...
@Test public void testEncodeSet_2(){ Set<ByteArrayWrapper> data = new HashSet<>(); byte[] setEncoded = encodeSet(data); assertEquals("c0", ByteUtil.toHexString(setEncoded)); }
Uint8 { public static Uint8 decode(byte[] bytes, int offset) { int intValue = bytes[offset] & 0xFF; return new Uint8(intValue); } Uint8(int intValue); byte asByte(); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Uint8 decode(byte[] byt...
@Test public void decodeOffsettedValue() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf3, (byte) 0xf4, 0x04, 0x55}; Uint8 decoded = Uint8.decode(bytes, 2); assertThat(decoded, is(new Uint8(243))); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void decodeSmallArray() { byte[] bytes = new byte[] {0...
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 add...
@Test public void testEquals() { RskAddress senderA = new RskAddress("0000000000000000000000000000000001000006"); RskAddress senderB = new RskAddress("0000000000000000000000000000000001000006"); RskAddress senderC = new RskAddress("0000000000000000000000000000000001000008"); RskAddress senderD = RskAddress.nullAddress(...
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 hashCo...
@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, sen...
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(); Strin...
@Test public void jsonString_otherAddress() { String address = "0x0000000000000000000000000000000000000001"; RskAddress rskAddress = new RskAddress(address); Assert.assertEquals(address, rskAddress.toJsonString()); }
Coin implements Comparable<Coin> { public byte[] getBytes() { return value.toByteArray(); } Coin(byte[] value); Coin(BigInteger value); byte[] getBytes(); BigInteger asBigInteger(); Coin negate(); Coin add(Coin val); Coin subtract(Coin val); Coin multiply(BigInteger val); Coin divide(BigInteger val); Coin[] divideAndR...
@Test public void zeroGetBytes() { assertThat(Coin.ZERO.getBytes(), is(new byte[]{0})); }
TrieKeySlice { public TrieKeySlice leftPad(int paddingLength) { if (paddingLength == 0) { return this; } int currentLength = length(); byte[] paddedExpandedKey = new byte[currentLength + paddingLength]; System.arraycopy(expandedKey, offset, paddedExpandedKey, paddingLength, currentLength); return new TrieKeySlice(padde...
@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 ...
TrieStoreImpl implements TrieStore { @Override public void save(Trie trie) { save(trie, true); } TrieStoreImpl(KeyValueDataSource store); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] hash); @Override byte[] retrieveValue(byte[] hash); @Override void dispose(); }
@Test public void saveTrieNode() { Trie trie = new Trie(store).put("foo", "bar".getBytes()); store.save(trie); verify(map, times(1)).put(trie.getHash().getBytes(), trie.toMessage()); verify(map, times(1)).get(trie.getHash().getBytes()); verifyNoMoreInteractions(map); } @Test public void saveFullTrie() { Trie trie = new...
TrieStoreImpl implements TrieStore { @Override public Optional<Trie> retrieve(byte[] hash) { byte[] message = this.store.get(hash); if (message == null) { return Optional.empty(); } Trie trie = Trie.fromMessage(message, this); savedTries.add(trie); return Optional.of(trie); } TrieStoreImpl(KeyValueDataSource store); @O...
@Test public void retrieveTrieNotFound() { Assert.assertFalse(store.retrieve(new byte[] { 0x01, 0x02, 0x03, 0x04 }).isPresent()); }
TrieConverter { public byte[] getOrchidAccountTrieRoot(Trie src) { Metric metric = profiler.start(Profiler.PROFILING_TYPE.TRIE_CONVERTER_GET_ACCOUNT_ROOT); byte[] trieRoot = cacheHashes.computeIfAbsent(src.getHash(), k -> { Trie trie = getOrchidAccountTrieRoot(src.getSharedPath(), src, true); return trie == null ? Hash...
@Test public void getOrchidAccountTrieRootWithCompressedStorageKeys() { TrieStore trieStore = new TrieStoreImpl(new HashMapDB()); Repository repository = new MutableRepository(new MutableTrieImpl(trieStore, new Trie(trieStore))); Repository track = repository.startTracking(); TestUtils.getRandom().setSeed(0); int maxAc...
PathEncoder { @Nonnull public static byte[] encode(byte[] path) { if (path == null) { throw new IllegalArgumentException("path"); } return encodeBinaryPath(path); } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int length); static int calculateEncodedL...
@Test public void encodeNullBinaryPath() { try { PathEncoder.encode(null); Assert.fail(); } catch (Exception ex) { Assert.assertTrue(ex instanceof IllegalArgumentException); } } @Test public void encodeBinaryPathOneByte() { byte[] path = new byte[] { 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01 }; byte[] encoded = Pa...
PathEncoder { @Nonnull private static byte[] encodeBinaryPath(byte[] path) { int lpath = path.length; int lencoded = calculateEncodedLength(lpath); byte[] encoded = new byte[lencoded]; int nbyte = 0; for (int k = 0; k < lpath; k++) { int offset = k % 8; if (k > 0 && offset == 0) { nbyte++; } if (path[k] == 0) { continu...
@Test public void encodeBinaryPath() { byte[] path = new byte[] { 0x00, 0x01, 0x01 }; byte[] encoded = PathEncoder.encode(path); Assert.assertNotNull(encoded); Assert.assertArrayEquals(new byte[] { 0x60 }, encoded); }
Web3Impl implements Web3 { @Override public String net_peerCount() { String s = null; try { int n = channelManager.getActivePeers().size(); return s = TypeConverter.toQuantityJsonHex(n); } finally { if (logger.isDebugEnabled()) { logger.debug("net_peerCount(): {}", s); } } } protected Web3Impl( Ethereum et...
@Test public void net_peerCount() throws Exception { Web3Impl web3 = createWeb3(); String peerCount = web3.net_peerCount(); Assert.assertEquals("Different number of peers than expected", "0x0", peerCount); }
PathEncoder { @Nonnull public static byte[] decode(byte[] encoded, int length) { if (encoded == null) { throw new IllegalArgumentException("encoded"); } return decodeBinaryPath(encoded, length); } private PathEncoder(); @Nonnull static byte[] encode(byte[] path); @Nonnull static byte[] decode(byte[] encoded, int lengt...
@Test public void decodeNullBinaryPath() { try { PathEncoder.decode(null, 0); Assert.fail(); } catch (Exception ex) { Assert.assertTrue(ex instanceof IllegalArgumentException); } } @Test public void decodeBinaryPathOneByte() { byte[] encoded = new byte[] { 0x6d }; byte[] path = PathEncoder.decode(encoded, 8); Assert.as...
PathEncoder { @Nonnull private static byte[] decodeBinaryPath(byte[] encoded, int bitlength) { byte[] path = new byte[bitlength]; for (int k = 0; k < bitlength; k++) { int nbyte = k / 8; int offset = k % 8; if (((encoded[nbyte] >> (7 - offset)) & 0x01) != 0) { path[k] = 1; } } return path; } private PathEncoder(); @No...
@Test public void decodeBinaryPath() { byte[] encoded = new byte[] { 0x60 }; byte[] path = PathEncoder.decode(encoded, 3); Assert.assertNotNull(path); Assert.assertArrayEquals(new byte[] { 0x00, 0x01, 0x01 }, path); }
MultiTrieStore implements TrieStore { @Override public void save(Trie trie) { getCurrentStore().save(trie); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] roo...
@Test public void callsSaveOnlyOnNewestStore() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInsta...
MultiTrieStore implements TrieStore { @Override public void flush() { epochs.forEach(TrieStore::flush); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] rootHas...
@Test public void callsFlushOnAllStores() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance("...
MultiTrieStore implements TrieStore { @Override public void dispose() { epochs.forEach(TrieStore::dispose); } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory, OnEpochDispose disposer); @Override void save(Trie trie); @Override void flush(); @Override Optional<Trie> retrieve(byte[] roo...
@Test public void callsDisposeOnAllStores() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFactory.newInstance...
MultiTrieStore implements TrieStore { @Override public byte[] retrieveValue(byte[] hash) { for (TrieStore epochTrieStore : epochs) { byte[] value = epochTrieStore.retrieveValue(hash); if (value != null) { return value; } } return null; } MultiTrieStore(int currentEpoch, int liveEpochs, TrieStoreFactory trieStoreFactory...
@Test public void retrievesValueFromNewestStoreWithValue() { TrieStore store1 = mock(TrieStore.class); TrieStore store2 = mock(TrieStore.class); TrieStore store3 = mock(TrieStore.class); TrieStoreFactory storeFactory = mock(TrieStoreFactory.class); when(storeFactory.newInstance("46")).thenReturn(store1); when(storeFact...
BitSet { public boolean get(int position) { if (position < 0 || position >= this.size) { throw new IndexOutOfBoundsException(String.format("Index: %s, Size: %s", position, this.size)); } int offset = position / 8; int bitoffset = position % 8; return (this.bytes[offset] & 0xff & (1 << bitoffset)) != 0; } BitSet(int siz...
@Test public void exceptionIfGetWithNegativePosition() { BitSet set = new BitSet(17); try { set.get(-1); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: -1, Size: 17", ex.getMessage()); } } @Test public void exceptionIfGetWithOutOfBoundPosition() { BitSet set = new BitSet(17); try { ...
BitSet { public void set(int position) { if (position < 0 || position >= this.size) { throw new IndexOutOfBoundsException(String.format("Index: %s, Size: %s", position, this.size)); } int offset = position / 8; int bitoffset = position % 8; this.bytes[offset] |= 1 << bitoffset; } BitSet(int size); void set(int position...
@Test public void exceptionIfSetWithNegativePosition() { BitSet set = new BitSet(17); try { set.set(-1); Assert.fail(); } catch (IndexOutOfBoundsException ex) { Assert.assertEquals("Index: -1, Size: 17", ex.getMessage()); } } @Test public void exceptionIfSetWithOutOfBoundPosition() { BitSet set = new BitSet(17); try { ...
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execu...
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("extractPublicKeyFromExtendedPublicKey", fn.name); Assert.assertEquals(1, fn.inputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(1...
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public boolean isEnabled() { return true; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments);...
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[]...
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public Object execute(Object[] arguments) { if (arguments == null) { throw new NativeContractIllegalArgumentException(String.format(INVALID_EXTENDED_PUBLIC_KEY, null)); } String xpub = (String) arguments[0]; NetworkParameters params = helper.validat...
@Test public void executes() { Assert.assertEquals( "02be517550b9e3be7fe42c80932d51e88e698663b4926e598b269d050e87e34d8c", ByteUtil.toHexString((byte[]) method.execute(new Object[]{ "xpub661MyMwAqRbcFMGNG2YcHvj3x63bAZN9U5cKikaiQ4zu2D1cvpnZYyXNR9nH62sGp4RR39Ui7SVQSq1PY4JbPuEuu5prVJJC3d5Pogft712", }))); } @Test public voi...
RLP { @Nullable public static RLPElement decode2OneItem(@CheckForNull byte[] msgData, int startPos) { if (msgData == null) { return null; } return RLP.decodeFirstElement(msgData, startPos); } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int index); static byte[] decodeI...
@Test public void partialDataParseTest() { String hex = "000080c180000000000000000000000042699b1104e93abf0008be55f912c2ff"; RLPList el = (RLPList) decode2OneItem(Hex.decode(hex), 3); assertEquals(1, el.size()); }
ExtractPublicKeyFromExtendedPublicKey extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 11_300L; } ExtractPublicKeyFromExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Ov...
@Test public void gasIsCorrect() { Assert.assertEquals(11_300, method.getGas(new Object[]{ "xpub661MyMwAqRbcFMGNG2YcHvj3x63bAZN9U5cKikaiQ4zu2D1cvpnZYyXNR9nH62sGp4RR39Ui7SVQSq1PY4JbPuEuu5prVJJC3d5Pogft712" }, new byte[]{})); }
GetMultisigScriptHash extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parse...
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("getMultisigScriptHash", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("int256").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getT...
GetMultisigScriptHash extends NativeMethod { @Override public boolean isEnabled() { return true; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments, byte[] orig...
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
GetMultisigScriptHash extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } GetMultisigScriptHash(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override long getGas(Object[] parsedArguments,...
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
GetMultisigScriptHash extends NativeMethod { @Override public Object execute(Object[] arguments) { if (arguments == null || arguments[0] == null) { throw new NativeContractIllegalArgumentException(REQUIRED_SIGNATURE_NULL_OR_ZERO); } int minimumSignatures = ((BigInteger) arguments[0]).intValueExact(); Object[] publicKey...
@Test public void executesWithAllCompressed() { Assert.assertEquals( "51f103320b435b5fe417b3f3e0f18972ccc710a0", ByteUtil.toHexString((byte[]) method.execute(new Object[]{ BigInteger.valueOf(8L), new byte[][] { Hex.decode("03b53899c390573471ba30e5054f78376c5f797fda26dde7a760789f02908cbad2"), Hex.decode("027319afb15481d...
ByteUtil { public static byte[] appendByte(byte[] bytes, byte b) { byte[] result = Arrays.copyOf(bytes, bytes.length + 1); result[result.length - 1] = b; return result; } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteg...
@Test public void testAppendByte() { byte[] bytes = "tes".getBytes(); byte b = 0x74; Assert.assertArrayEquals("test".getBytes(), ByteUtil.appendByte(bytes, b)); }
GetMultisigScriptHash extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { Object[] keys = ((Object[]) parsedArguments[1]); if (keys == null || keys.length < 2) { return BASE_COST; } return BASE_COST + (keys.length - 2) * COST_PER_EXTRA_KEY; } GetMultisigScriptHash(Execut...
@Test public void gasIsBaseIfLessThanOrEqualstoTwoKeysPassed() { Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), null }, new byte[]{})); Assert.assertEquals(20_000L, method.getGas(new Object[]{ BigInteger.valueOf(1L), new Object[]{ } }, new byte[]{})); Assert.assertEquals(20_000L, metho...
DeriveExtendedPublicKey extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Ove...
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("deriveExtendedPublicKey", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("string").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.ge...
DeriveExtendedPublicKey extends NativeMethod { @Override public boolean isEnabled() { return true; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled...
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
DeriveExtendedPublicKey extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boole...
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
ByteUtil { public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) { if (b == null) { return EMPTY_BYTE_ARRAY; } byte[] bytes = new byte[numBytes]; byte[] biBytes = b.toByteArray(); int start = (biBytes.length == numBytes + 1) ? 1 : 0; int length = Math.min(biBytes.length, numBytes); System.arraycopy(biBytes...
@Test public void testBigIntegerToBytes() { byte[] expecteds = new byte[]{(byte) 0xff, (byte) 0xec, 0x78}; BigInteger b = BigInteger.valueOf(16772216); byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); } @Test public void testBigIntegerToBytesNegative() { byte[] expecteds = new byte...
DeriveExtendedPublicKey extends NativeMethod { @Override public Object execute(Object[] arguments) { if (arguments == null) { throw new NativeContractIllegalArgumentException("Must provide xpub and path arguments. None was provided"); } String xpub = (String) arguments[0]; String path = (String) arguments[1]; NetworkPa...
@Test public void executes() { Assert.assertEquals( "tpubDCGMkPKredy7oh6zw8f4ExWFdTgQCrAHToF1ytny3gbVy9GkUNK2Nqh7NbKbh8dkd5VtjUiLJPkbEkeg29NVHwxYwzHJFt9SazGLZrrU4Y4", method.execute(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "2/3/4" }...
DeriveExtendedPublicKey extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 107_000L; } DeriveExtendedPublicKey(ExecutionEnvironment executionEnvironment, HDWalletUtilsHelper helper); @Override CallTransaction.Function getFunction(); @Override Object execute(Objec...
@Test public void gasIsCorrect() { Assert.assertEquals(107_000, method.getGas(new Object[]{ "tpubD6NzVbkrYhZ4YHQqwWz3Tm1ESZ9AidobeyLG4mEezB6hN8gFFWrcjczyF77Lw3HEs6Rjd2R11BEJ8Y9ptfxx9DFknkdujp58mFMx9H5dc1r", "2/3/4" }, new byte[]{})); }
HDWalletUtilsHelper { public NetworkParameters validateAndExtractNetworkFromExtendedPublicKey(String xpub) { if (xpub == null) { throw new NativeContractIllegalArgumentException(String.format("Invalid extended public key '%s'", xpub)); } if (xpub.startsWith("xpub")) { return NetworkParameters.fromID(NetworkParameters.I...
@Test public void validateAndExtractNetworkFromExtendedPublicKeyMainnet() { Assert.assertEquals( NetworkParameters.fromID(NetworkParameters.ID_MAINNET), helper.validateAndExtractNetworkFromExtendedPublicKey("xpubSomethingSomething") ); } @Test public void validateAndExtractNetworkFromExtendedPublicKeyTestnet() { Assert...
ToBase58Check extends NativeMethod { @Override public CallTransaction.Function getFunction() { return function; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onl...
@Test public void functionSignatureOk() { CallTransaction.Function fn = method.getFunction(); Assert.assertEquals("toBase58Check", fn.name); Assert.assertEquals(2, fn.inputs.length); Assert.assertEquals(SolidityType.getType("bytes").getName(), fn.inputs[0].type.getName()); Assert.assertEquals(SolidityType.getType("int2...
ToBase58Check extends NativeMethod { @Override public boolean isEnabled() { return true; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLocalCalls(); @O...
@Test public void shouldBeEnabled() { Assert.assertTrue(method.isEnabled()); }
ToBase58Check extends NativeMethod { @Override public boolean onlyAllowsLocalCalls() { return false; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @Override boolean onlyAllowsLoca...
@Test public void shouldAllowAnyTypeOfCall() { Assert.assertFalse(method.onlyAllowsLocalCalls()); }
ToBase58Check extends NativeMethod { @Override public Object execute(Object[] arguments) { if (arguments == null) { throw new NativeContractIllegalArgumentException(HASH_NOT_PRESENT); } byte[] hash = (byte[]) arguments[0]; if (hash == null) { throw new NativeContractIllegalArgumentException(HASH_NOT_PRESENT); } if (has...
@Test public void executes() { Assert.assertEquals( "mgivuh9jErcGdRr81cJ3A7YfgbJV7WNyZV", method.execute(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(111L) })); } @Test public void validatesHashPresence() { try { method.execute(new Object[]{ Hex.decode("aabbcc"), BigInteger.v...
ToBase58Check extends NativeMethod { @Override public long getGas(Object[] parsedArguments, byte[] originalData) { return 13_000L; } ToBase58Check(ExecutionEnvironment executionEnvironment); @Override CallTransaction.Function getFunction(); @Override Object execute(Object[] arguments); @Override boolean isEnabled(); @O...
@Test public void gasIsCorrect() { Assert.assertEquals(13_000, method.getGas(new Object[]{ Hex.decode("0d3bf5f30dda7584645546079318e97f0e1d044f"), BigInteger.valueOf(111L) }, new byte[]{})); }
HDWalletUtils extends NativeContract { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.empty(); } HDWalletUtils(ActivationConfig config, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }
@Test public void hasNoDefaultMethod() { Assert.assertFalse(contract.getDefaultMethod().isPresent()); }
HDWalletUtils extends NativeContract { @Override public List<NativeMethod> getMethods() { return Arrays.asList( new ToBase58Check(getExecutionEnvironment()), new DeriveExtendedPublicKey(getExecutionEnvironment(), helper), new ExtractPublicKeyFromExtendedPublicKey(getExecutionEnvironment(), helper), new GetMultisigScrip...
@Test public void hasFourMethods() { Assert.assertEquals(4, contract.getMethods().size()); }
BlockAccessor { public Optional<Block> getBlock(short blockDepth, ExecutionEnvironment environment) { if (blockDepth < 0) { throw new NativeContractIllegalArgumentException(String.format( "Invalid block depth '%d' (should be a non-negative value)", blockDepth )); } if (blockDepth >= maximumBlockDepth) { return Optional...
@Test public void getBlockBeyondMaximumBlockDepth() { executionEnvironment = mock(ExecutionEnvironment.class); Assert.assertFalse(blockAccessor.getBlock(MAXIMUM_BLOCK_DEPTH, executionEnvironment).isPresent()); Assert.assertFalse(blockAccessor.getBlock((short) (MAXIMUM_BLOCK_DEPTH + 1), executionEnvironment).isPresent()...
ByteUtil { @Nonnull public static String toHexString(@Nonnull byte[] data) { return Hex.toHexString(Objects.requireNonNull(data)); } private ByteUtil(); static byte[] appendByte(byte[] bytes, byte b); static byte[] cloneBytes(byte[] bytes); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] big...
@Test public void testToHexString_ProducedHex() { byte[] data = new byte[] {(byte) 0xff, 0x0, 0x13, (byte) 0x88}; assertEquals(Hex.toHexString(data), ByteUtil.toHexString(data)); } @Test(expected = NullPointerException.class) public void testToHexString_NullPointerExceptionForNull() { assertEquals("", ByteUtil.toHexStr...
BlockHeaderContract extends NativeContract { @Override public Optional<NativeMethod> getDefaultMethod() { return Optional.empty(); } BlockHeaderContract(ActivationConfig activationConfig, RskAddress contractAddress); @Override List<NativeMethod> getMethods(); @Override Optional<NativeMethod> getDefaultMethod(); }
@Test public void hasNoDefaultMethod() { Assert.assertFalse(contract.getDefaultMethod().isPresent()); }
BlockHeaderContract extends NativeContract { @Override public List<NativeMethod> getMethods() { return Arrays.asList( new GetCoinbaseAddress(getExecutionEnvironment(), this.blockAccessor), new GetBlockHash(getExecutionEnvironment(), this.blockAccessor), new GetMergedMiningTags(getExecutionEnvironment(), this.blockAcces...
@Test public void hasNineMethods() { Assert.assertEquals(9, contract.getMethods().size()); }
NativeMethod { public ExecutionEnvironment getExecutionEnvironment() { return executionEnvironment; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[...
@Test public void executionEnvironmentGetter() { Assert.assertEquals(executionEnvironment, method.getExecutionEnvironment()); }
NativeMethod { public long getGas(Object[] parsedArguments, byte[] originalData) { return originalData == null ? 0 : originalData.length * 2; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execut...
@Test public void getGasWithNullData() { Assert.assertEquals(0L, method.getGas(null, null)); } @Test public void getGasWithNonNullData() { Assert.assertEquals(6L, method.getGas(null, Hex.decode("aabbcc"))); Assert.assertEquals(10L, method.getGas(null, Hex.decode("aabbccddee"))); } @Test public void withArgumentsGetsGas...
NativeMethod { public String getName() { return getFunction().name; } NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] origin...
@Test public void getName() { function.name = "a-method-name"; Assert.assertEquals("a-method-name", method.getName()); }
NativeMethod { public abstract Object execute(Object[] arguments); NativeMethod(ExecutionEnvironment executionEnvironment); ExecutionEnvironment getExecutionEnvironment(); abstract CallTransaction.Function getFunction(); abstract Object execute(Object[] arguments); long getGas(Object[] parsedArguments, byte[] originalD...
@Test public void withArgumentsExecutesMethod() { Assert.assertEquals("execution-result", withArguments.execute()); }