Search in sources :

Example 6 with Coin

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

the class SyncProcessorTest method processBodyResponseWithTransactionAddsToBlockchain.

@Test
public void processBodyResponseWithTransactionAddsToBlockchain() {
    Account senderAccount = createAccount("sender");
    Account receiverAccount = createAccount("receiver");
    List<Account> accounts = new ArrayList<Account>();
    List<Coin> balances = new ArrayList<>();
    accounts.add(senderAccount);
    balances.add(Coin.valueOf(20000000));
    accounts.add(receiverAccount);
    balances.add(Coin.ZERO);
    final BlockStore store = new BlockStore();
    Blockchain blockchain = BlockChainBuilder.ofSize(0, false, accounts, balances);
    Block genesis = blockchain.getBestBlock();
    SimpleMessageChannel sender = new SimpleMessageChannel(new byte[] { 0x01 });
    Assert.assertEquals(0, blockchain.getBestBlock().getNumber());
    Transaction tx = createTransaction(senderAccount, receiverAccount, BigInteger.valueOf(1000000), BigInteger.ZERO);
    List<Transaction> txs = new ArrayList<>();
    txs.add(tx);
    Block block = new BlockGenerator().createChildBlock(genesis, txs, blockchain.getRepository().getRoot());
    BlockExecutor blockExecutor = new BlockExecutor(config, blockchain.getRepository(), null, blockchain.getBlockStore(), null);
    Assert.assertEquals(1, block.getTransactionsList().size());
    blockExecutor.executeAndFillAll(block, genesis);
    Assert.assertEquals(21000, block.getFeesPaidToMiner().asBigInteger().intValueExact());
    Assert.assertEquals(1, block.getTransactionsList().size());
    Assert.assertEquals(1, block.getNumber());
    Assert.assertArrayEquals(blockchain.getBestBlockHash(), block.getParentHash().getBytes());
    BlockNodeInformation nodeInformation = new BlockNodeInformation();
    RskSystemProperties config = new RskSystemProperties();
    BlockSyncService blockSyncService = new BlockSyncService(config, store, blockchain, nodeInformation, SyncConfiguration.IMMEDIATE_FOR_TESTING);
    SyncProcessor processor = new SyncProcessor(config, blockchain, blockSyncService, RskMockFactory.getPeerScoringManager(), getChannelManager(), SyncConfiguration.IMMEDIATE_FOR_TESTING, new ProofOfWorkRule(config).setFallbackMiningEnabled(false), DIFFICULTY_CALCULATOR);
    processor.setSelectedPeer(sender, StatusUtils.getFakeStatus(), 0);
    List<Transaction> transactions = block.getTransactionsList();
    List<BlockHeader> uncles = block.getUncleList();
    long lastRequestId = new Random().nextLong();
    BodyResponseMessage response = new BodyResponseMessage(lastRequestId, transactions, uncles);
    processor.registerExpectedMessage(response);
    Deque<BlockHeader> headerStack = new ArrayDeque<>();
    headerStack.add(block.getHeader());
    List<Deque<BlockHeader>> headers = new ArrayList<>();
    headers.add(headerStack);
    List<BlockIdentifier> bids = new ArrayList<>();
    bids.add(new BlockIdentifier(blockchain.getBlockByNumber(0).getHash().getBytes(), 0));
    bids.add(new BlockIdentifier(block.getHash().getBytes(), 1));
    processor.startDownloadingBodies(headers, Collections.singletonMap(sender.getPeerNodeID(), bids));
    ((DownloadingBodiesSyncState) processor.getSyncState()).expectBodyResponseFor(lastRequestId, sender.getPeerNodeID(), block.getHeader());
    processor.processBodyResponse(sender, response);
    Assert.assertEquals(1, blockchain.getBestBlock().getNumber());
    Assert.assertArrayEquals(block.getHash().getBytes(), blockchain.getBestBlockHash());
    Assert.assertTrue(processor.getExpectedResponses().isEmpty());
}
Also used : BlockGenerator(co.rsk.blockchain.utils.BlockGenerator) ProofOfWorkRule(co.rsk.validators.ProofOfWorkRule) Coin(co.rsk.core.Coin) BlockExecutor(co.rsk.core.bc.BlockExecutor) DownloadingBodiesSyncState(co.rsk.net.sync.DownloadingBodiesSyncState) SimpleMessageChannel(co.rsk.net.simples.SimpleMessageChannel) RskSystemProperties(co.rsk.config.RskSystemProperties) Test(org.junit.Test)

Example 7 with Coin

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

the class TestProgramInvokeFactory method generalInvoke.

private ProgramInvoke generalInvoke(Transaction tx, int txindex, Repository repository, BlockStore blockStore) {
    /**
     *         ADDRESS op       **
     */
    // YP: Get address of currently executing account.
    RskAddress addr = tx.isContractCreation() ? tx.getContractAddress() : tx.getReceiveAddress();
    /**
     *         ORIGIN op       **
     */
    // YP: This is the sender of original transaction; it is never a contract.
    RskAddress origin = tx.getSender();
    /**
     *         CALLER op       **
     */
    // YP: This is the address of the account that is directly responsible for this execution.
    RskAddress caller = tx.getSender();
    /**
     *         BALANCE op       **
     */
    Coin balance = repository.getBalance(addr);
    /**
     *         GASPRICE op       **
     */
    Coin gasPrice = tx.getGasPrice();
    /**
     * GAS op **
     */
    byte[] gas = tx.getGasLimit();
    /**
     *        CALLVALUE op      **
     */
    Coin callValue = tx.getValue() == null ? Coin.ZERO : tx.getValue();
    /**
     *     CALLDATALOAD  op   **
     */
    /**
     *     CALLDATACOPY  op   **
     */
    /**
     *     CALLDATASIZE  op   **
     */
    byte[] data = tx.isContractCreation() ? ByteUtil.EMPTY_BYTE_ARRAY : (tx.getData() == null ? ByteUtil.EMPTY_BYTE_ARRAY : tx.getData());
    // byte[] data =  tx.getData() == null ? ByteUtil.EMPTY_BYTE_ARRAY : tx.getData() ;
    /**
     *    PREVHASH  op  **
     */
    byte[] lastHash = env.getPreviousHash();
    /**
     *   COINBASE  op **
     */
    byte[] coinbase = env.getCurrentCoinbase();
    /**
     * TIMESTAMP  op  **
     */
    long timestamp = ByteUtil.byteArrayToLong(env.getCurrentTimestamp());
    /**
     * NUMBER  op  **
     */
    long number = ByteUtil.byteArrayToLong(env.getCurrentNumber());
    /**
     * DIFFICULTY  op  **
     */
    byte[] difficulty = env.getCurrentDifficulty();
    /**
     * GASLIMIT op **
     */
    byte[] gaslimit = env.getCurrentGasLimit();
    return new ProgramInvokeImpl(addr.getBytes(), origin.getBytes(), caller.getBytes(), balance.getBytes(), gasPrice.getBytes(), gas, callValue.getBytes(), data, lastHash, coinbase, timestamp, number, txindex, difficulty, gaslimit, repository, blockStore);
}
Also used : Coin(co.rsk.core.Coin) RskAddress(co.rsk.core.RskAddress) ProgramInvokeImpl(org.ethereum.vm.program.invoke.ProgramInvokeImpl)

Example 8 with Coin

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

the class AccountBuilder method build.

public static StateWrap build(AccountTck account) {
    ContractDetailsImpl details = new ContractDetailsImpl(new RskSystemProperties());
    details.setCode(parseData(account.getCode()));
    details.setStorage(convertStorage(account.getStorage()));
    AccountState state = new AccountState();
    state.addToBalance(new Coin(unifiedNumericToBigInteger(account.getBalance())));
    state.setNonce(unifiedNumericToBigInteger(account.getNonce()));
    state.setStateRoot(details.getStorageHash());
    state.setCodeHash(HashUtil.keccak256(details.getCode()));
    return new StateWrap(state, details);
}
Also used : Coin(co.rsk.core.Coin) ContractDetailsImpl(co.rsk.db.ContractDetailsImpl) AccountState(org.ethereum.core.AccountState) RskSystemProperties(co.rsk.config.RskSystemProperties)

Example 9 with Coin

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

the class AccountValidator method valid.

public static List<String> valid(RskAddress addr, AccountState expectedState, ContractDetails expectedDetails, AccountState currentState, ContractDetails currentDetails) {
    List<String> results = new ArrayList<>();
    if (currentState == null || currentDetails == null) {
        String formattedString = String.format("Account: %s: expected but doesn't exist", addr);
        results.add(formattedString);
        return results;
    }
    if (expectedState == null || expectedDetails == null) {
        String formattedString = String.format("Account: %s: unexpected account in the repository", addr);
        results.add(formattedString);
        return results;
    }
    Coin expectedBalance = expectedState.getBalance();
    if (!currentState.getBalance().equals(expectedBalance)) {
        String formattedString = String.format("Account: %s: has unexpected balance, expected balance: %s found balance: %s", addr, expectedBalance.toString(), currentState.getBalance().toString());
        results.add(formattedString);
    }
    BigInteger expectedNonce = expectedState.getNonce();
    if (currentState.getNonce().compareTo(expectedNonce) != 0) {
        String formattedString = String.format("Account: %s: has unexpected nonce, expected nonce: %s found nonce: %s", addr, expectedNonce.toString(), currentState.getNonce().toString());
        results.add(formattedString);
    }
    byte[] code = Arrays.equals(currentState.getCodeHash(), EMPTY_DATA_HASH) ? new byte[0] : currentDetails.getCode();
    if (!Arrays.equals(expectedDetails.getCode(), code)) {
        String formattedString = String.format("Account: %s: has unexpected code, expected code: %s found code: %s", addr, Hex.toHexString(expectedDetails.getCode()), Hex.toHexString(currentDetails.getCode()));
        results.add(formattedString);
    }
    // compare storage
    Set<DataWord> currentKeys = currentDetails.getStorage().keySet();
    Set<DataWord> expectedKeys = expectedDetails.getStorage().keySet();
    Set<DataWord> checked = new HashSet<>();
    for (DataWord key : currentKeys) {
        DataWord currentValue = currentDetails.getStorage().get(key);
        DataWord expectedValue = expectedDetails.getStorage().get(key);
        if (expectedValue == null) {
            String formattedString = String.format("Account: %s: has unexpected storage data: %s = %s", addr, key, currentValue);
            results.add(formattedString);
            continue;
        }
        if (!expectedValue.equals(currentValue)) {
            String formattedString = String.format("Account: %s: has unexpected value, for key: %s , expectedValue: %s real value: %s", addr, key.toString(), expectedValue.toString(), currentValue.toString());
            results.add(formattedString);
            continue;
        }
        checked.add(key);
    }
    for (DataWord key : expectedKeys) {
        if (!checked.contains(key)) {
            String formattedString = String.format("Account: %s: doesn't exist expected storage key: %s", addr, key.toString());
            results.add(formattedString);
        }
    }
    return results;
}
Also used : Coin(co.rsk.core.Coin) BigInteger(java.math.BigInteger) DataWord(org.ethereum.vm.DataWord)

Example 10 with Coin

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

the class BlockchainVMTest method testSEND_1.

@Test
public void testSEND_1() {
    NewBlockChainInfo binfo = createNewBlockchain();
    Blockchain blockchain = binfo.blockchain;
    BlockGenerator blockGenerator = new BlockGenerator();
    Block block1 = blockGenerator.createChildBlock(blockchain.getBestBlock(), null, binfo.repository.getRoot());
    List<Transaction> txs = new ArrayList<>();
    Coin transferAmount = Coin.valueOf(100L);
    // Add a single transaction paying to a new address
    byte[] dstAddress = randomAddress();
    BigInteger transactionGasLimit = new BigInteger("21000");
    Coin transactionGasPrice = Coin.valueOf(1);
    Transaction t = new Transaction(ZERO_BYTE_ARRAY, transactionGasPrice.getBytes(), transactionGasLimit.toByteArray(), dstAddress, transferAmount.getBytes(), null, new RskSystemProperties().getBlockchainConfig().getCommonConstants().getChainId());
    t.sign(binfo.faucetKey.getPrivKeyBytes());
    txs.add(t);
    Block block2 = blockGenerator.createChildBlock(block1, txs, binfo.repository.getRoot());
    Assert.assertEquals(ImportResult.IMPORTED_BEST, blockchain.tryToConnect(block1));
    MinerHelper mh = new MinerHelper(binfo.repository, binfo.blockchain);
    mh.completeBlock(block2, block1);
    Assert.assertEquals(ImportResult.IMPORTED_BEST, blockchain.tryToConnect(block2));
    Assert.assertEquals(blockchain.getBestBlock(), block2);
    Assert.assertEquals(2, block2.getNumber());
    Coin srcAmount = faucetAmount.subtract(transferAmount);
    srcAmount = srcAmount.subtract(transactionGasPrice.multiply(transactionGasLimit));
    Assert.assertEquals(binfo.repository.getBalance(new RskAddress(binfo.faucetKey.getAddress())), srcAmount);
    Assert.assertEquals(binfo.repository.getBalance(new RskAddress(dstAddress)), transferAmount);
}
Also used : ArrayList(java.util.ArrayList) BlockGenerator(co.rsk.blockchain.utils.BlockGenerator) Coin(co.rsk.core.Coin) RskAddress(co.rsk.core.RskAddress) BigInteger(java.math.BigInteger) RskSystemProperties(co.rsk.config.RskSystemProperties) 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