Search in sources :

Example 51 with Keccak256

use of co.rsk.crypto.Keccak256 in project rskj by rsksmart.

the class Tx method create.

public static Transaction create(RskSystemProperties config, long value, long gaslimit, long gasprice, long nonce, long data, long sender) {
    Random r = new Random(sender);
    Transaction transaction = Mockito.mock(Transaction.class);
    Mockito.when(transaction.getValue()).thenReturn(new Coin(BigInteger.valueOf(value)));
    Mockito.when(transaction.getGasLimit()).thenReturn(BigInteger.valueOf(gaslimit).toByteArray());
    Mockito.when(transaction.getGasLimitAsInteger()).thenReturn(BigInteger.valueOf(gaslimit));
    Mockito.when(transaction.getGasPrice()).thenReturn(Coin.valueOf(gasprice));
    Mockito.when(transaction.getNonce()).thenReturn(BigInteger.valueOf(nonce).toByteArray());
    Mockito.when(transaction.getNonceAsInteger()).thenReturn(BigInteger.valueOf(nonce));
    byte[] returnSenderBytes = new byte[20];
    r.nextBytes(returnSenderBytes);
    RskAddress returnSender = new RskAddress(returnSenderBytes);
    byte[] returnReceiveAddressBytes = new byte[20];
    r.nextBytes(returnReceiveAddressBytes);
    RskAddress returnReceiveAddress = new RskAddress(returnReceiveAddressBytes);
    Mockito.when(transaction.getSender()).thenReturn(returnSender);
    Mockito.when(transaction.getHash()).thenReturn(new Keccak256(TestUtils.randomBytes(32)));
    Mockito.when(transaction.acceptTransactionSignature(config.getBlockchainConfig().getCommonConstants().getChainId())).thenReturn(Boolean.TRUE);
    Mockito.when(transaction.getReceiveAddress()).thenReturn(returnReceiveAddress);
    ArrayList<Byte> bytes = new ArrayList();
    long amount = 21000;
    if (data != 0) {
        data /= 2;
        for (int i = 0; i < data / 4; i++) {
            bytes.add((byte) 0);
            amount += 4;
        }
        for (int i = 0; i < data / 68; i++) {
            bytes.add((byte) 1);
            amount += 68;
        }
    }
    int n = bytes.size();
    byte[] b = new byte[n];
    for (int i = 0; i < n; i++) {
        b[i] = bytes.get(i);
    }
    Mockito.when(transaction.getData()).thenReturn(b);
    Mockito.when(transaction.transactionCost(eq(config), any(Block.class))).thenReturn(amount);
    return transaction;
}
Also used : Coin(co.rsk.core.Coin) Random(java.util.Random) Transaction(org.ethereum.core.Transaction) RskAddress(co.rsk.core.RskAddress) ArrayList(java.util.ArrayList) Block(org.ethereum.core.Block) Keccak256(co.rsk.crypto.Keccak256)

Example 52 with Keccak256

use of co.rsk.crypto.Keccak256 in project rskj by rsksmart.

the class BridgeSupport method executeVoteFederationChangeFunction.

private ABICallVoteResult executeVoteFederationChangeFunction(boolean dryRun, ABICallSpec callSpec) throws IOException {
    // Try to do a dry-run and only register the vote if the
    // call would be successful
    ABICallVoteResult result;
    Integer executionResult;
    switch(callSpec.getFunction()) {
        case "create":
            executionResult = createFederation(dryRun);
            result = new ABICallVoteResult(executionResult == 1, executionResult);
            break;
        case "add":
            byte[] publicKeyBytes = (byte[]) callSpec.getArguments()[0];
            BtcECKey publicKey;
            try {
                publicKey = BtcECKey.fromPublicOnly(publicKeyBytes);
            } catch (Exception e) {
                throw new BridgeIllegalArgumentException("Public key could not be parsed " + Hex.toHexString(publicKeyBytes), e);
            }
            executionResult = addFederatorPublicKey(dryRun, publicKey);
            result = new ABICallVoteResult(executionResult == 1, executionResult);
            break;
        case "commit":
            Keccak256 hash = new Keccak256((byte[]) callSpec.getArguments()[0]);
            executionResult = commitFederation(dryRun, hash);
            result = new ABICallVoteResult(executionResult == 1, executionResult);
            break;
        case "rollback":
            executionResult = rollbackFederation(dryRun);
            result = new ABICallVoteResult(executionResult == 1, executionResult);
            break;
        default:
            // Fail by default
            result = new ABICallVoteResult(false, FEDERATION_CHANGE_GENERIC_ERROR_CODE);
    }
    return result;
}
Also used : BigInteger(java.math.BigInteger) Keccak256(co.rsk.crypto.Keccak256) IOException(java.io.IOException) BlockStoreException(co.rsk.bitcoinj.store.BlockStoreException)

Example 53 with Keccak256

use of co.rsk.crypto.Keccak256 in project rskj by rsksmart.

the class TrieImpl method getHash.

/**
 * getHash calculates and/or returns the hash associated with this node content
 *
 * the internal variable hash could contains the cached hash.
 *
 * This method is not synchronized because the result of it's execution
 *
 * disregarding the lazy initialization is idempotent. It's better to keep
 *
 * it out of synchronized.
 *
 * @return  a byte array with the node serialized to bytes
 */
@Override
public Keccak256 getHash() {
    if (this.hash != null) {
        return this.hash.copy();
    }
    if (isEmptyTrie(this.value, this.nodes, this.hashes)) {
        return emptyHash.copy();
    }
    byte[] message = this.toMessage();
    this.hash = new Keccak256(Keccak256Helper.keccak256(message));
    return this.hash.copy();
}
Also used : Keccak256(co.rsk.crypto.Keccak256)

Example 54 with Keccak256

use of co.rsk.crypto.Keccak256 in project rskj by rsksmart.

the class TrieImpl method toMessage.

/**
 * toMessage serialize the node to bytes. Used to persist the node in a key-value store
 * like levelDB or redis.
 *
 * The serialization includes:
 * - arity: byte
 * - bits with present hashes: two bytes (example: 0x0203 says that the node has
 * hashes at index 0, 1, 9 (the other subnodes are null)
 * - present hashes: 32 bytes each
 * - associated value: remainder bytes (no bytes if null)
 *
 * @return a byte array with the serialized info
 */
@Override
public byte[] toMessage() {
    int lvalue = this.value == null ? 0 : this.value.length;
    int nnodes = this.getNodeCount();
    int lshared = this.sharedPathLength;
    int lencoded = getEncodedPathLength(lshared);
    boolean hasLongVal = this.hasLongValue();
    int bits = 0;
    for (int k = 0; k < ARITY; k++) {
        Keccak256 nodeHash = this.getHash(k);
        if (nodeHash == null) {
            continue;
        }
        bits |= 1 << k;
    }
    ByteBuffer buffer = ByteBuffer.allocate(MESSAGE_HEADER_LENGTH + lencoded + nnodes * Keccak256Helper.DEFAULT_SIZE_BYTES + (hasLongVal ? Keccak256Helper.DEFAULT_SIZE_BYTES : lvalue));
    buffer.put((byte) ARITY);
    byte flags = 0;
    if (this.isSecure) {
        flags |= 1;
    }
    if (hasLongVal) {
        flags |= 2;
    }
    buffer.put(flags);
    buffer.putShort((short) bits);
    buffer.putShort((short) lshared);
    if (lshared > 0) {
        buffer.put(encodedSharedPath);
    }
    for (int k = 0; k < ARITY; k++) {
        Keccak256 nodeHash = this.getHash(k);
        if (nodeHash == null) {
            continue;
        }
        buffer.put(nodeHash.getBytes());
    }
    if (lvalue > 0) {
        if (hasLongVal) {
            buffer.put(this.getValueHash());
        } else {
            buffer.put(this.value);
        }
    }
    return buffer.array();
}
Also used : Keccak256(co.rsk.crypto.Keccak256) ByteBuffer(java.nio.ByteBuffer)

Example 55 with Keccak256

use of co.rsk.crypto.Keccak256 in project rskj by rsksmart.

the class TrieImpl method fromMessage.

private static TrieImpl fromMessage(byte[] message, int position, int msglength, TrieStore store) {
    if (message == null) {
        return null;
    }
    ByteArrayInputStream bstream = new ByteArrayInputStream(message, position, msglength);
    DataInputStream istream = new DataInputStream(bstream);
    try {
        int arity = istream.readByte();
        if (arity != ARITY) {
            throw new IllegalArgumentException(INVALID_ARITY);
        }
        int flags = istream.readByte();
        boolean isSecure = (flags & 0x01) == 1;
        boolean hasLongVal = (flags & 0x02) == 2;
        int bhashes = istream.readShort();
        int lshared = istream.readShort();
        int nhashes = 0;
        int lencoded = TrieImpl.getEncodedPathLength(lshared);
        byte[] encodedSharedPath = null;
        if (lencoded > 0) {
            encodedSharedPath = new byte[lencoded];
            if (istream.read(encodedSharedPath) != lencoded) {
                throw new EOFException();
            }
        }
        Keccak256[] hashes = new Keccak256[arity];
        for (int k = 0; k < arity; k++) {
            if ((bhashes & (1 << k)) == 0) {
                continue;
            }
            byte[] valueHash = new byte[Keccak256Helper.DEFAULT_SIZE_BYTES];
            if (istream.read(valueHash) != Keccak256Helper.DEFAULT_SIZE_BYTES) {
                throw new EOFException();
            }
            hashes[k] = new Keccak256(valueHash);
            nhashes++;
        }
        int offset = MESSAGE_HEADER_LENGTH + lencoded + nhashes * Keccak256Helper.DEFAULT_SIZE_BYTES;
        byte[] value = null;
        if (hasLongVal) {
            byte[] valueHash = new byte[Keccak256Helper.DEFAULT_SIZE_BYTES];
            if (istream.read(valueHash) != Keccak256Helper.DEFAULT_SIZE_BYTES) {
                throw new EOFException();
            }
            value = store.retrieveValue(valueHash);
        } else {
            int lvalue = msglength - offset;
            if (lvalue > 0) {
                value = new byte[lvalue];
                if (istream.read(value) != lvalue) {
                    throw new EOFException();
                }
            }
        }
        TrieImpl trie = new TrieImpl(encodedSharedPath, lshared, value, null, hashes, store).withSecure(isSecure);
        if (store != null) {
            trie.saved = true;
        }
        return trie;
    } catch (IOException ex) {
        logger.error(ERROR_CREATING_TRIE, ex);
        panicProcessor.panic(PANIC_TOPIC, ERROR_CREATING_TRIE + ": " + ex.getMessage());
        throw new TrieSerializationException(ERROR_CREATING_TRIE, ex);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) EOFException(java.io.EOFException) Keccak256(co.rsk.crypto.Keccak256) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream)

Aggregations

Keccak256 (co.rsk.crypto.Keccak256)102 Test (org.junit.Test)53 Block (org.ethereum.core.Block)40 BlockGenerator (co.rsk.blockchain.utils.BlockGenerator)15 BigInteger (java.math.BigInteger)14 RskSystemProperties (co.rsk.config.RskSystemProperties)8 SimpleMessageChannel (co.rsk.net.simples.SimpleMessageChannel)8 SyncConfiguration (co.rsk.net.sync.SyncConfiguration)8 HashMapDB (org.ethereum.datasource.HashMapDB)8 RepositoryImpl (co.rsk.db.RepositoryImpl)7 ArrayList (java.util.ArrayList)7 Blockchain (org.ethereum.core.Blockchain)7 BlockStore (org.ethereum.db.BlockStore)7 IndexedBlockStore (org.ethereum.db.IndexedBlockStore)7 RLPList (org.ethereum.util.RLPList)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Script (co.rsk.bitcoinj.script.Script)5 Coin (co.rsk.core.Coin)5 IOException (java.io.IOException)5 BlockHeader (org.ethereum.core.BlockHeader)5