Search in sources :

Example 56 with AionTxReceipt

use of org.aion.base.AionTxReceipt in project aion by aionnetwork.

the class StakingContractHelper method getEffectiveStake.

/**
 * this method called by the kernel for querying the correct stakes in the staking contract by giving desired coinbase address and the block signing address.
 * @param signingAddress the block signing address
 * @param coinbase the staker's coinbase for receiving the block rewards
 * @return the stake amount of the staker
 */
public BigInteger getEffectiveStake(AionAddress signingAddress, AionAddress coinbase, Block block) throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException {
    if (signingAddress == null || coinbase == null) {
        throw new NullPointerException();
    }
    if (!AvmProvider.tryAcquireLock(10, TimeUnit.MINUTES)) {
        throw new IllegalStateException("Failed to acquire the avm lock!");
    }
    if (!AvmProvider.isVersionEnabled(LATEST_AVM_VERSION)) {
        AvmProvider.enableAvmVersion(LATEST_AVM_VERSION, AvmConfigurations.getProjectRootDirectory());
    }
    IAvmResourceFactory resourceFactory = AvmProvider.getResourceFactory(LATEST_AVM_VERSION);
    if (this.effectiveStake == null) {
        this.effectiveStake = resourceFactory.newStreamingEncoder().encodeOneString("getEffectiveStake").getEncoding();
    }
    byte[] abi = ByteUtil.merge(this.effectiveStake, resourceFactory.newStreamingEncoder().encodeOneAddress(signingAddress).getEncoding(), resourceFactory.newStreamingEncoder().encodeOneAddress(coinbase).getEncoding());
    AvmProvider.releaseLock();
    AionTransaction callTx = AionTransaction.create(keyForCallandEstimate, BigInteger.ZERO.toByteArray(), stakingContractAddr, BigInteger.ZERO.toByteArray(), abi, 2_000_000L, 10_000_000_000L, TransactionTypes.DEFAULT, null);
    AionTxReceipt receipt = null;
    try {
        receipt = callConstant(callTx, block);
    } catch (VmFatalException e) {
        LOG_VM.error("VM fatal exception! Shutting down the kernel!", e);
        System.exit(SystemExitCodes.FATAL_VM_ERROR);
    }
    if (receipt == null || Arrays.equals(receipt.getTransactionOutput(), new byte[0])) {
        LOG_CONS.debug("getEffectiveStake failed due to the " + (receipt == null ? "null receipt" : "empty transactionOutput"));
        return BigInteger.ZERO;
    }
    if (!AvmProvider.tryAcquireLock(10, TimeUnit.MINUTES)) {
        throw new IllegalStateException("Failed to acquire the avm lock!");
    }
    BigInteger output = resourceFactory.newDecoder(receipt.getTransactionOutput()).decodeOneBigInteger();
    AvmProvider.releaseLock();
    return output;
}
Also used : IAvmResourceFactory(org.aion.avm.stub.IAvmResourceFactory) VmFatalException(org.aion.zero.impl.vm.common.VmFatalException) BigInteger(java.math.BigInteger) AionTransaction(org.aion.base.AionTransaction) AionTxReceipt(org.aion.base.AionTxReceipt)

Example 57 with AionTxReceipt

use of org.aion.base.AionTxReceipt in project aion by aionnetwork.

the class OldTxExecutorTest method testBasicTransactionCost.

@Test
public void testBasicTransactionCost() throws Exception {
    byte[] txNonce = BigInteger.ZERO.toByteArray();
    AionAddress to = AddressUtils.wrapAddress("2222222222222222222222222222222222222222222222222222222222222222");
    byte[] value = BigInteger.ONE.toByteArray();
    byte[] data = new byte[0];
    long nrg = new DataWord(100000L).longValue();
    long nrgPrice = DataWord.ONE.longValue();
    ECKey key = ECKeyFac.inst().create();
    AionTransaction tx = AionTransaction.create(key, txNonce, to, value, data, nrg, nrgPrice, TransactionTypes.DEFAULT, null);
    MiningBlock block = createDummyBlock();
    AionRepositoryImpl repoTop = blockchain.getRepository();
    RepositoryCache repo = repoTop.startTracking();
    repo.addBalance(tx.getSenderAddress(), BigInteger.valueOf(1_000_000_000L));
    repo.flushTo(repoTop, true);
    AionTxReceipt receipt = executeTransaction(repo, block, tx).getReceipt();
    System.out.println(receipt);
    assertEquals(TxUtil.calculateTransactionCost(tx), receipt.getEnergyUsed());
}
Also used : AionAddress(org.aion.types.AionAddress) RepositoryCache(org.aion.base.db.RepositoryCache) DataWord(org.aion.util.types.DataWord) ECKey(org.aion.crypto.ECKey) AionTransaction(org.aion.base.AionTransaction) AionRepositoryImpl(org.aion.zero.impl.db.AionRepositoryImpl) AionTxReceipt(org.aion.base.AionTxReceipt) MiningBlock(org.aion.zero.impl.types.MiningBlock) Test(org.junit.Test)

Example 58 with AionTxReceipt

use of org.aion.base.AionTxReceipt in project aion by aionnetwork.

the class OldTxExecutorTest method testCreateTransaction.

@Test
public void testCreateTransaction() throws Exception {
    Compiler.Result r = Compiler.getInstance().compile(ContractUtils.readContract("Ticker.sol"), Options.ABI, Options.BIN);
    CompilationResult cr = CompilationResult.parse(r.output);
    String deployer = cr.contracts.get("Ticker").bin;
    System.out.println(deployer);
    byte[] txNonce = BigInteger.ZERO.toByteArray();
    AionAddress to = null;
    byte[] value = BigInteger.ZERO.toByteArray();
    byte[] data = Hex.decode(deployer);
    long nrg = 500_000L;
    long nrgPrice = 1;
    AionTransaction tx = AionTransaction.create(deployerKey, txNonce, to, value, data, nrg, nrgPrice, TransactionTypes.DEFAULT, null);
    MiningBlock block = createDummyBlock();
    AionRepositoryImpl repoTop = blockchain.getRepository();
    RepositoryCache repo = repoTop.startTracking();
    repo.addBalance(tx.getSenderAddress(), BigInteger.valueOf(500_000L).multiply(BigInteger.valueOf(tx.getEnergyPrice())));
    AionTxReceipt receipt = executeTransaction(repo, block, tx).getReceipt();
    System.out.println(receipt);
    assertArrayEquals(Hex.decode(deployer.substring(deployer.indexOf("60506040", 1))), receipt.getTransactionOutput());
}
Also used : Compiler(org.aion.solidity.Compiler) AionAddress(org.aion.types.AionAddress) RepositoryCache(org.aion.base.db.RepositoryCache) AionTransaction(org.aion.base.AionTransaction) AionRepositoryImpl(org.aion.zero.impl.db.AionRepositoryImpl) CompilationResult(org.aion.solidity.CompilationResult) AionTxReceipt(org.aion.base.AionTxReceipt) MiningBlock(org.aion.zero.impl.types.MiningBlock) Test(org.junit.Test)

Example 59 with AionTxReceipt

use of org.aion.base.AionTxReceipt in project aion by aionnetwork.

the class StatefulnessTest method testUsingCallInContract.

@Test
public void testUsingCallInContract() {
    AvmVersion version = AvmVersion.VERSION_1;
    if (txType == TransactionTypes.DEFAULT) {
        // skip this test cause the contract can't deploy successfully in the FVM.
        return;
    }
    AionTxReceipt receipt = deployContract(version);
    // Check the contract has the Avm prefix, and deployment succeeded, and grab the address.
    assertEquals(AddressSpecs.A0_IDENTIFIER, receipt.getTransactionOutput()[0]);
    assertTrue(receipt.isSuccessful());
    AionAddress contract = new AionAddress(receipt.getTransactionOutput());
    BigInteger deployerInitialNonce = getNonce(this.deployer);
    BigInteger contractInitialNonce = getNonce(contract);
    BigInteger deployerInitialBalance = getBalance(this.deployer);
    BigInteger contractInitialBalance = getBalance(contract);
    BigInteger fundsToSendToContract = BigInteger.valueOf(1000);
    // Transfer some value to the contract so we can do a 'call' from within it.
    receipt = transferValueTo(contract, fundsToSendToContract);
    assertTrue(receipt.isSuccessful());
    // verify that the sender and contract balances are correct after the transfer.
    BigInteger transferEnergyCost = BigInteger.valueOf(receipt.getEnergyUsed()).multiply(BigInteger.valueOf(this.energyPrice));
    BigInteger deployerBalanceAfterTransfer = deployerInitialBalance.subtract(fundsToSendToContract).subtract(transferEnergyCost);
    BigInteger contractBalanceAfterTransfer = contractInitialBalance.add(fundsToSendToContract);
    BigInteger deployerNonceAfterTransfer = deployerInitialNonce.add(BigInteger.ONE);
    assertEquals(deployerBalanceAfterTransfer, getBalance(this.deployer));
    assertEquals(contractBalanceAfterTransfer, getBalance(contract));
    assertEquals(deployerNonceAfterTransfer, getNonce(this.deployer));
    assertEquals(contractInitialNonce, getNonce(contract));
    // Generate a random beneficiary to transfer funds to via the contract.
    AionAddress beneficiary = randomAddress();
    long valueForContractToSend = fundsToSendToContract.longValue() / 2;
    // Call the contract to send value using an internal call.
    receipt = callContract(version, contract, "transferValue", beneficiary.toByteArray(), valueForContractToSend);
    assertTrue(receipt.isSuccessful());
    // Verify the accounts have the expected state.
    BigInteger deployerBalanceAfterCall = getBalance(this.deployer);
    BigInteger contractBalanceAfterCall = getBalance(contract);
    BigInteger beneficiaryBalanceAfterCall = getBalance(beneficiary);
    BigInteger callEnergyCost = BigInteger.valueOf(receipt.getEnergyUsed()).multiply(BigInteger.valueOf(this.energyPrice));
    assertEquals(deployerBalanceAfterTransfer.subtract(callEnergyCost), deployerBalanceAfterCall);
    assertEquals(contractBalanceAfterTransfer.subtract(BigInteger.valueOf(valueForContractToSend)), contractBalanceAfterCall);
    assertEquals(BigInteger.valueOf(valueForContractToSend), beneficiaryBalanceAfterCall);
    assertEquals(deployerNonceAfterTransfer.add(BigInteger.ONE), getNonce(this.deployer));
    // The contract nonce increases because it fires off an internal transaction.
    assertEquals(contractInitialNonce.add(BigInteger.ONE), getNonce(contract));
}
Also used : AionAddress(org.aion.types.AionAddress) BigInteger(java.math.BigInteger) AionTxReceipt(org.aion.base.AionTxReceipt) AvmVersion(org.aion.avm.stub.AvmVersion) Test(org.junit.Test)

Example 60 with AionTxReceipt

use of org.aion.base.AionTxReceipt in project aion by aionnetwork.

the class AlternatingVmBlockTest method testFullBlockWithAlternatingVms.

/**
 * Tests constructing a block with the max number of alternating transactions without going over
 * the block energy limit. This should be successful.
 */
@Test
public void testFullBlockWithAlternatingVms() throws IOException {
    BigInteger nonce = BigInteger.ZERO;
    long avmContractDeployEnergyUsed = getAvmContractDeploymentCost(AvmVersion.VERSION_1, nonce);
    long fvmContractDeployEnergyUsed = getFvmContractDeploymentCost(nonce.add(BigInteger.ONE));
    List<AionTransaction> alternatingTransactions = makeAlternatingAvmFvmContractCreateTransactions(AvmVersion.VERSION_1, 4, nonce.add(BigInteger.TWO));
    Block parentBlock = blockchain.getBestBlock();
    MiningBlock block = blockchain.createBlock(parentBlock, alternatingTransactions, false, parentBlock.getTimestamp());
    Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block);
    long expectedEnergyUsed = (avmContractDeployEnergyUsed * 2) + (fvmContractDeployEnergyUsed * 2);
    assertEquals(ImportResult.IMPORTED_BEST, connectResult.getLeft());
    assertEquals(expectedEnergyUsed, connectResult.getRight().getBlock().getNrgConsumed());
    assertTrue(connectResult.getRight().getBlock().getNrgLimit() > expectedEnergyUsed);
    boolean isAvmTransaction = true;
    for (AionTxReceipt receipt : connectResult.getRight().getReceipts()) {
        if (isAvmTransaction) {
            assertEquals(avmContractDeployEnergyUsed, receipt.getEnergyUsed());
        } else {
            assertEquals(fvmContractDeployEnergyUsed, receipt.getEnergyUsed());
        }
        assertTrue(receipt.isSuccessful());
        isAvmTransaction = !isAvmTransaction;
    }
}
Also used : ImportResult(org.aion.zero.impl.core.ImportResult) AionBlockSummary(org.aion.zero.impl.types.AionBlockSummary) BigInteger(java.math.BigInteger) MiningBlock(org.aion.zero.impl.types.MiningBlock) Block(org.aion.zero.impl.types.Block) AionTransaction(org.aion.base.AionTransaction) AionTxReceipt(org.aion.base.AionTxReceipt) MiningBlock(org.aion.zero.impl.types.MiningBlock) Test(org.junit.Test)

Aggregations

AionTxReceipt (org.aion.base.AionTxReceipt)111 Test (org.junit.Test)76 AionTransaction (org.aion.base.AionTransaction)74 AionBlockSummary (org.aion.zero.impl.types.AionBlockSummary)61 AionAddress (org.aion.types.AionAddress)56 BigInteger (java.math.BigInteger)53 ImportResult (org.aion.zero.impl.core.ImportResult)50 MiningBlock (org.aion.zero.impl.types.MiningBlock)43 ArrayList (java.util.ArrayList)24 Block (org.aion.zero.impl.types.Block)24 AionTxExecSummary (org.aion.base.AionTxExecSummary)17 RepositoryCache (org.aion.base.db.RepositoryCache)17 StandaloneBlockchain (org.aion.zero.impl.blockchain.StandaloneBlockchain)15 Builder (org.aion.zero.impl.blockchain.StandaloneBlockchain.Builder)14 ECKey (org.aion.crypto.ECKey)12 SolidityType (org.aion.solidity.SolidityType)10 AccountState (org.aion.base.AccountState)9 Log (org.aion.types.Log)9 AionTxInfo (org.aion.zero.impl.types.AionTxInfo)7 StakingBlock (org.aion.zero.impl.types.StakingBlock)7