List of usage examples for org.bouncycastle.util BigIntegers fromUnsignedByteArray
public static BigInteger fromUnsignedByteArray(byte[] buf)
From source file:co.rsk.core.bc.BlockExecutorTest.java
License:Open Source License
@Test public void executeBlockWithTwoTransactions() { Repository repository = new RepositoryImpl(new TrieImpl(new TrieStoreImpl(new HashMapDB()), true), new HashMapDB(), new TrieStorePoolOnMemory(), config.detailsInMemoryStorageLimit()); Repository track = repository.startTracking(); Account account = createAccount("acctest1", track, Coin.valueOf(60000)); Account account2 = createAccount("acctest2", track, Coin.valueOf(10L)); track.commit();//from ww w . j av a 2 s . c o m Assert.assertFalse(Arrays.equals(EMPTY_TRIE_HASH, repository.getRoot())); final ProgramInvokeFactoryImpl programInvokeFactory = new ProgramInvokeFactoryImpl(); BlockExecutor executor = new BlockExecutor(repository, (tx1, txindex1, coinbase, track1, block1, totalGasUsed1) -> new TransactionExecutor(tx1, txindex1, block1.getCoinbase(), track1, null, null, programInvokeFactory, block1, null, totalGasUsed1, config.getVmConfig(), config.getBlockchainConfig(), config.playVM(), config.isRemascEnabled(), config.vmTrace(), new PrecompiledContracts(config), config.databaseDir(), config.vmTraceDir(), config.vmTraceCompressed())); Transaction tx1 = createTransaction(account, account2, BigInteger.TEN, repository.getNonce(account.getAddress())); Transaction tx2 = createTransaction(account, account2, BigInteger.TEN, repository.getNonce(account.getAddress()).add(BigInteger.ONE)); List<Transaction> txs = new ArrayList<>(); txs.add(tx1); txs.add(tx2); List<BlockHeader> uncles = new ArrayList<>(); BlockGenerator blockGenerator = new BlockGenerator(); Block block = blockGenerator.createChildBlock(blockGenerator.getGenesisBlock(), txs, uncles, 1, null); BlockResult result = executor.execute(block, repository.getRoot(), false); Assert.assertNotNull(result); Assert.assertNotNull(result.getTransactionReceipts()); Assert.assertFalse(result.getTransactionReceipts().isEmpty()); Assert.assertEquals(2, result.getTransactionReceipts().size()); TransactionReceipt receipt = result.getTransactionReceipts().get(0); Assert.assertEquals(tx1, receipt.getTransaction()); Assert.assertEquals(21000, new BigInteger(1, receipt.getGasUsed()).longValue()); Assert.assertEquals(21000, BigIntegers.fromUnsignedByteArray(receipt.getCumulativeGas()).longValue()); Assert.assertTrue(receipt.hasTxStatus() && receipt.isTxStatusOK() && receipt.isSuccessful()); receipt = result.getTransactionReceipts().get(1); Assert.assertEquals(tx2, receipt.getTransaction()); Assert.assertEquals(21000, new BigInteger(1, receipt.getGasUsed()).longValue()); Assert.assertEquals(42000, BigIntegers.fromUnsignedByteArray(receipt.getCumulativeGas()).longValue()); Assert.assertTrue(receipt.hasTxStatus() && receipt.isTxStatusOK() && receipt.isSuccessful()); Assert.assertEquals(42000, result.getGasUsed()); Assert.assertEquals(42000, result.getPaidFees().asBigInteger().intValueExact()); Assert.assertNotNull(result.getReceiptsRoot()); Assert.assertArrayEquals(BlockChainImpl.calcReceiptsTrie(result.getTransactionReceipts()), result.getReceiptsRoot()); Assert.assertFalse(Arrays.equals(repository.getRoot(), result.getStateRoot())); Assert.assertNotNull(result.getLogsBloom()); Assert.assertEquals(256, result.getLogsBloom().length); for (int k = 0; k < result.getLogsBloom().length; k++) Assert.assertEquals(0, result.getLogsBloom()[k]); AccountState accountState = repository.getAccountState(account.getAddress()); Assert.assertNotNull(accountState); Assert.assertEquals(BigInteger.valueOf(60000), accountState.getBalance().asBigInteger()); Repository finalRepository = repository.getSnapshotTo(result.getStateRoot()); accountState = finalRepository.getAccountState(account.getAddress()); Assert.assertNotNull(accountState); Assert.assertEquals(BigInteger.valueOf(60000 - 42000 - 20), accountState.getBalance().asBigInteger()); }
From source file:co.rsk.net.handler.TxPendingValidator.java
License:Open Source License
public TransactionValidationResult isValid(Transaction tx, Block executionBlock, @Nullable AccountState state) { BigInteger blockGasLimit = BigIntegers.fromUnsignedByteArray(executionBlock.getGasLimit()); Coin minimumGasPrice = executionBlock.getMinimumGasPrice(); long bestBlockNumber = executionBlock.getNumber(); long basicTxCost = tx.transactionCost(executionBlock, config.getBlockchainConfig()); if (state == null && basicTxCost != 0) { logger.trace("[tx={}, sender={}] account doesn't exist", tx.getHash(), tx.getSender()); return TransactionValidationResult.withError("the sender account doesn't exist"); }/*from w w w . j a v a2 s . com*/ for (TxValidatorStep step : validatorSteps) { TransactionValidationResult validationResult = step.validate(tx, state, blockGasLimit, minimumGasPrice, bestBlockNumber, basicTxCost == 0); if (!validationResult.transactionIsValid()) { logger.info("[tx={}] validation failed with error: {}", tx.getHash(), validationResult.getErrorMessage()); return validationResult; } } return TransactionValidationResult.ok(); }
From source file:co.rsk.peg.BridgeSerializationUtils.java
License:Open Source License
public static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data) { Map<Sha256Hash, Long> map = new HashMap<>(); if (data == null || data.length == 0) { return map; }/* w w w. ja v a2 s. co m*/ RLPList rlpList = (RLPList) RLP.decode2(data).get(0); // List size must be even - key, value pairs expected in sequence if (rlpList.size() % 2 != 0) { throw new RuntimeException( "deserializeMapOfHashesToLong: expected an even number of entries, but odd given"); } int numEntries = rlpList.size() / 2; for (int k = 0; k < numEntries; k++) { Sha256Hash hash = Sha256Hash.wrap(rlpList.get(k * 2).getRLPData()); Long number = BigIntegers.fromUnsignedByteArray(rlpList.get(k * 2 + 1).getRLPData()).longValue(); map.put(hash, number); } return map; }
From source file:co.rsk.peg.BridgeSerializationUtils.java
License:Open Source License
public static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters) { RLPList rlpList = (RLPList) RLP.decode2(data).get(0); if (rlpList.size() != FEDERATION_RLP_LIST_SIZE) { throw new RuntimeException( String.format("Invalid serialized Federation. Expected %d elements but got %d", FEDERATION_RLP_LIST_SIZE, rlpList.size())); }/*from w w w. j a v a 2 s . co m*/ byte[] creationTimeBytes = rlpList.get(FEDERATION_CREATION_TIME_INDEX).getRLPData(); Instant creationTime = Instant .ofEpochMilli(BigIntegers.fromUnsignedByteArray(creationTimeBytes).longValue()); List<BtcECKey> pubKeys = ((RLPList) rlpList.get(FEDERATION_PUB_KEYS_INDEX)).stream() .map(pubKeyBytes -> BtcECKey.fromPublicOnly(pubKeyBytes.getRLPData())).collect(Collectors.toList()); byte[] creationBlockNumberBytes = rlpList.get(FEDERATION_CREATION_BLOCK_NUMBER_INDEX).getRLPData(); long creationBlockNumber = BigIntegers.fromUnsignedByteArray(creationBlockNumberBytes).longValue(); return new Federation(pubKeys, creationTime, creationBlockNumber, networkParameters); }
From source file:co.rsk.peg.BridgeSerializationUtils.java
License:Open Source License
private static BigInteger safeToBigInteger(byte[] data) { return data == null ? BigInteger.ZERO : BigIntegers.fromUnsignedByteArray(data); }
From source file:co.rsk.peg.BridgeSerializationUtils.java
License:Open Source License
public static ReleaseRequestQueue deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters) { List<ReleaseRequestQueue.Entry> entries = new ArrayList<>(); if (data == null || data.length == 0) { return new ReleaseRequestQueue(entries); }// www . j a v a 2s .c om RLPList rlpList = (RLPList) RLP.decode2(data).get(0); // Must have an even number of items if (rlpList.size() % 2 != 0) { throw new RuntimeException(String.format( "Invalid serialized ReleaseRequestQueue. Expected an even number of elements, but got %d", rlpList.size())); } int n = rlpList.size() / 2; for (int k = 0; k < n; k++) { byte[] addressBytes = rlpList.get(k * 2).getRLPData(); Address address = new Address(networkParameters, addressBytes); Long amount = BigIntegers.fromUnsignedByteArray(rlpList.get(k * 2 + 1).getRLPData()).longValue(); entries.add(new ReleaseRequestQueue.Entry(address, Coin.valueOf(amount))); } return new ReleaseRequestQueue(entries); }
From source file:co.rsk.peg.BridgeSerializationUtils.java
License:Open Source License
public static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters) { Set<ReleaseTransactionSet.Entry> entries = new HashSet<>(); if (data == null || data.length == 0) { return new ReleaseTransactionSet(entries); }/*from www .ja va 2s . com*/ RLPList rlpList = (RLPList) RLP.decode2(data).get(0); // Must have an even number of items if (rlpList.size() % 2 != 0) { throw new RuntimeException(String.format( "Invalid serialized ReleaseTransactionSet. Expected an even number of elements, but got %d", rlpList.size())); } int n = rlpList.size() / 2; for (int k = 0; k < n; k++) { byte[] txPayload = rlpList.get(k * 2).getRLPData(); BtcTransaction tx = new BtcTransaction(networkParameters, txPayload); Long height = BigIntegers.fromUnsignedByteArray(rlpList.get(k * 2 + 1).getRLPData()).longValue(); entries.add(new ReleaseTransactionSet.Entry(tx, height)); } return new ReleaseTransactionSet(entries); }
From source file:co.rsk.remasc.RemascStorageProvider.java
License:Open Source License
public static SortedMap<Long, List<Sibling>> getSiblingsFromBytes(byte[] bytes) { SortedMap<Long, List<Sibling>> siblings = new TreeMap<>(); if (bytes == null || bytes.length == 0) { return siblings; }// www. j a v a2s . co m RLPList rlpList = (RLPList) RLP.decode2(bytes).get(0); int nentries = rlpList.size() / 2; for (int k = 0; k < nentries; k++) { byte[] bytesKey = rlpList.get(k * 2).getRLPData(); byte[] bytesValue = rlpList.get(k * 2 + 1).getRLPData(); long longKey = bytesKey == null ? 0 : BigIntegers.fromUnsignedByteArray(bytesKey).longValue(); Long key = Long.valueOf(longKey); RLPList rlpSiblingList = (RLPList) RLP.decode2(bytesValue).get(0); int nsiblings = rlpSiblingList.size(); List<Sibling> list = new ArrayList<>(); for (int j = 0; j < nsiblings; j++) { byte[] bytesSibling = rlpSiblingList.get(j).getRLPData(); Sibling sibling = Sibling.create(bytesSibling); list.add(sibling); } siblings.put(key, list); } return siblings; }
From source file:co.rsk.remasc.Sibling.java
License:Open Source License
public static Sibling create(byte[] data) { ArrayList<RLPElement> params = RLP.decode2(data); RLPList sibling = (RLPList) params.get(0); byte[] hash = sibling.get(0).getRLPData(); RskAddress coinbase = RLP.parseRskAddress(sibling.get(1).getRLPData()); RskAddress includedBlockCoinbase = RLP.parseRskAddress(sibling.get(2).getRLPData()); Coin paidFees = RLP.parseCoin(sibling.get(3).getRLPData()); byte[] bytesIncludedHeight = sibling.get(4).getRLPData(); RLPElement uncleCountElement = sibling.get(5); byte[] bytesUncleCount = uncleCountElement != null ? uncleCountElement.getRLPData() : null; long includedHeight = bytesIncludedHeight == null ? 0 : BigIntegers.fromUnsignedByteArray(bytesIncludedHeight).longValue(); int uncleCount = bytesUncleCount == null ? 0 : BigIntegers.fromUnsignedByteArray(bytesUncleCount).intValue(); return new Sibling(hash, coinbase, includedBlockCoinbase, paidFees, includedHeight, uncleCount); }
From source file:co.rsk.test.DslFilesTest.java
License:Open Source License
@Test public void runCreate01Resource() throws FileNotFoundException, DslProcessorException { DslParser parser = DslParser.fromResource("dsl/create01.txt"); World world = new World(); WorldDslProcessor processor = new WorldDslProcessor(world); processor.processCommands(parser);//from w w w .ja va2 s .com Transaction transaction = world.getTransactionByName("tx01"); Assert.assertNotNull(transaction); TransactionInfo txinfo = world.getBlockChain().getTransactionInfo(transaction.getHash().getBytes()); Assert.assertNotNull(txinfo); BigInteger gasUsed = BigIntegers.fromUnsignedByteArray(txinfo.getReceipt().getGasUsed()); Assert.assertNotEquals(BigInteger.ZERO, gasUsed); // According to TestRPC and geth, the gas used is 0x010c2d Assert.assertEquals(BigIntegers.fromUnsignedByteArray(Hex.decode("010c2d")), gasUsed); }