Search in sources :

Example 66 with Coin

use of co.rsk.core.Coin in project rskj by rsksmart.

the class TransactionExecutor method finalization.

public void finalization() {
    if (!readyToExecute) {
        return;
    }
    // RSK if local call gas balances must not be changed
    if (localCall) {
        return;
    }
    logger.trace("Finalize transaction {} {}", toBI(tx.getNonce()), tx.getHash());
    cacheTrack.commit();
    // Should include only LogInfo's that was added during not rejected transactions
    List<LogInfo> notRejectedLogInfos = result.getLogInfoList().stream().filter(logInfo -> !logInfo.isRejected()).collect(Collectors.toList());
    TransactionExecutionSummary.Builder summaryBuilder = TransactionExecutionSummary.builderFor(tx).gasLeftover(mEndGas).logs(notRejectedLogInfos).result(result.getHReturn());
    if (result != null) {
        // Accumulate refunds for suicides
        result.addFutureRefund((long) result.getDeleteAccounts().size() * GasCost.SUICIDE_REFUND);
        long gasRefund = Math.min(result.getFutureRefund(), result.getGasUsed() / 2);
        RskAddress addr = tx.isContractCreation() ? tx.getContractAddress() : tx.getReceiveAddress();
        mEndGas = mEndGas.add(BigInteger.valueOf(gasRefund));
        summaryBuilder.gasUsed(toBI(result.getGasUsed())).gasRefund(toBI(gasRefund)).deletedAccounts(result.getDeleteAccounts()).internalTransactions(result.getInternalTransactions());
        ContractDetails cdetails = track.getContractDetails(addr);
        if (cdetails != null) {
            summaryBuilder.storageDiff(cdetails.getStorage());
        }
        if (result.getException() != null) {
            summaryBuilder.markAsFailed();
        }
    }
    logger.trace("Building transaction execution summary");
    TransactionExecutionSummary summary = summaryBuilder.build();
    // Refund for gas leftover
    track.addBalance(tx.getSender(), summary.getLeftover().add(summary.getRefund()));
    logger.trace("Pay total refund to sender: [{}], refund val: [{}]", tx.getSender(), summary.getRefund());
    // Transfer fees to miner
    Coin summaryFee = summary.getFee();
    // TODO: REMOVE THIS WHEN THE LocalBLockTests starts working with REMASC
    if (config.isRemascEnabled()) {
        logger.trace("Adding fee to remasc contract account");
        track.addBalance(PrecompiledContracts.REMASC_ADDR, summaryFee);
    } else {
        track.addBalance(coinbase, summaryFee);
    }
    this.paidFees = summaryFee;
    if (result != null) {
        logger.trace("Processing result");
        logs = notRejectedLogInfos;
        result.getCodeChanges().forEach((key, value) -> track.saveCode(new RskAddress(key), value));
        // Traverse list of suicides
        result.getDeleteAccounts().forEach(address -> track.delete(new RskAddress(address)));
    }
    if (listener != null) {
        listener.onTransactionExecuted(summary);
    }
    logger.trace("tx listener done");
    if (config.vmTrace() && program != null && result != null) {
        ProgramTrace trace = program.getTrace().result(result.getHReturn()).error(result.getException());
        String txHash = tx.getHash().toHexString();
        try {
            saveProgramTraceFile(config, txHash, trace);
            if (listener != null) {
                listener.onVMTraceCreated(txHash, trace);
            }
        } catch (IOException e) {
            String errorMessage = String.format("Cannot write trace to file: %s", e.getMessage());
            panicProcessor.panic("executor", errorMessage);
            logger.error(errorMessage);
        }
    }
    logger.trace("tx finalization done");
}
Also used : Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) EMPTY_BYTE_ARRAY(org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY) RskAddress(co.rsk.core.RskAddress) EthereumListenerAdapter(org.ethereum.listener.EthereumListenerAdapter) Coin(co.rsk.core.Coin) ArrayUtils.isEmpty(org.apache.commons.lang3.ArrayUtils.isEmpty) ContractDetails(org.ethereum.db.ContractDetails) BlockchainConfig(org.ethereum.config.BlockchainConfig) BigInteger(java.math.BigInteger) VMUtils.saveProgramTraceFile(org.ethereum.vm.VMUtils.saveProgramTraceFile) ProgramInvoke(org.ethereum.vm.program.invoke.ProgramInvoke) PanicProcessor(co.rsk.panic.PanicProcessor) Logger(org.slf4j.Logger) IOException(java.io.IOException) BlockStore(org.ethereum.db.BlockStore) EthereumListener(org.ethereum.listener.EthereumListener) Collectors(java.util.stream.Collectors) BIUtil(org.ethereum.util.BIUtil) ArrayUtils.getLength(org.apache.commons.lang3.ArrayUtils.getLength) ReceiptStore(org.ethereum.db.ReceiptStore) Program(org.ethereum.vm.program.Program) ProgramTrace(org.ethereum.vm.trace.ProgramTrace) List(java.util.List) VmConfig(co.rsk.config.VmConfig) org.ethereum.vm(org.ethereum.vm) ProgramResult(org.ethereum.vm.program.ProgramResult) ProgramInvokeFactory(org.ethereum.vm.program.invoke.ProgramInvokeFactory) RskSystemProperties(co.rsk.config.RskSystemProperties) Constants(org.ethereum.config.Constants) Coin(co.rsk.core.Coin) ProgramTrace(org.ethereum.vm.trace.ProgramTrace) RskAddress(co.rsk.core.RskAddress) IOException(java.io.IOException) ContractDetails(org.ethereum.db.ContractDetails)

Example 67 with Coin

use of co.rsk.core.Coin in project rskj by rsksmart.

the class TransactionExecutor method execute.

public void execute() {
    if (!readyToExecute) {
        return;
    }
    logger.trace("Execute transaction {} {}", toBI(tx.getNonce()), tx.getHash());
    if (!localCall) {
        track.increaseNonce(tx.getSender());
        BigInteger txGasLimit = toBI(tx.getGasLimit());
        Coin txGasCost = tx.getGasPrice().multiply(txGasLimit);
        track.addBalance(tx.getSender(), txGasCost.negate());
        logger.trace("Paying: txGasCost: [{}], gasPrice: [{}], gasLimit: [{}]", txGasCost, tx.getGasPrice(), txGasLimit);
    }
    if (tx.isContractCreation()) {
        create();
    } else {
        call();
    }
}
Also used : Coin(co.rsk.core.Coin) BigInteger(java.math.BigInteger)

Example 68 with Coin

use of co.rsk.core.Coin in project rskj by rsksmart.

the class GenesisLoader method generatePreMine.

private static Map<RskAddress, InitialAddressState> generatePreMine(RskSystemProperties config, BigInteger initialNonce, Map<String, AllocatedAccount> alloc) {
    Map<RskAddress, InitialAddressState> premine = new HashMap<>();
    ContractDetailsMapper detailsMapper = new ContractDetailsMapper(config);
    for (Map.Entry<String, AllocatedAccount> accountEntry : alloc.entrySet()) {
        if (!StringUtils.equals("00", accountEntry.getKey())) {
            Coin balance = new Coin(new BigInteger(accountEntry.getValue().getBalance()));
            BigInteger nonce;
            if (accountEntry.getValue().getNonce() != null) {
                nonce = new BigInteger(accountEntry.getValue().getNonce());
            } else {
                nonce = initialNonce;
            }
            AccountState acctState = new AccountState(nonce, balance);
            ContractDetails contractDetails = null;
            Contract contract = accountEntry.getValue().getContract();
            if (contract != null) {
                contractDetails = detailsMapper.mapFromContract(contract);
                if (contractDetails.getCode() != null) {
                    acctState.setCodeHash(Keccak256Helper.keccak256(contractDetails.getCode()));
                }
                acctState.setStateRoot(contractDetails.getStorageHash());
            }
            premine.put(new RskAddress(accountEntry.getKey()), new InitialAddressState(acctState, contractDetails));
        }
    }
    return premine;
}
Also used : HashMap(java.util.HashMap) AccountState(org.ethereum.core.AccountState) ContractDetails(org.ethereum.db.ContractDetails) Coin(co.rsk.core.Coin) RskAddress(co.rsk.core.RskAddress) BigInteger(java.math.BigInteger) HashMap(java.util.HashMap) Map(java.util.Map)

Example 69 with Coin

use of co.rsk.core.Coin in project rskj by rsksmart.

the class TransactionPoolImplTest method processBestBlockRemovesTransactionsInBlock.

@Test
public void processBestBlockRemovesTransactionsInBlock() {
    BlockChainImpl blockchain = createBlockchain();
    Coin balance = Coin.valueOf(1000000);
    TransactionPoolImpl transactionPool = createSampleNewTransactionPoolWithAccounts(3, balance, blockchain);
    transactionPool.processBest(blockchain.getBestBlock());
    Transaction tx1 = createSampleTransaction(1, 2, 1000, 0);
    Transaction tx2 = createSampleTransaction(1, 2, 3000, 1);
    Transaction tx3 = createSampleTransaction(2, 3, 1000, 0);
    Transaction tx4 = createSampleTransaction(2, 3, 3000, 1);
    transactionPool.addTransaction(tx1);
    transactionPool.addTransaction(tx2);
    List<Transaction> txs = new ArrayList<>();
    txs.add(tx1);
    txs.add(tx2);
    txs.add(tx3);
    txs.add(tx4);
    transactionPool.addTransactions(txs);
    List<Transaction> btxs = new ArrayList<>();
    btxs.add(tx1);
    btxs.add(tx3);
    Block genesis = blockchain.getBestBlock();
    Block block = new BlockBuilder().parent(genesis).transactions(btxs).build();
    transactionPool.getBlockStore().saveBlock(genesis, new BlockDifficulty(BigInteger.ONE), true);
    transactionPool.processBest(block);
    List<Transaction> alltxs = transactionPool.getPendingTransactions();
    Assert.assertNotNull(alltxs);
    Assert.assertFalse(alltxs.isEmpty());
    Assert.assertEquals(2, alltxs.size());
    Assert.assertFalse(alltxs.contains(tx1));
    Assert.assertTrue(alltxs.contains(tx2));
    Assert.assertFalse(alltxs.contains(tx3));
    Assert.assertTrue(alltxs.contains(tx4));
    Assert.assertSame(block, transactionPool.getBestBlock());
}
Also used : Coin(co.rsk.core.Coin) BlockDifficulty(co.rsk.core.BlockDifficulty) Transaction(org.ethereum.core.Transaction) ArrayList(java.util.ArrayList) Block(org.ethereum.core.Block) BlockBuilder(co.rsk.test.builders.BlockBuilder) Test(org.junit.Test)

Example 70 with Coin

use of co.rsk.core.Coin in project rskj by rsksmart.

the class TransactionPoolImplTest method addAndExecuteTwoPendingTransaction.

@Test
public void addAndExecuteTwoPendingTransaction() {
    BlockChainImpl blockchain = createBlockchain();
    Coin balance = Coin.valueOf(1000000);
    TransactionPoolImpl transactionPool = createSampleNewTransactionPoolWithAccounts(2, balance, blockchain);
    transactionPool.processBest(blockchain.getBestBlock());
    Transaction tx1 = createSampleTransaction(1, 2, 1000, 0);
    Transaction tx2 = createSampleTransaction(1, 2, 3000, 1);
    Account receiver = createAccount(2);
    transactionPool.addTransaction(tx1);
    transactionPool.addTransaction(tx2);
    Repository repository = transactionPool.getRepository();
    Assert.assertEquals(BigInteger.valueOf(1004000), repository.getBalance(receiver.getAddress()).asBigInteger());
}
Also used : Coin(co.rsk.core.Coin) Account(org.ethereum.core.Account) Repository(org.ethereum.core.Repository) Transaction(org.ethereum.core.Transaction) Test(org.junit.Test)

Aggregations

Coin (co.rsk.core.Coin)95 Test (org.junit.Test)46 RskAddress (co.rsk.core.RskAddress)37 BigInteger (java.math.BigInteger)32 Repository (org.ethereum.core.Repository)23 Transaction (org.ethereum.core.Transaction)23 Program (org.ethereum.vm.program.Program)12 AccountState (org.ethereum.core.AccountState)10 ArrayList (java.util.ArrayList)9 Ignore (org.junit.Ignore)9 ProgramInvokeMockImpl (org.ethereum.vm.program.invoke.ProgramInvokeMockImpl)8 Account (org.ethereum.core.Account)7 BlockExecutor (co.rsk.core.bc.BlockExecutor)6 BlockChainBuilder (co.rsk.test.builders.BlockChainBuilder)6 Keccak256 (co.rsk.crypto.Keccak256)5 Block (org.ethereum.core.Block)5 DataWord (org.ethereum.vm.DataWord)5 ProgramInvoke (org.ethereum.vm.program.invoke.ProgramInvoke)5 BlockGenerator (co.rsk.blockchain.utils.BlockGenerator)4 RskSystemProperties (co.rsk.config.RskSystemProperties)4