use of org.aion.base.AionTxReceipt in project aion by aionnetwork.
the class AionBlockchainImpl method applyBlock.
private AionBlockSummary applyBlock(Block block) {
long saveTime = System.nanoTime();
List<AionTxReceipt> receipts = new ArrayList<>();
List<AionTxExecSummary> summaries = new ArrayList<>();
if (!block.getTransactionsList().isEmpty()) {
// might apply the block before the 040 fork point.
boolean fork040Enable = forkUtility.is040ForkActive(block.getNumber());
if (fork040Enable) {
TransactionTypeRule.allowAVMContractTransaction();
}
if (forkUtility.isSignatureSwapForkActive(block.getNumber())) {
HashUtil.setAfterSignatureSwap();
} else {
HashUtil.setBeforeSignatureSwap();
}
try {
// Booleans moved out here so their meaning is explicit.
boolean isLocalCall = false;
boolean incrementSenderNonce = true;
boolean checkBlockEnergyLimit = false;
List<AionTxExecSummary> executionSummaries = BulkExecutor.executeAllTransactionsInBlock(block.getDifficulty(), block.getNumber(), block.getTimestamp(), block.getNrgLimit(), block.getCoinbase(), block.getTransactionsList(), track, isLocalCall, incrementSenderNonce, fork040Enable, checkBlockEnergyLimit, LOGGER_VM, getPostExecutionWorkForApplyBlock(repository), executionTypeForAVM, cachedBlockNumberForAVM, forkUtility.isUnityForkActive(block.getNumber()), forkUtility.isSignatureSwapForkActive(block.getNumber()));
// Check for rejected transaction already included in the chain.
if (isException(block.getNumber())) {
for (AionTxExecSummary summary : executionSummaries) {
if (summary.isRejected()) {
AionTxReceipt receipt = summary.getReceipt();
receipt.setNrgUsed(receipt.getTransaction().getEnergyLimit());
}
}
}
for (AionTxExecSummary summary : executionSummaries) {
receipts.add(summary.getReceipt());
summaries.add(summary);
}
} catch (VmFatalException e) {
LOG.error("Shutdown due to a VM fatal error.", e);
System.exit(SystemExitCodes.FATAL_VM_ERROR);
}
}
Map<AionAddress, BigInteger> rewards = addReward(block);
return new AionBlockSummary(block, rewards, receipts, summaries);
}
use of org.aion.base.AionTxReceipt in project aion by aionnetwork.
the class AionBlockchainImpl method generatePreBlock.
/**
* For generating the necessary transactions for a block
*
* @param block
* @return
*/
private RetValidPreBlock generatePreBlock(Block block) {
long saveTime = System.nanoTime();
List<AionTxReceipt> receipts = new ArrayList<>();
List<AionTxExecSummary> summaries = new ArrayList<>();
List<AionTransaction> transactions = new ArrayList<>();
if (!block.getTransactionsList().isEmpty()) {
boolean fork040Enable = forkUtility.is040ForkActive(block.getNumber());
if (fork040Enable) {
TransactionTypeRule.allowAVMContractTransaction();
}
try {
// Booleans moved out here so their meaning is explicit.
boolean isLocalCall = false;
boolean incrementSenderNonce = true;
boolean checkBlockEnergyLimit = true;
List<AionTxExecSummary> executionSummaries = BulkExecutor.executeAllTransactionsInBlock(block.getDifficulty(), block.getNumber(), block.getTimestamp(), block.getNrgLimit(), block.getCoinbase(), block.getTransactionsList(), track, isLocalCall, incrementSenderNonce, fork040Enable, checkBlockEnergyLimit, LOGGER_VM, getPostExecutionWorkForGeneratePreBlock(repository), BlockCachingContext.PENDING, bestBlock.getNumber(), forkUtility.isUnityForkActive(block.getNumber()), forkUtility.isSignatureSwapForkActive(block.getNumber()));
for (AionTxExecSummary summary : executionSummaries) {
if (!summary.isRejected()) {
transactions.add(summary.getTransaction());
receipts.add(summary.getReceipt());
summaries.add(summary);
}
}
} catch (VmFatalException e) {
LOG.error("Shutdown due to a VM fatal error.", e);
System.exit(SystemExitCodes.FATAL_VM_ERROR);
}
}
Map<AionAddress, BigInteger> rewards = addReward(block);
return new RetValidPreBlock(transactions, rewards, receipts, summaries);
}
use of org.aion.base.AionTxReceipt in project aion by aionnetwork.
the class PendingStateTest method testAddPendingTransaction_AVMContractCall_Success.
@Test
public void testAddPendingTransaction_AVMContractCall_Success() throws Exception {
TestResourceProvider resourceProvider = TestResourceProvider.initializeAndCreateNewProvider(AvmPathManager.getPathOfProjectRootDirectory());
IAvmResourceFactory resourceFactory = resourceProvider.factoryForVersion1;
// Successful transaction
byte[] jar = resourceFactory.newContractFactory().getDeploymentBytes(AvmContract.HELLO_WORLD);
AionTransaction createTransaction = AionTransaction.create(deployerKey, BigInteger.ZERO.toByteArray(), null, BigInteger.ZERO.toByteArray(), jar, 5_000_000, energyPrice, TransactionTypes.AVM_CREATE_CODE, null);
assertEquals(pendingState.addTransactionFromApiServer(createTransaction), TxResponse.SUCCESS);
MiningBlock block = blockchain.createNewMiningBlock(blockchain.getBestBlock(), pendingState.getPendingTransactions(), false);
Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block);
AionTxReceipt receipt = connectResult.getRight().getReceipts().get(0);
// Check the block was imported, the contract has the Avm prefix, and deployment succeeded.
assertThat(connectResult.getLeft()).isEqualTo(ImportResult.IMPORTED_BEST);
// verify that the output is indeed the contract address
AionAddress contractAddress = TxUtil.calculateContractAddress(createTransaction);
assertThat(contractAddress.toByteArray()).isEqualTo(receipt.getTransactionOutput());
AionAddress contract = new AionAddress(receipt.getTransactionOutput());
byte[] call = resourceFactory.newStreamingEncoder().encodeOneString("sayHello").getEncoding();
AionTransaction callTransaction = AionTransaction.create(deployerKey, BigInteger.ONE.toByteArray(), contract, BigInteger.ZERO.toByteArray(), call, 2_000_000, energyPrice, TransactionTypes.DEFAULT, null);
assertEquals(pendingState.addTransactionFromApiServer(callTransaction), TxResponse.SUCCESS);
}
use of org.aion.base.AionTxReceipt in project aion by aionnetwork.
the class BlockchainForkingTest method testForkWithRevertOnSmallContractStorage.
/**
* Test the fork case when the block being replaced had contract storage changes that differ
* from the previous block and are replaced by new changes in the updated block.
*
* <p>Ensures that the output of applying the block after the fork is the same as applying the
* block first.
*/
@Test
public void testForkWithRevertOnSmallContractStorage() {
// ****** setup ******
// build a blockchain with CONCURRENT_THREADS_PER_TYPE blocks
List<ECKey> accounts = generateAccounts(10);
StandaloneBlockchain.Builder builder = new StandaloneBlockchain.Builder();
StandaloneBlockchain sourceChain = builder.withValidatorConfiguration("simple").withDefaultAccounts(accounts).build().bc;
StandaloneBlockchain testChain = builder.withValidatorConfiguration("simple").withDefaultAccounts(accounts).build().bc;
assertThat(testChain).isNotEqualTo(sourceChain);
assertThat(testChain.genesis).isEqualTo(sourceChain.genesis);
long time = System.currentTimeMillis();
// add a block with contract deploy
ECKey sender = accounts.remove(0);
AionTransaction deployTx = deployContract(sender);
MiningBlock block = sourceChain.createNewMiningBlockInternal(sourceChain.genesis, Arrays.asList(deployTx), true, time / 10_000L).block;
Pair<ImportResult, AionBlockSummary> connectResult = sourceChain.tryToConnectAndFetchSummary(block);
AionTxReceipt receipt = connectResult.getRight().getReceipts().get(0);
assertThat(receipt.isSuccessful()).isTrue();
ImportResult result = connectResult.getLeft();
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
result = testChain.tryToConnect(block);
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
assertThat(testChain.getRepository().getRoot()).isEqualTo(sourceChain.getRepository().getRoot());
AionAddress contract = TxUtil.calculateContractAddress(receipt.getTransaction());
// add a block with transactions to both
List<AionTransaction> txs = generateTransactions(20, accounts, sourceChain.getRepository());
block = sourceChain.createNewMiningBlockInternal(sourceChain.getBestBlock(), txs, true, time / 10_000L).block;
result = sourceChain.tryToConnect(block);
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
result = testChain.tryToConnect(block);
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
assertThat(testChain.getRepository().getRoot()).isEqualTo(sourceChain.getRepository().getRoot());
// create a slow / fast block distinction
AionTransaction callTx = callSetValue2(sender, contract, 5, 6, BigInteger.ONE);
MiningBlock fastBlock = sourceChain.createNewMiningBlockInternal(sourceChain.getBestBlock(), Arrays.asList(callTx), true, time / 10_000L).block;
callTx = callSetValue2(sender, contract, 1, 9, BigInteger.ONE);
MiningBlock slowBlock = new MiningBlock(sourceChain.createNewMiningBlockInternal(sourceChain.getBestBlock(), Arrays.asList(callTx), true, time / 10_000L).block);
MiningBlockHeader newBlockHeader = MiningBlockHeader.Builder.newInstance().withHeader(slowBlock.getHeader()).withTimestamp(time / 10_000L + 100).build();
slowBlock.updateHeader(newBlockHeader);
time += 100;
// sourceChain imports only fast block
assertThat(sourceChain.tryToConnect(fastBlock)).isEqualTo(ImportResult.IMPORTED_BEST);
// testChain imports both blocks
assertThat(testChain.tryToConnect(fastBlock)).isEqualTo(ImportResult.IMPORTED_BEST);
assertThat(testChain.tryToConnect(slowBlock)).isEqualTo(ImportResult.IMPORTED_NOT_BEST);
// build two blocks with different contract storage calls
// the second block gets a higher total difficulty
callTx = callSetValue(sender, contract, 5, BigInteger.TWO);
MiningBlock lowBlock = testChain.createNewMiningBlockInternal(slowBlock, Arrays.asList(callTx), true, time / 10_000L + 101).block;
callTx = callSetValue(sender, contract, 9, BigInteger.TWO);
MiningBlock highBlock = sourceChain.createNewMiningBlockInternal(fastBlock, Arrays.asList(callTx), true, time / 10_000L).block;
// System.out.println("***highBlock TD: " + highBlock.getDifficultyBI());
// System.out.println("***lowBlock TD: " + lowBlock.getDifficultyBI());
assertThat(highBlock.getDifficultyBI()).isGreaterThan(lowBlock.getDifficultyBI());
// build first chain with highBlock applied directly
connectResult = sourceChain.tryToConnectAndFetchSummary(highBlock);
receipt = connectResult.getRight().getReceipts().get(0);
assertThat(receipt.isSuccessful()).isTrue();
result = connectResult.getLeft();
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
// collect the consensus information from the block & receipt
AionBlockSummary blockSummary = connectResult.getRight();
byte[] stateRoot = blockSummary.getBlock().getStateRoot();
byte[] blockReceiptsRoot = blockSummary.getBlock().getReceiptsRoot();
byte[] receiptTrieEncoded = receipt.getReceiptTrieEncoded();
// ****** test fork behavior ******
// first import lowBlock
assertThat(testChain.tryToConnect(lowBlock)).isEqualTo(ImportResult.IMPORTED_BEST);
// next import highBlock causing the fork
connectResult = testChain.tryToConnectAndFetchSummary(highBlock);
receipt = connectResult.getRight().getReceipts().get(0);
assertThat(receipt.isSuccessful()).isTrue();
System.out.println(receipt);
result = connectResult.getLeft();
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
// collect the consensus information from the block & receipt
blockSummary = connectResult.getRight();
assertThat(testChain.getBestBlock()).isEqualTo(sourceChain.getBestBlock());
assertThat(blockSummary.getBlock().getStateRoot()).isEqualTo(stateRoot);
assertThat(blockSummary.getBlock().getReceiptsRoot()).isEqualTo(blockReceiptsRoot);
assertThat(receipt.getReceiptTrieEncoded()).isEqualTo(receiptTrieEncoded);
}
use of org.aion.base.AionTxReceipt in project aion by aionnetwork.
the class BlockchainForkingTest method testVmTypeRetrieval_ForkWithConflictingContractVM.
/**
* Ensures that if a side-chain block is imported after a main-chain block creating the same
* contract address X but using different VMs, then each chain will operate on the correct VM.
*/
@Test
public void testVmTypeRetrieval_ForkWithConflictingContractVM() throws Exception {
TestResourceProvider resourceProvider = TestResourceProvider.initializeAndCreateNewProvider(AvmPathManager.getPathOfProjectRootDirectory());
IAvmResourceFactory resourceFactory = resourceProvider.factoryForVersion1;
// blocks to be built
MiningBlock block, fastBlock, slowBlock, lowBlock, highBlock;
// transactions used in blocks
AionTransaction deployOnAVM, deployOnFVM, callTxOnFVM;
// for processing block results
Pair<ImportResult, AionBlockSummary> connectResult;
ImportResult result;
AionTxReceipt receipt;
// build a blockchain
TransactionTypeRule.allowAVMContractTransaction();
List<ECKey> accounts = generateAccounts(10);
StandaloneBlockchain.Builder builder = new StandaloneBlockchain.Builder();
StandaloneBlockchain sourceChain = builder.withValidatorConfiguration("simple").withDefaultAccounts(accounts).build().bc;
StandaloneBlockchain testChain = builder.withValidatorConfiguration("simple").withDefaultAccounts(accounts).build().bc;
ECKey sender = accounts.remove(0);
assertThat(testChain).isNotEqualTo(sourceChain);
assertThat(testChain.genesis).isEqualTo(sourceChain.genesis);
long time = System.currentTimeMillis();
// add a block to both chains
block = sourceChain.createNewMiningBlockInternal(sourceChain.getBestBlock(), Collections.emptyList(), true, time / 10_000L).block;
assertThat(sourceChain.tryToConnect(block)).isEqualTo(ImportResult.IMPORTED_BEST);
assertThat(testChain.tryToConnect(block)).isEqualTo(ImportResult.IMPORTED_BEST);
// ****** setup side chain ******
// deploy contracts on different VMs for the two chains
deployOnAVM = deployStatefulnessAVMContract(resourceFactory, sender);
fastBlock = sourceChain.createNewMiningBlockInternal(sourceChain.getBestBlock(), Arrays.asList(deployOnAVM), true, time / 10_000L).block;
deployOnFVM = deployContract(sender);
slowBlock = new MiningBlock(sourceChain.createNewMiningBlockInternal(sourceChain.getBestBlock(), Arrays.asList(deployOnFVM), true, time / 10_000L).block);
MiningBlockHeader newBlockHeader = MiningBlockHeader.Builder.newInstance().withHeader(slowBlock.getHeader()).withTimestamp(time / 10_000L + 100).build();
slowBlock.updateHeader(newBlockHeader);
time += 100;
// sourceChain imports only fast block
connectResult = sourceChain.tryToConnectAndFetchSummary(fastBlock);
result = connectResult.getLeft();
receipt = connectResult.getRight().getReceipts().get(0);
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
assertThat(receipt.isSuccessful()).isTrue();
AionAddress contract = TxUtil.calculateContractAddress(receipt.getTransaction());
// testChain imports both blocks
connectResult = testChain.tryToConnectAndFetchSummary(fastBlock);
result = connectResult.getLeft();
receipt = connectResult.getRight().getReceipts().get(0);
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
assertThat(receipt.isSuccessful()).isTrue();
assertThat(TxUtil.calculateContractAddress(receipt.getTransaction())).isEqualTo(contract);
connectResult = testChain.tryToConnectAndFetchSummary(slowBlock);
result = connectResult.getLeft();
receipt = connectResult.getRight().getReceipts().get(0);
assertThat(result).isEqualTo(ImportResult.IMPORTED_NOT_BEST);
assertThat(receipt.isSuccessful()).isTrue();
assertThat(TxUtil.calculateContractAddress(receipt.getTransaction())).isEqualTo(contract);
// ****** check that the correct contract details are kept ******
// check that both chains have the correct vm type for the AVM contract
byte[] codeHashAVM = sourceChain.getRepository().getAccountState(contract).getCodeHash();
assertThat(testChain.getRepository().getVMUsed(contract, codeHashAVM)).isEqualTo(sourceChain.getRepository().getVMUsed(contract, codeHashAVM));
// check that only the second chain has the vm type for the FVM contract
byte[] codeHashFVM = ((AionRepositoryImpl) testChain.getRepository().getSnapshotTo(slowBlock.getStateRoot())).getAccountState(contract).getCodeHash();
assertThat(sourceChain.getRepository().getVMUsed(contract, codeHashFVM)).isEqualTo(InternalVmType.UNKNOWN);
assertThat(testChain.getRepository().getVMUsed(contract, codeHashFVM)).isEqualTo(InternalVmType.FVM);
// check the stored information details
ContractInformation infoSingleImport = sourceChain.getRepository().getIndexedContractInformation(contract);
System.out.println("without side chain:" + infoSingleImport);
assertThat(infoSingleImport.getVmUsed(codeHashAVM)).isEqualTo(InternalVmType.AVM);
assertThat(infoSingleImport.getInceptionBlocks(codeHashAVM)).isEqualTo(Set.of(fastBlock.getHashWrapper()));
assertThat(infoSingleImport.getVmUsed(codeHashFVM)).isEqualTo(InternalVmType.UNKNOWN);
assertThat(infoSingleImport.getInceptionBlocks(codeHashFVM)).isEmpty();
ContractInformation infoMultiImport = testChain.getRepository().getIndexedContractInformation(contract);
System.out.println("with side chain:" + infoMultiImport);
assertThat(infoMultiImport.getVmUsed(codeHashAVM)).isEqualTo(InternalVmType.AVM);
assertThat(infoMultiImport.getInceptionBlocks(codeHashAVM)).isEqualTo(Set.of(fastBlock.getHashWrapper()));
assertThat(infoMultiImport.getVmUsed(codeHashFVM)).isEqualTo(InternalVmType.FVM);
assertThat(infoMultiImport.getInceptionBlocks(codeHashFVM)).isEqualTo(Set.of(slowBlock.getHashWrapper()));
// build two blocks where the second block has a higher total difficulty
callTxOnFVM = callSetValue(sender, contract, 9, BigInteger.ONE);
lowBlock = testChain.createNewMiningBlockInternal(slowBlock, Arrays.asList(callTxOnFVM), true, time / 10_000L + 101).block;
int expectedCount = 3;
List<AionTransaction> callTxOnAVM = callStatefulnessAVM(resourceFactory, sender, expectedCount, BigInteger.ONE, contract);
highBlock = sourceChain.createNewMiningBlockInternal(fastBlock, callTxOnAVM, true, time / 10_000L).block;
assertThat(highBlock.getDifficultyBI()).isGreaterThan(lowBlock.getDifficultyBI());
// build first chain with highBlock applied directly
connectResult = sourceChain.tryToConnectAndFetchSummary(highBlock);
// get last tx
receipt = connectResult.getRight().getReceipts().get(expectedCount);
assertThat(receipt.isSuccessful()).isTrue();
result = connectResult.getLeft();
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
// collect the consensus information from the block & receipt
AionBlockSummary blockSummary = connectResult.getRight();
byte[] stateRoot = blockSummary.getBlock().getStateRoot();
byte[] blockReceiptsRoot = blockSummary.getBlock().getReceiptsRoot();
byte[] receiptTrieEncoded = receipt.getReceiptTrieEncoded();
int returnedCount = resourceFactory.newDecoder(blockSummary.getReceipts().get(expectedCount).getTransactionOutput()).decodeOneInteger();
assertThat(returnedCount).isEqualTo(expectedCount);
// ****** test fork behavior ******
// first import lowBlock
assertThat(testChain.tryToConnect(lowBlock)).isEqualTo(ImportResult.IMPORTED_BEST);
// next import highBlock causing the fork
connectResult = testChain.tryToConnectAndFetchSummary(highBlock);
receipt = connectResult.getRight().getReceipts().get(expectedCount);
assertThat(receipt.isSuccessful()).isTrue();
System.out.println(receipt);
result = connectResult.getLeft();
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
// collect the consensus information from the block & receipt
blockSummary = connectResult.getRight();
assertThat(testChain.getBestBlock()).isEqualTo(sourceChain.getBestBlock());
assertThat(blockSummary.getBlock().getStateRoot()).isEqualTo(stateRoot);
assertThat(blockSummary.getBlock().getReceiptsRoot()).isEqualTo(blockReceiptsRoot);
assertThat(receipt.getReceiptTrieEncoded()).isEqualTo(receiptTrieEncoded);
returnedCount = resourceFactory.newDecoder(blockSummary.getReceipts().get(expectedCount).getTransactionOutput()).decodeOneInteger();
assertThat(returnedCount).isEqualTo(expectedCount);
}
Aggregations