Search in sources :

Example 36 with MiningBlock

use of org.aion.zero.impl.types.MiningBlock in project aion by aionnetwork.

the class SolidityTypeTest method testBytes2.

@Test
public void testBytes2() throws Exception {
    byte[] x = Hex.decode("11223344556677881122334455667788112233445566778811223344556677881122334455667788");
    SolidityType type = new BytesType();
    byte[] params = ByteUtil.merge(Hex.decode("00000000000000000000000000000010"), type.encode(x));
    System.out.println(Hex.toHexString(params));
    AionTransaction tx = createTransaction(ByteUtil.merge(Hex.decode("61cb5a01"), params));
    MiningBlock block = createDummyBlock();
    RepositoryCache repo = createRepository(tx);
    AionTxReceipt receipt = executeTransaction(tx, block, repo).getReceipt();
    System.out.println(receipt);
    assertArrayEquals(params, receipt.getTransactionOutput());
    assertArrayEquals(x, (byte[]) type.decode(receipt.getTransactionOutput(), 16));
}
Also used : RepositoryCache(org.aion.base.db.RepositoryCache) AionTransaction(org.aion.base.AionTransaction) SolidityType(org.aion.solidity.SolidityType) AionTxReceipt(org.aion.base.AionTxReceipt) MiningBlock(org.aion.zero.impl.types.MiningBlock) BytesType(org.aion.solidity.SolidityType.BytesType) Test(org.junit.Test)

Example 37 with MiningBlock

use of org.aion.zero.impl.types.MiningBlock in project aion by aionnetwork.

the class AvmInternalTxTest method makeCall.

private void makeCall(BigInteger nonce, AionAddress contract, byte[] call) {
    AionTransaction transaction = AionTransaction.create(deployerKey, nonce.toByteArray(), contract, new byte[0], call, 2_000_000, minEnergyPrice, TransactionTypes.DEFAULT, null);
    MiningBlock block = this.blockchain.createNewMiningBlock(this.blockchain.getBestBlock(), Collections.singletonList(transaction), false);
    Pair<ImportResult, AionBlockSummary> connectResult = this.blockchain.tryToConnectAndFetchSummary(block);
    AionTxReceipt receipt = connectResult.getRight().getReceipts().get(0);
    // Check the block was imported and the transaction was successful.
    assertThat(connectResult.getLeft()).isEqualTo(ImportResult.IMPORTED_BEST);
    assertThat(receipt.isSuccessful()).isTrue();
    System.out.println(block);
}
Also used : ImportResult(org.aion.zero.impl.core.ImportResult) AionBlockSummary(org.aion.zero.impl.types.AionBlockSummary) AionTransaction(org.aion.base.AionTransaction) AionTxReceipt(org.aion.base.AionTxReceipt) MiningBlock(org.aion.zero.impl.types.MiningBlock)

Example 38 with MiningBlock

use of org.aion.zero.impl.types.MiningBlock in project aion by aionnetwork.

the class AvmBulkTransactionTest method sendTransactionsInBulkInSingleBlock.

private AionBlockSummary sendTransactionsInBulkInSingleBlock(List<AionTransaction> transactions) {
    Block parentBlock = this.blockchain.getBestBlock();
    MiningBlock block = this.blockchain.createBlock(parentBlock, transactions, false, parentBlock.getTimestamp());
    Pair<ImportResult, AionBlockSummary> connectResult = this.blockchain.tryToConnectAndFetchSummary(block);
    assertEquals(ImportResult.IMPORTED_BEST, connectResult.getLeft());
    return connectResult.getRight();
}
Also used : ImportResult(org.aion.zero.impl.core.ImportResult) AionBlockSummary(org.aion.zero.impl.types.AionBlockSummary) MiningBlock(org.aion.zero.impl.types.MiningBlock) Block(org.aion.zero.impl.types.Block) MiningBlock(org.aion.zero.impl.types.MiningBlock)

Example 39 with MiningBlock

use of org.aion.zero.impl.types.MiningBlock in project aion by aionnetwork.

the class AionBlockchainImpl method createNewStakingBlock.

private StakingBlock createNewStakingBlock(Block parent, List<AionTransaction> txs, byte[] newSeed, byte[] signingPublicKey, byte[] coinbase) {
    BlockHeader parentHdr = parent.getHeader();
    byte[] sealedSeed = newSeed;
    if (!forkUtility.isUnityForkActive(parentHdr.getNumber() + 1)) {
        LOG.debug("Unity fork has not been enabled! Can't create the staking blocks");
        return null;
    }
    byte[] parentSeed;
    BigInteger newDiff;
    if (parentHdr.getSealType() == Seal.PROOF_OF_STAKE) {
        LOG.warn("Tried to create 2 PoS blocks in a row");
        return null;
    } else if (parentHdr.getSealType() == Seal.PROOF_OF_WORK) {
        if (forkUtility.isUnityForkBlock(parentHdr.getNumber())) {
            // this is the first PoS block, use all zeroes as seed, and totalStake / 10 as difficulty
            parentSeed = GENESIS_SEED;
            newDiff = calculateFirstPoSDifficultyAtBlock(parent);
        } else if (forkUtility.isNonceForkBlock(parentHdr.getNumber())) {
            BlockHeader parentStakingBlock = getParent(parentHdr).getHeader();
            parentSeed = ((StakingBlockHeader) parentStakingBlock).getSeedOrProof();
            newDiff = calculateFirstPoSDifficultyAtBlock(parent);
            forkUtility.setNonceForkResetDiff(newDiff);
        } else {
            Block[] blockFamily = repository.getBlockStore().getTwoGenerationBlocksByHashWithInfo(parentHdr.getParentHash());
            Objects.requireNonNull(blockFamily[0]);
            BlockHeader parentStakingBlock = blockFamily[0].getHeader();
            BlockHeader parentStakingBlocksParent = blockFamily[1].getHeader();
            parentSeed = ((StakingBlockHeader) parentStakingBlock).getSeedOrProof();
            newDiff = chainConfiguration.getUnityDifficultyCalculator().calculateDifficulty(parentStakingBlock, parentStakingBlocksParent);
        }
    } else {
        throw new IllegalStateException("Invalid block type");
    }
    long newTimestamp;
    AionAddress coinbaseAddress = new AionAddress(coinbase);
    if (signingPublicKey != null) {
        // Create block template for the external stakers.
        byte[] proofHash = null;
        if (forkUtility.isSignatureSwapForkBlock(parent.getNumber() - 1)) {
            if (!VRF_Ed25519.verify(parentSeed, newSeed, signingPublicKey)) {
                LOG.debug("Seed verification failed! previousProof:{} newProof:{} pKey:{}", ByteUtil.toHexString(parentSeed), ByteUtil.toHexString(newSeed), ByteUtil.toHexString(signingPublicKey));
                return null;
            }
            proofHash = VRF_Ed25519.generateProofHash(newSeed);
        } else if (forkUtility.isSignatureSwapForkActive(parent.getNumber() + 1)) {
            byte[] parentSeedHash = VRF_Ed25519.generateProofHash(parentSeed);
            if (!VRF_Ed25519.verify(parentSeedHash, newSeed, signingPublicKey)) {
                LOG.debug("Seed verification failed! previousProof:{} newProof:{} pKey:{}", ByteUtil.toHexString(parentSeed), ByteUtil.toHexString(newSeed), ByteUtil.toHexString(signingPublicKey));
                return null;
            }
            proofHash = VRF_Ed25519.generateProofHash(newSeed);
        } else {
            if (!ECKeyEd25519.verify(parentSeed, newSeed, signingPublicKey)) {
                LOG.debug("Seed verification failed! previousSeed:{} newSeed:{} pKey:{}", ByteUtil.toHexString(parentSeed), ByteUtil.toHexString(newSeed), ByteUtil.toHexString(signingPublicKey));
                return null;
            }
            if (forkUtility.isNonceForkActive(parentHdr.getNumber() + 1)) {
                // new seed generation
                BlockHeader parentStakingBlock = getParent(parentHdr).getHeader();
                // retrieve components
                parentSeed = ((StakingBlockHeader) parentStakingBlock).getSeedOrProof();
                byte[] signerAddress = new AionAddress(AddressSpecs.computeA0Address(signingPublicKey)).toByteArray();
                ;
                byte[] powMineHash = ((MiningBlock) parent).getHeader().getMineHash();
                byte[] powNonce = ((MiningBlock) parent).getNonce();
                int lastIndex = parentSeed.length + signerAddress.length + powMineHash.length + powNonce.length;
                byte[] concatenated = new byte[lastIndex + 1];
                System.arraycopy(parentSeed, 0, concatenated, 0, parentSeed.length);
                System.arraycopy(signerAddress, 0, concatenated, parentSeed.length, signerAddress.length);
                System.arraycopy(powMineHash, 0, concatenated, parentSeed.length + signerAddress.length, powMineHash.length);
                System.arraycopy(powNonce, 0, concatenated, parentSeed.length + signerAddress.length + powMineHash.length, powNonce.length);
                concatenated[lastIndex] = 0;
                byte[] hash1 = h256(concatenated);
                concatenated[lastIndex] = 1;
                byte[] hash2 = h256(concatenated);
                sealedSeed = new byte[hash1.length + hash2.length];
                System.arraycopy(hash1, 0, sealedSeed, 0, hash1.length);
                System.arraycopy(hash2, 0, sealedSeed, hash1.length, hash2.length);
            }
        }
        AionAddress signingAddress = new AionAddress(AddressSpecs.computeA0Address(signingPublicKey));
        BigInteger stakes = null;
        try {
            stakes = getStakingContractHelper().getEffectiveStake(signingAddress, coinbaseAddress, parent);
        } catch (Exception e) {
            LOG.error("Shutdown due to a fatal error encountered while getting the effective stake.", e);
            System.exit(SystemExitCodes.FATAL_VM_ERROR);
        }
        if (stakes.signum() < 1) {
            LOG.debug("The caller {} with coinbase {} has no stake ", signingAddress.toString(), coinbase.toString());
            return null;
        }
        long newDelta = StakingDeltaCalculator.calculateDelta(proofHash == null ? sealedSeed : proofHash, newDiff, stakes);
        newTimestamp = Long.max(parent.getHeader().getTimestamp() + newDelta, parent.getHeader().getTimestamp() + 1);
    } else {
        newTimestamp = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        if (parentHdr.getTimestamp() >= newTimestamp) {
            newTimestamp = parentHdr.getTimestamp() + 1;
        }
    }
    StakingBlock block;
    try {
        StakingBlockHeader.Builder headerBuilder = StakingBlockHeader.Builder.newInstance().withParentHash(parent.getHash()).withCoinbase(coinbaseAddress).withNumber(parentHdr.getNumber() + 1).withTimestamp(newTimestamp).withExtraData(minerExtraData).withTxTrieRoot(calcTxTrieRoot(txs)).withEnergyLimit(energyLimitStrategy.getEnergyLimit(parentHdr)).withDifficulty(ByteUtil.bigIntegerToBytes(newDiff, DIFFICULTY_BYTES)).withDefaultStateRoot().withDefaultReceiptTrieRoot().withDefaultLogsBloom().withDefaultSignature().withDefaultSigningPublicKey();
        if (signingPublicKey != null) {
            headerBuilder.withSigningPublicKey(signingPublicKey);
        }
        if (forkUtility.isSignatureSwapForkActive(parentHdr.getNumber() + 1)) {
            headerBuilder.withProof(sealedSeed);
        } else {
            headerBuilder.withSeed(sealedSeed);
        }
        block = new StakingBlock(headerBuilder.build(), txs);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    BigInteger transactionFee = blockPreSeal(parentHdr, block);
    if (transactionFee == null) {
        return null;
    }
    if (signingPublicKey != null) {
        stakingBlockTemplate.putIfAbsent(ByteArrayWrapper.wrap(block.getHeader().getMineHash()), block);
    }
    LOG.debug("GetBlockTemp: {}", block.toString());
    return block;
}
Also used : AionAddress(org.aion.types.AionAddress) StakingBlockHeader(org.aion.zero.impl.types.StakingBlockHeader) MiningBlock(org.aion.zero.impl.types.MiningBlock) VmFatalException(org.aion.zero.impl.vm.common.VmFatalException) BigInteger(java.math.BigInteger) Block(org.aion.zero.impl.types.Block) BlockDetailsValidator.isValidBlock(org.aion.zero.impl.valid.BlockDetailsValidator.isValidBlock) GenesisStakingBlock(org.aion.zero.impl.types.GenesisStakingBlock) RetValidPreBlock(org.aion.zero.impl.types.RetValidPreBlock) MiningBlock(org.aion.zero.impl.types.MiningBlock) EventBlock(org.aion.evtmgr.impl.evt.EventBlock) StakingBlock(org.aion.zero.impl.types.StakingBlock) BlockHeader(org.aion.zero.impl.types.BlockHeader) MiningBlockHeader(org.aion.zero.impl.types.MiningBlockHeader) StakingBlockHeader(org.aion.zero.impl.types.StakingBlockHeader) GenesisStakingBlock(org.aion.zero.impl.types.GenesisStakingBlock) StakingBlock(org.aion.zero.impl.types.StakingBlock)

Example 40 with MiningBlock

use of org.aion.zero.impl.types.MiningBlock in project aion by aionnetwork.

the class StandaloneBlockchain method createBlockAndBlockTemplate.

/**
 * create a testing mining block and the block template
 */
public MiningBlock createBlockAndBlockTemplate(Block parent, List<AionTransaction> txs, boolean waitUntilBlockTime, long currTimeSeconds) {
    boolean unityForkEnabled = forkUtility.isUnityForkActive(parent.getNumber() + 1);
    boolean signatureSwapForkEnabled = forkUtility.isSignatureSwapForkActive(parent.getNumber() + 1);
    for (AionTransaction tx : txs) {
        if (TXValidator.validateTx(tx, unityForkEnabled, signatureSwapForkEnabled).isFail()) {
            throw new InvalidParameterException("invalid transaction input! " + tx.toString());
        }
    }
    BlockContext context = createNewMiningBlockInternal(parent, txs, waitUntilBlockTime, currTimeSeconds);
    if (context != null) {
        MiningBlock block = context.block;
        boolean newblock = miningBlockTemplate.put(ByteArrayWrapper.wrap(block.getHash()), block) == null;
        return newblock ? block : null;
    }
    return null;
}
Also used : InvalidParameterException(java.security.InvalidParameterException) BlockContext(org.aion.zero.impl.types.BlockContext) AionTransaction(org.aion.base.AionTransaction) MiningBlock(org.aion.zero.impl.types.MiningBlock)

Aggregations

MiningBlock (org.aion.zero.impl.types.MiningBlock)185 Test (org.junit.Test)136 AionTransaction (org.aion.base.AionTransaction)128 ImportResult (org.aion.zero.impl.core.ImportResult)81 AionAddress (org.aion.types.AionAddress)79 BigInteger (java.math.BigInteger)64 Block (org.aion.zero.impl.types.Block)63 AionBlockSummary (org.aion.zero.impl.types.AionBlockSummary)59 RepositoryCache (org.aion.base.db.RepositoryCache)41 AionTxReceipt (org.aion.base.AionTxReceipt)37 ArrayList (java.util.ArrayList)36 ECKey (org.aion.crypto.ECKey)27 AionRepositoryImpl (org.aion.zero.impl.db.AionRepositoryImpl)27 AionTxExecSummary (org.aion.base.AionTxExecSummary)25 AionRepositoryCache (org.aion.zero.impl.db.AionRepositoryCache)24 MiningBlockHeader (org.aion.zero.impl.types.MiningBlockHeader)22 BlockContext (org.aion.zero.impl.types.BlockContext)18 DataWord (org.aion.util.types.DataWord)13 MockDB (org.aion.db.impl.mockdb.MockDB)12 StakingBlock (org.aion.zero.impl.types.StakingBlock)11