Search in sources :

Example 61 with ECKey

use of org.ethereum.crypto.ECKey in project rskj by rsksmart.

the class BlockGenerator method createFallbackMinedChildBlockWithTimeStamp.

public Block createFallbackMinedChildBlockWithTimeStamp(Block parent, byte[] difficulty, long timeStamp, boolean goodSig) {
    List<Transaction> txs = new ArrayList<>();
    Block block = new Block(// parent hash
    parent.getHash().getBytes(), // uncle hash
    EMPTY_LIST_HASH, parent.getCoinbase().getBytes(), ByteUtils.clone(new Bloom().getData()), // difficulty
    difficulty, parent.getNumber() + 1, parent.getGasLimit(), parent.getGasUsed(), timeStamp, // extraData
    EMPTY_BYTE_ARRAY, // mixHash
    EMPTY_BYTE_ARRAY, // provisory nonce
    BigInteger.ZERO.toByteArray(), // receipts root
    EMPTY_TRIE_HASH, // transaction root
    BlockChainImpl.calcTxTrie(txs), // EMPTY_TRIE_HASH,   // state root
    ByteUtils.clone(parent.getStateRoot()), // transaction list
    txs, // uncle list
    null, null, Coin.ZERO);
    ECKey fallbackMiningKey0 = ECKey.fromPrivate(BigInteger.TEN);
    ECKey fallbackMiningKey1 = ECKey.fromPrivate(BigInteger.TEN.add(BigInteger.ONE));
    ECKey fallbackKey;
    if (block.getNumber() % 2 == 0) {
        fallbackKey = fallbackMiningKey0;
    } else {
        fallbackKey = fallbackMiningKey1;
    }
    byte[] signature = fallbackSign(block.getHashForMergedMining(), fallbackKey);
    if (!goodSig) {
        // just make it a little bad
        signature[5] = (byte) (signature[5] + 1);
    }
    block.setBitcoinMergedMiningHeader(signature);
    return block;
}
Also used : SimpleRskTransaction(co.rsk.peg.simples.SimpleRskTransaction) ArrayList(java.util.ArrayList) SimpleBlock(co.rsk.peg.simples.SimpleBlock) ECKey(org.ethereum.crypto.ECKey)

Example 62 with ECKey

use of org.ethereum.crypto.ECKey in project rskj by rsksmart.

the class CodeReplaceTest method replaceCodeTest1.

@Test
public void replaceCodeTest1() throws IOException, InterruptedException {
    BigInteger nonce = config.getBlockchainConfig().getCommonConstants().getInitialNonce();
    BlockChainImpl blockchain = org.ethereum.core.ImportLightTest.createBlockchain(GenesisLoader.loadGenesis(config, nonce, getClass().getResourceAsStream("/genesis/genesis-light.json"), false));
    ECKey sender = ECKey.fromPrivate(Hex.decode("3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c"));
    System.out.println("address: " + Hex.toHexString(sender.getAddress()));
    String asm = // (7b) Extract real code into address 0, skip first 12 bytes, copy 20 bytes
    "0x14 0x0C 0x00 CODECOPY " + // (5b) offset 0, size 0x14, now return the first code
    "0x14 0x00  RETURN " + // (4b) header script v1
    "HEADER !0x01 !0x01 !0x00 " + // (3b) store at offset 0, read data from offset 0. Transfer 32 bytes
    "0x00 CALLDATALOAD " + // (3b) store the data at address 0
    "0x00 MSTORE " + // We replace TWO TIMES to make sure that only the last replacement takes place
    "0x01 0x00 CODEREPLACE " + // This is the good one.
    "0x10 0x00 CODEREPLACE";
    // (5b) set new code: offset 0, size 16 bytes.
    EVMAssembler assembler = new EVMAssembler();
    byte[] code = assembler.assemble(asm);
    // Creates a contract
    Transaction tx1 = createTx(blockchain, sender, new byte[0], code);
    executeTransaction(blockchain, tx1);
    // Now we can directly check the store and see the new code.
    RskAddress createdContract = tx1.getContractAddress();
    byte[] expectedCode = Arrays.copyOfRange(code, 12, 12 + 20);
    byte[] installedCode = blockchain.getRepository().getContractDetails(createdContract).getCode();
    // assert the contract has been created
    Assert.assertTrue(Arrays.equals(expectedCode, installedCode));
    // Note that this code does not have a header, then its version == 0
    String asm2 = // (5b) Store at address 0x00, the value 0xFF
    "0xFF 0x00 MSTORE " + // (5b) And return such value 0xFF, at offset 0x1F
    "0x01 0x1F RETURN " + // fill with nops to make it 16 bytes in length
    "STOP STOP STOP STOP STOP STOP";
    // 16
    byte[] code2 = assembler.assemble(asm2);
    // The second transaction changes the contract code
    Transaction tx2 = createTx(blockchain, sender, tx1.getContractAddress().getBytes(), code2);
    TransactionExecutor executor2 = executeTransaction(blockchain, tx2);
    byte[] installedCode2 = blockchain.getRepository().getContractDetails(createdContract).getCode();
    // assert the contract code has been created
    Assert.assertTrue(Arrays.equals(installedCode2, code2));
    // there is one code change
    Assert.assertEquals(1, executor2.getResult().getCodeChanges().size());
    // We could add a third tx to execute the new code
    Transaction tx3 = createTx(blockchain, sender, tx1.getContractAddress().getBytes(), new byte[0]);
    TransactionExecutor executor3 = executeTransaction(blockchain, tx3);
    // check return code from contract call
    Assert.assertArrayEquals(Hex.decode("FF"), executor3.getResult().getHReturn());
}
Also used : Transaction(org.ethereum.core.Transaction) BlockChainImpl(co.rsk.core.bc.BlockChainImpl) BigInteger(java.math.BigInteger) ECKey(org.ethereum.crypto.ECKey) TransactionExecutor(org.ethereum.core.TransactionExecutor) EVMAssembler(co.rsk.asm.EVMAssembler) Test(org.junit.Test)

Example 63 with ECKey

use of org.ethereum.crypto.ECKey in project rskj by rsksmart.

the class CodeReplaceTest method replaceCodeTest2.

@Test
public void replaceCodeTest2() throws IOException, InterruptedException {
    // We test code replacement during initialization: this is forbitten.
    BigInteger nonce = config.getBlockchainConfig().getCommonConstants().getInitialNonce();
    BlockChainImpl blockchain = org.ethereum.core.ImportLightTest.createBlockchain(GenesisLoader.loadGenesis(config, nonce, getClass().getResourceAsStream("/genesis/genesis-light.json"), false));
    ECKey sender = ECKey.fromPrivate(Hex.decode("3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c"));
    System.out.println("address: " + Hex.toHexString(sender.getAddress()));
    String asm = // (4b) header script v1
    "HEADER !0x01 !0x01 !0x00 " + // (5b) we attempt to replace the code
    "0x01 0x00 CODEREPLACE " + // (7b) Extract real code into address 0, skip first 12 bytes, copy 1 bytes
    "0x01 0x15 0x00 CODECOPY " + // (5b) offset 0, size 0x01, now return the first code
    "0x01 0x00  RETURN " + // (1b) REAL code to install
    "STOP ";
    EVMAssembler assembler = new EVMAssembler();
    byte[] code = assembler.assemble(asm);
    // Creates a contract
    Transaction tx1 = createTx(blockchain, sender, new byte[0], code);
    TransactionExecutor executor1 = executeTransaction(blockchain, tx1);
    // Now we can directly check the store and see the new code.
    Assert.assertTrue(executor1.getResult().getException() != null);
}
Also used : Transaction(org.ethereum.core.Transaction) BlockChainImpl(co.rsk.core.bc.BlockChainImpl) BigInteger(java.math.BigInteger) ECKey(org.ethereum.crypto.ECKey) TransactionExecutor(org.ethereum.core.TransactionExecutor) EVMAssembler(co.rsk.asm.EVMAssembler) Test(org.junit.Test)

Example 64 with ECKey

use of org.ethereum.crypto.ECKey in project rskj by rsksmart.

the class TransactionTest method dontLogWhenReverting.

@Test
public void dontLogWhenReverting() throws IOException, InterruptedException {
    /*

        Original contracts

        pragma solidity ^0.4.0;
        contract TestEventInvoked {
            event internalEvent();

            function doIt() {
                internalEvent();
                throw;
            }
        }

        contract TestEventInvoker {
            event externalEvent();

            function doIt(address invokedAddress) {
                externalEvent();
                invokedAddress.call.gas(50000)(0xb29f0835);
            }
        }

         */
    BigInteger nonce = config.getBlockchainConfig().getCommonConstants().getInitialNonce();
    Blockchain blockchain = ImportLightTest.createBlockchain(GenesisLoader.loadGenesis(config, nonce, getClass().getResourceAsStream("/genesis/genesis-light.json"), false));
    ECKey sender = ECKey.fromPrivate(Hex.decode("3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c"));
    System.out.println("address: " + Hex.toHexString(sender.getAddress()));
    // First contract code TestEventInvoked
    String code1 = "6060604052341561000f57600080fd5b5b60ae8061001e6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063b29f083514603d575b600080fd5b3415604757600080fd5b604d604f565b005b7f95481a538d62f8458d3cecac82408d5ff2630d8335962b1cdbac16f1a9b910e760405160405180910390a1600080fd5b5600a165627a7a723058207d93861daff7f4a0479d7f3eb0ca7ef5cef7e2bbf2c4637ab4f021ecc5afa7ad0029";
    // Second contract code TestEventInvoker
    String code2 = "6060604052341561000f57600080fd5b5b6101358061001f6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063e25fd8a71461003e575b600080fd5b341561004957600080fd5b610075600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610077565b005b7f4cd6f2e769273405c20f3a0c098c9045749deec145502c4838b54206ec5c542860405160405180910390a18073ffffffffffffffffffffffffffffffffffffffff1661c35063b29f0835906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040160006040518083038160008887f19350505050505b505600a165627a7a7230582019096fd773ebc5581ba378acd64cb1acb450b4eb4866d710f3e3f4e33d635a4b0029";
    // Second contract ABI
    String abi2 = "[{\"constant\":false,\"inputs\":[{\"name\":\"invokedAddress\",\"type\":\"address\"}],\"name\":\"doIt\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"externalEvent\",\"type\":\"event\"}]";
    Transaction tx1 = createTx(blockchain, sender, new byte[0], Hex.decode(code1));
    executeTransaction(blockchain, tx1);
    Transaction tx2 = createTx(blockchain, sender, new byte[0], Hex.decode(code2));
    executeTransaction(blockchain, tx2);
    CallTransaction.Contract contract2 = new CallTransaction.Contract(abi2);
    byte[] data = contract2.getByName("doIt").encode(Hex.toHexString(tx1.getContractAddress().getBytes()));
    Transaction tx3 = createTx(blockchain, sender, tx2.getContractAddress().getBytes(), data);
    TransactionExecutor executor = executeTransaction(blockchain, tx3);
    Assert.assertEquals(1, executor.getResult().getLogInfoList().size());
    Assert.assertEquals(false, executor.getResult().getLogInfoList().get(0).isRejected());
    Assert.assertEquals(1, executor.getVMLogs().size());
}
Also used : BigInteger(java.math.BigInteger) ECKey(org.ethereum.crypto.ECKey) Test(org.junit.Test)

Example 65 with ECKey

use of org.ethereum.crypto.ECKey in project rskj by rsksmart.

the class TransactionTest method test2.

@Ignore
@Test
public /* achieve public key of the sender */
void test2() throws Exception {
    // cat --> 79b08ad8787060333663d19704909ee7b1903e58
    // cow --> cd2a3d9f938e13cd947ec05abc7fe734df8dd826
    BigInteger value = new BigInteger("1000000000000000000000");
    byte[] privKey = HashUtil.keccak256("cat".getBytes());
    ECKey ecKey = ECKey.fromPrivate(privKey);
    byte[] senderPrivKey = HashUtil.keccak256("cow".getBytes());
    byte[] gasPrice = Hex.decode("09184e72a000");
    byte[] gas = Hex.decode("4255");
    // Tn (nonce); Tp(pgas); Tg(gaslimi); Tt(value); Tv(value); Ti(sender);  Tw; Tr; Ts
    Transaction tx = new Transaction(null, gasPrice, gas, ecKey.getAddress(), value.toByteArray(), null);
    tx.sign(senderPrivKey);
    System.out.println("v\t\t\t: " + Hex.toHexString(new byte[] { tx.getSignature().v }));
    System.out.println("r\t\t\t: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(tx.getSignature().r)));
    System.out.println("s\t\t\t: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(tx.getSignature().s)));
    System.out.println("RLP encoded tx\t\t: " + Hex.toHexString(tx.getEncoded()));
    // retrieve the signer/sender of the transaction
    ECKey key = ECKey.signatureToKey(tx.getHash().getBytes(), tx.getSignature().toBase64());
    System.out.println("Tx unsigned RLP\t\t: " + Hex.toHexString(tx.getEncodedRaw()));
    System.out.println("Tx signed   RLP\t\t: " + Hex.toHexString(tx.getEncoded()));
    System.out.println("Signature public key\t: " + Hex.toHexString(key.getPubKey()));
    System.out.println("Sender is\t\t: " + Hex.toHexString(key.getAddress()));
    assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826", Hex.toHexString(key.getAddress()));
    System.out.println(tx.toString());
}
Also used : BigInteger(java.math.BigInteger) ECKey(org.ethereum.crypto.ECKey) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

ECKey (org.ethereum.crypto.ECKey)76 Test (org.junit.Test)43 BigInteger (java.math.BigInteger)17 NodeDistanceTable (co.rsk.net.discovery.table.NodeDistanceTable)10 ArrayList (java.util.ArrayList)10 Node (org.ethereum.net.rlpx.Node)10 InetSocketAddress (java.net.InetSocketAddress)9 Transaction (org.ethereum.core.Transaction)8 BlockGenerator (co.rsk.blockchain.utils.BlockGenerator)7 RepositoryImpl (co.rsk.db.RepositoryImpl)7 SimpleRskTransaction (co.rsk.peg.simples.SimpleRskTransaction)7 Channel (io.netty.channel.Channel)7 org.ethereum.core (org.ethereum.core)7 co.rsk.bitcoinj.core (co.rsk.bitcoinj.core)6 BridgeEventLogger (co.rsk.peg.utils.BridgeEventLogger)6 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 BlockChainBuilder (co.rsk.test.builders.BlockChainBuilder)4 Account (org.ethereum.core.Account)4 RskAddress (co.rsk.core.RskAddress)3