Java Code Examples for org.ethereum.crypto.HashUtil#sha3()

The following examples show how to use org.ethereum.crypto.HashUtil#sha3() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TransactionTest.java    From ethereumj with MIT License 6 votes vote down vote up
@Test /* sign transaction  https://tools.ietf.org/html/rfc6979 */
public void test1() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, IOException {

    //python taken exact data
    String txRLPRawData = "a9e880872386f26fc1000085e8d4a510008203e89413978aee95f38490e9769c39b2773ed763d9cd5f80";
    // String txRLPRawData = "f82804881bc16d674ec8000094cd2a3d9f938e13cd947ec05abc7fe734df8dd8268609184e72a0006480";

    byte[] cowPrivKey = Hex.decode("c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4");
    ECKey key = ECKey.fromPrivate(cowPrivKey);

    byte[] data    = Hex.decode(txRLPRawData);

    // step 1: serialize + RLP encode
    // step 2: hash = sha3(step1)
    byte[] txHash = HashUtil.sha3(data);

    String signature = key.doSign(txHash).toBase64();
    System.out.println(signature);
}
 
Example 2
Source File: RLPTest.java    From ethereumj with MIT License 6 votes vote down vote up
@Test /** found bug encode list affects element value,
           hhh... not really at  the end but keep the test */
 public void test10() {

/* 2 */    byte[] prevHash =
             {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
           prevHash = RLP.encodeElement(prevHash);

/* 2 */    byte[] uncleList = HashUtil.sha3(RLP.encodeList(new byte[]{}));

/* 3 */    byte[] coinbase =
             {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
              0x00, 0x00, 0x00, 0x00};
           coinbase = RLP.encodeElement(coinbase);

     byte[] header = RLP.encodeList(
             prevHash, uncleList, coinbase);

     assertEquals("f856a000000000000000000000000000000000000000000000000000000000000000001dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000",
             Hex.toHexString(header));
 }
 
Example 3
Source File: CommonConfig.java    From nuls-v2 with MIT License 5 votes vote down vote up
public Source<byte[], byte[]> trieNodeSource() {
    if (trieNodeSource == null) {
        DbSource<byte[]> db = blockchainDB();
        Source<byte[], byte[]> src = new PrefixLookupSource<>(db, NodeKeyCompositor.PREFIX_BYTES);
        trieNodeSource = new XorDataSource<>(src, HashUtil.sha3("state".getBytes()));
    }
    return trieNodeSource;
}
 
Example 4
Source File: Cache.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * Put the node in the cache if RLP encoded value is longer than 32 bytes
 * 
 * @param o the Node which could be a pair-, multi-item Node or single Value  
 * @return sha3 hash of RLP encoded node if length &gt; 32 otherwise return node itself
 */
public Object put(Object o) {
	Value value = new Value(o);
	byte[] enc = value.encode();
	if (enc.length >= 32) {
		byte[] sha = HashUtil.sha3(enc);
		this.nodes.put(new ByteArrayWrapper(sha), new Node(value, true));
		this.isDirty = true;
		return sha;
	}
	return value;
}
 
Example 5
Source File: TrieImpl.java    From ethereumj with MIT License 5 votes vote down vote up
@Override
public byte[] getRootHash() {
    if (root == null
            || (root instanceof byte[] && ((byte[]) root).length == 0)
            || (root instanceof String && "".equals((String) root))) {
        return ByteUtil.EMPTY_BYTE_ARRAY;
    } else if (root instanceof byte[]) {
        return (byte[]) this.getRoot();
    } else {
        Value rootValue = new Value(this.getRoot());
        byte[] val = rootValue.encode();
        return HashUtil.sha3(val);
    }
}
 
Example 6
Source File: WorldManager.java    From ethereumj with MIT License 5 votes vote down vote up
public void init() {
	this.wallet = new Wallet();
    byte[] cowAddr = HashUtil.sha3("cow".getBytes());
    wallet.importKey(cowAddr);

    String secret = CONFIG.coinbaseSecret();
    byte[] cbAddr = HashUtil.sha3(secret.getBytes());
    wallet.importKey(cbAddr);
}
 
Example 7
Source File: TransactionTest.java    From ethereumj with MIT License 5 votes vote down vote up
@Test  /* achieve public key of the sender nonce: 01 */
  public void test3() throws Exception {

      // cat --> 79b08ad8787060333663d19704909ee7b1903e58
      // cow --> cd2a3d9f938e13cd947ec05abc7fe734df8dd826

ECKey ecKey = ECKey.fromPrivate(HashUtil.sha3("cat".getBytes()));
      byte[] senderPrivKey = HashUtil.sha3("cow".getBytes());
      
byte[] nonce = { 0x01 };
byte[] gasPrice = Hex.decode("09184e72a000");
byte[] gasLimit = Hex.decode("4255");
      BigInteger value = new BigInteger("1000000000000000000000000");

Transaction tx = new Transaction(nonce, gasPrice, gasLimit,
		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(), 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()));

      Assert.assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826",
              Hex.toHexString(key.getAddress()));
  }
 
Example 8
Source File: BlockHeader.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * Verify that block is valid for its difficulty
 * 
 * @return boolean
 */
public boolean validateNonce() {
	BigInteger max = BigInteger.valueOf(2).pow(256);
	byte[] target = BigIntegers.asUnsignedByteArray(32,
			max.divide(new BigInteger(1, this.getDifficulty())));
	byte[] hash = HashUtil.sha3(this.getEncodedWithoutNonce());
	byte[] concat = Arrays.concatenate(hash, this.getNonce());
	byte[] result = HashUtil.sha3(concat);
	return FastByteComparisons.compareTo(result, 0, 32, target, 0, 32) < 0;
}
 
Example 9
Source File: RepositoryImpl.java    From nuls with MIT License 5 votes vote down vote up
@Override
public synchronized void saveCode(byte[] addr, byte[] code) {
    byte[] codeHash = HashUtil.sha3(code);
    codeCache.put(codeKey(codeHash, addr), code);
    AccountState accountState = getOrCreateAccountState(addr);
    accountStateCache.put(addr, accountState.withCodeHash(codeHash));
}
 
Example 10
Source File: TransactionTest.java    From ethereumj with MIT License 5 votes vote down vote up
@Test
    public void testTransactionCreateContract() {

//        String rlp = "f89f808609184e72a0008203e8808203e8b84b4560005444602054600f60056002600a02010b0d630000001d596002602054630000003b5860066000530860056006600202010a0d6300000036596004604054630000003b5860056060541ca0ddc901d83110ea50bc40803f42083afea1bbd420548f6392a679af8e24b21345a06620b3b512bea5f0a272703e8d6933177c23afc79516fd0ca4a204aa6e34c7e9";

        byte[] senderPrivKey = HashUtil.sha3("cow".getBytes());

        byte[] nonce			= BigIntegers.asUnsignedByteArray(BigInteger.ZERO);
        byte[] gasPrice			= Hex.decode("09184e72a000");		// 10000000000000
        byte[] gas				= Hex.decode("03e8");			// 1000
        byte[] recieveAddress	= null;
        byte[] endowment     	= Hex.decode("03e8"); //10000000000000000"
        byte[] init 			= Hex.decode("4560005444602054600f60056002600a02010b0d630000001d596002602054630000003b5860066000530860056006600202010a0d6300000036596004604054630000003b586005606054");


        Transaction tx1 = new Transaction(nonce, gasPrice, gas,
                recieveAddress, endowment, init);
        tx1.sign(senderPrivKey);

        byte[] payload = tx1.getEncoded();


        System.out.println(Hex.toHexString(payload));
        Transaction tx2 = new Transaction(payload);
//        tx2.getSender();

        String plainTx1 = Hex.toHexString(tx1.getEncodedRaw());
        String plainTx2 = Hex.toHexString(tx2.getEncodedRaw());

//        Transaction tx = new Transaction(Hex.decode(rlp));

        System.out.println("tx1.hash: " + Hex.toHexString(tx1.getHash()));
        System.out.println("tx2.hash: " + Hex.toHexString(tx2.getHash()));
        System.out.println();
        System.out.println("plainTx1: " + plainTx1 );
        System.out.println("plainTx2: " + plainTx2 );

        System.out.println( Hex.toHexString(tx2.getSender()));
    }
 
Example 11
Source File: BlockStoreDummy.java    From nuls with MIT License 4 votes vote down vote up
@Override
public byte[] getBlockHashByNumber(long blockNumber) {

    byte[] data = String.valueOf(blockNumber).getBytes();
    return HashUtil.sha3(data);
}
 
Example 12
Source File: TransactionsMessageTest.java    From ethereumj with MIT License 4 votes vote down vote up
@Test /* Transactions msg encode */
public void test_3() throws Exception {

    String expected = "f87302f870808b00d3c21bcecceda10000009479b08ad8787060333663d19704909ee7b1903e588609184e72a000824255801ca00f410a70e42b2c9854a8421d32c87c370a2b9fff0a27f9f031bb4443681d73b5a018a7dc4c4f9dee9f3dc35cb96ca15859aa27e219a8e4a8547be6bd3206979858";

    BigInteger value = new BigInteger("1000000000000000000000000");

    byte[] privKey = HashUtil.sha3("cat".getBytes());
    ECKey ecKey = ECKey.fromPrivate(privKey);

    byte[] gasPrice=  Hex.decode("09184e72a000");
    byte[] gas =      Hex.decode("4255");

    Transaction tx = new Transaction(null, value.toByteArray(),
            ecKey.getAddress(),  gasPrice, gas, null);

    tx.sign(privKey);
    tx.getEncoded();

    Set<Transaction> txs = new HashSet<>(Arrays.asList(tx));
    TransactionsMessage transactionsMessage = new TransactionsMessage(txs);

    assertEquals(EthMessageCodes.TRANSACTIONS, transactionsMessage.getCommand());
    assertEquals(expected, Hex.toHexString(transactionsMessage.getEncoded()));
}
 
Example 13
Source File: CommonConfig.java    From nuls with MIT License 4 votes vote down vote up
public Source<byte[], byte[]> blockchainSource(String name) {
    return new XorDataSource<>(blockchainDbCache(), HashUtil.sha3(name.getBytes()));
}
 
Example 14
Source File: VMComplexTest.java    From ethereumj with MIT License 4 votes vote down vote up
@Test // contract call recursive
  public void test1() {

/**
 *       #The code will run
 *       ------------------

         a = contract.storage[999]
         if a > 0:
             contract.storage[999] = a - 1

             # call to contract: 77045e71a7a2c50903d88e564cd72fab11e82051
             send((tx.gas / 10 * 8), 0x77045e71a7a2c50903d88e564cd72fab11e82051, 0)
         else:
             stop
 */

      int expectedGas = 438;

      DataWord key1 = new DataWord(999);
      DataWord value1 = new DataWord(3);

      // Set contract into Database
      String callerAddr   = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826";
      String contractAddr = "77045e71a7a2c50903d88e564cd72fab11e82051";
      String code         = "6103e75660005460006000530b0f630000004c596001600053036103e757600060006000600060007377045e71a7a2c50903d88e564cd72fab11e820516008600a5c0402f1630000004c585d00";

      byte[] contractAddrB = Hex.decode(contractAddr);
      byte[] callerAddrB = Hex.decode(callerAddr);
      byte[] codeB = Hex.decode(code);

      byte[] codeKey = HashUtil.sha3(codeB);
      AccountState accountState = new AccountState();
      accountState.setCodeHash(codeKey);

      ProgramInvokeMockImpl pi =  new ProgramInvokeMockImpl();
      pi.setOwnerAddress(contractAddrB);
      Repository repository = pi.getRepository();

      repository.createAccount(callerAddrB);
      repository.addBalance(callerAddrB, new BigInteger("100000000000000000000"));

      repository.createAccount(contractAddrB);
      repository.saveCode(contractAddrB, codeB);
      repository.addStorageRow(contractAddrB, key1, value1);

      // Play the program
      VM vm = new VM();
      Program program = new Program(codeB, pi);

      try {
          while(!program.isStopped())
              vm.step(program);
      } catch (RuntimeException e) {
          program.setRuntimeFailure(e);
      }

      System.out.println();
      System.out.println("============ Results ============");

      BigInteger balance = repository.getBalance(callerAddrB);

      System.out.println("*** Used gas: " + program.result.getGasUsed());
      System.out.println("*** Contract Balance: " + balance);

      // todo: assert caller balance after contract exec

      repository.close();
      assertEquals(expectedGas, program.result.getGasUsed());
  }
 
Example 15
Source File: CommonWallet.java    From wkcwallet-java with Apache License 2.0 4 votes vote down vote up
@Override
public String toV3(String password, int n, int p, int r) {

    // derived key
    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[64];
    random.nextBytes(salt);
    int dkLen = 32;
    byte[] derivedkey = SCrypt.generate(password.getBytes(), salt, n, r, p, dkLen);
    byte[] dk = Arrays.copyOf(derivedkey, 16);
    byte[] vk = Arrays.copyOfRange(derivedkey, 16, 32);

    // Encrypt
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CTR/NoPadding");
        SecretKey aesKey = new SecretKeySpec(dk, "AES");
        byte[] iv = new byte[16];
        random.nextBytes(iv);
        IvParameterSpec iv_spec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, aesKey, iv_spec);
        byte[] ciphertext = cipher.doFinal(getPrivateKey());

        // Calc MAC
        byte[] mac = HashUtil.sha3(Arrays.concatenate(vk, ciphertext));

        // Output
        StringBuilder sb = new StringBuilder();
        sb.append("{\"address\":\"").append(getAddressString()).append('"');
        sb.append(",\"crypto\":{\"cipher\":\"aes-128-ctr\"");
        sb.append(",\"ciphertext\":\"").append(Hex.toHexString(ciphertext)).append('"');
        sb.append(",\"cipherparams\":{");
        sb.append("\"iv\":\"").append(Hex.toHexString(iv)).append('"');
        sb.append("}");
        sb.append(",\"kdf\":\"").append("scrypt").append('"');
        sb.append(",\"kdfparams\":{");
        sb.append("\"dklen\":").append(dkLen);
        sb.append(",\"n\":").append(n);
        sb.append(",\"r\":").append(r);
        sb.append(",\"p\":").append(p);
        sb.append(",\"salt\":\"").append(Hex.toHexString(salt)).append('"');
        sb.append('}');
        sb.append(",\"mac\":\"").append(Hex.toHexString(mac)).append('"');
        sb.append('}');
        sb.append(",\"id\":\"").append(UUID.randomUUID()).append('"');
        sb.append(",\"version\":3}");
        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeCryptoException();
    }

}
 
Example 16
Source File: Value.java    From wkcwallet-java with Apache License 2.0 4 votes vote down vote up
public byte[] hash(){
    if (sha3 == null)
        sha3 = HashUtil.sha3(encode());
    return sha3;
}
 
Example 17
Source File: Value.java    From nuls-v2 with MIT License 4 votes vote down vote up
public byte[] hash() {
    if (sha3 == null) {
        sha3 = HashUtil.sha3(encode());
    }
    return sha3;
}
 
Example 18
Source File: CommonConfig.java    From nuls-v2 with MIT License 4 votes vote down vote up
public Source<byte[], byte[]> blockchainSource(String name) {
    return new XorDataSource<>(blockchainDbCache(), HashUtil.sha3(name.getBytes()));
}
 
Example 19
Source File: BlockStoreDummy.java    From nuls-v2 with MIT License 4 votes vote down vote up
@Override
public byte[] getBlockHashByNumber(long blockNumber) {

    byte[] data = String.valueOf(blockNumber).getBytes();
    return HashUtil.sha3(data);
}
 
Example 20
Source File: TransactionTest.java    From ethereumj with MIT License 2 votes vote down vote up
@Test  /* achieve public key of the sender */
public void test2() throws Exception {

    // cat --> 79b08ad8787060333663d19704909ee7b1903e58
    // cow --> cd2a3d9f938e13cd947ec05abc7fe734df8dd826

    BigInteger value = new BigInteger("1000000000000000000000");

    byte[] privKey = HashUtil.sha3("cat".getBytes());
    ECKey ecKey = ECKey.fromPrivate(privKey);

    byte[] senderPrivKey = HashUtil.sha3("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(), 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()));

    Assert.assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826",
            Hex.toHexString(key.getAddress()));

    System.out.println(tx.toString());
}