use of org.aion.zero.impl.core.ImportResult 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.zero.impl.core.ImportResult in project aion by aionnetwork.
the class BlockchainForkingTest method testSameBlockDifferentNonceAndSolutionSimple.
/*-
* Tests the case where multiple threads submit a single block (content) but
* with different mining nonces and solutions. In this case our rules dictate
* that all subsequent blocks are considered invalid.
*
* (common ancestor)
* / \
* / \
* / \
* (a)o (b)x
*
* Given:
* a.td == b.td
*/
@Test
public void testSameBlockDifferentNonceAndSolutionSimple() {
StandaloneBlockchain.Builder builder = new StandaloneBlockchain.Builder();
StandaloneBlockchain.Bundle b = builder.withValidatorConfiguration("simple").build();
StandaloneBlockchain bc = b.bc;
MiningBlock block = bc.createNewMiningBlock(bc.getBestBlock(), Collections.emptyList(), true);
MiningBlock sameBlock = (MiningBlock) BlockUtil.newBlockFromRlp(block.getEncoded());
ImportResult firstRes = bc.tryToConnect(block);
// check that the returned block is the first block
assertThat(bc.getBestBlock() == block).isTrue();
assertThat(firstRes).isEqualTo(ImportResult.IMPORTED_BEST);
// check that the correct caching context was used
Pair<Long, BlockCachingContext> cacheContext = bc.getAvmCachingContext();
assertThat(cacheContext.getLeft()).isEqualTo(block.getNumber() - 1);
assertThat(cacheContext.getRight()).isEqualTo(BlockCachingContext.MAINCHAIN);
ImportResult secondRes = bc.tryToConnect(sameBlock);
// the second block should get rejected, so check that the reference still refers
// to the first block (we dont change the published reference)
assertThat(bc.getBestBlock() == block).isTrue();
assertThat(secondRes).isEqualTo(ImportResult.EXIST);
// the caching context does not change for already known blocks
cacheContext = bc.getAvmCachingContext();
assertThat(cacheContext.getLeft()).isEqualTo(block.getNumber() - 1);
assertThat(cacheContext.getRight()).isEqualTo(BlockCachingContext.MAINCHAIN);
}
use of org.aion.zero.impl.core.ImportResult 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);
}
use of org.aion.zero.impl.core.ImportResult in project aion by aionnetwork.
the class BlockchainConcurrentImportTest method generateBlocks.
private static void generateBlocks() {
System.out.format("%nGenerating %d input blocks...%n", CONCURRENT_THREADS_PER_TYPE);
Random rand = new Random();
MiningBlock parent, block, mainChain;
mainChain = sourceChain.getGenesis();
knownBlocks.add(mainChain);
List<AionTransaction> txs;
AionRepositoryImpl sourceRepo = sourceChain.getRepository();
long time = System.currentTimeMillis();
for (int i = 0; i < CONCURRENT_THREADS_PER_TYPE; i++) {
// ensuring that we add to the main chain at least every MAIN_CHAIN_FREQUENCY block
if (i % MAIN_CHAIN_FREQUENCY == 0) {
// the parent will be the main chain
parent = mainChain;
} else {
// the parent is a random already imported block
parent = knownBlocks.get(rand.nextInt(knownBlocks.size()));
}
// generate transactions for correct root
byte[] originalRoot = sourceRepo.getRoot();
sourceRepo.syncToRoot(parent.getStateRoot());
txs = generateTransactions(MAX_TX_PER_BLOCK, accounts, sourceRepo);
sourceRepo.syncToRoot(originalRoot);
block = sourceChain.createNewMiningBlockInternal(parent, txs, true, time / 10000L).block;
MiningBlockHeader newBlockHeader = MiningBlockHeader.Builder.newInstance().withHeader(block.getHeader()).withExtraData(String.valueOf(i).getBytes()).build();
block.updateHeader(newBlockHeader);
ImportResult result = sourceChain.tryToConnect(block);
knownBlocks.add(block);
if (result == ImportResult.IMPORTED_BEST) {
mainChain = block;
}
if (DISPLAY_MESSAGES) {
System.out.format("Created block with hash: %s, number: %6d, extra data: %6s, txs: %3d, import status: %20s %n", block.getShortHash(), block.getNumber(), new String(block.getExtraData()), block.getTransactionsList().size(), result.toString());
}
}
// all blocks except the genesis will be imported by the other chain
knownBlocks.remove(sourceChain.getGenesis());
}
use of org.aion.zero.impl.core.ImportResult in project aion by aionnetwork.
the class BlockchainConcurrentImportTest method addThread_tryToConnect.
/**
* Adds a new thread for importing an already known block.
*
* @param _threads list of threads to be executed; the current thread will be added to this list
* @param _chain the blockchain where the blocks will be imported
* @param _block the block to import
*/
private void addThread_tryToConnect(List<Runnable> _threads, StandaloneBlockchain _chain, MiningBlock _block) {
_threads.add(() -> {
testChain.assertEqualTotalDifficulty();
// importing the given block
ImportResult result = _chain.tryToConnect(_block);
testChain.assertEqualTotalDifficulty();
if (DISPLAY_MESSAGES) {
System.out.format("Import block with hash: %s, number: %6d, extra data: %6s, txs: %3d, status: %20s in thread: %20s %n", _block.getShortHash(), _block.getNumber(), new String(_block.getExtraData()), _block.getTransactionsList().size(), result.toString(), Thread.currentThread().getName());
}
// checking total difficulty
if (result == ImportResult.IMPORTED_BEST || result == ImportResult.IMPORTED_NOT_BEST) {
AionBlockStore store = _chain.getRepository().getBlockStore();
BigInteger tdFromStore = _chain.getTotalDifficultyForHash(_block.getHash());
BigInteger tdCalculated = _chain.getTotalDifficultyForHash(_block.getParentHash()).add(_block.getDifficultyBI());
assertThat(tdFromStore).isEqualTo(tdCalculated);
assertThat(tdCalculated).isEqualTo(_chain.getTotalDifficultyForHash(_block.getHash()));
if (result == ImportResult.IMPORTED_BEST) {
// can't check for equality since other blocks may have already been
// imported
Block bestBlock = store.getBestBlock();
assertNotNull(bestBlock);
assertThat(bestBlock.getTotalDifficulty()).isAtLeast(tdFromStore);
}
}
});
}
Aggregations