org.spongycastle.util.BigIntegers Java Examples

The following examples show how to use org.spongycastle.util.BigIntegers. 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
public void testTransactionFromNew1() throws MissingPrivateKeyException {
   	Transaction txNew = new Transaction(testNonce, testGasPrice, testGasLimit, testReceiveAddress, testValue, testData);
   	
   	assertEquals("", Hex.toHexString(txNew.getNonce()));
   	assertEquals(new BigInteger(1, testGasPrice), new BigInteger(1, txNew.getGasPrice()));
   	assertEquals(new BigInteger(1, testGasLimit), new BigInteger(1, txNew.getGasLimit()));
   	assertEquals(Hex.toHexString(testReceiveAddress), Hex.toHexString(txNew.getReceiveAddress()));
   	assertEquals(new BigInteger(1, testValue), new BigInteger(1, txNew.getValue()));
   	assertEquals("", Hex.toHexString(txNew.getData()));
   	assertNull(txNew.getSignature());
   	
   	assertEquals(RLP_ENCODED_RAW_TX, Hex.toHexString(txNew.getEncodedRaw()));
   	assertEquals(HASH_TX, Hex.toHexString(txNew.getHash()));
   	assertEquals(RLP_ENCODED_UNSIGNED_TX, Hex.toHexString(txNew.getEncoded()));
   	txNew.sign(Hex.decode(KEY));
   	assertEquals(RLP_ENCODED_SIGNED_TX, Hex.toHexString(txNew.getEncoded()));   	
   	
   	assertEquals(27, txNew.getSignature().v);
   	assertEquals("eab47c1a49bf2fe5d40e01d313900e19ca485867d462fe06e139e3a536c6d4f4", Hex.toHexString(BigIntegers.asUnsignedByteArray(txNew.getSignature().r)));
   	assertEquals("14a569d327dcda4b29f74f93c0e9729d2f49ad726e703f9cd90dbb0fbf6649f1", Hex.toHexString(BigIntegers.asUnsignedByteArray(txNew.getSignature().s)));
}
 
Example #2
Source File: Transaction.java    From wkcwallet-java with Apache License 2.0 6 votes vote down vote up
public String toString(int maxDataSize) {
    if(!this.parsed) {
        this.rlpParse();
    }

    String dataS;
    if(this.data == null) {
        dataS = "";
    } else if(this.data.length < maxDataSize) {
        dataS = ByteUtil.toHexString(this.data);
    } else {
        dataS = ByteUtil.toHexString(Arrays.copyOfRange(this.data, 0, maxDataSize)) + "... (" + this.data.length + " bytes)";
    }

    return "TransactionData [hash=" + ByteUtil.toHexString(this.hash) + "  nonce=" + ByteUtil.toHexString(this.nonce) + ", gasPrice=" + ByteUtil.toHexString(this.gasPrice) + ", gas=" + ByteUtil.toHexString(this.gasLimit) + ", receiveAddress=" + ByteUtil.toHexString(this.receiveAddress) + ", value=" + ByteUtil.toHexString(this.value) + ", data=" + dataS + ", signatureV=" + (this.signature == null?"":Byte.valueOf(this.signature.v)) + ", signatureR=" + (this.signature == null?"":ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(this.signature.r))) + ", signatureS=" + (this.signature == null?"":ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(this.signature.s))) + "]";
}
 
Example #3
Source File: TransactionTest.java    From ethereumj with MIT License 6 votes vote down vote up
@Test
public void testTransactionFromSignedRLP() throws Exception {
   	Transaction txSigned = new Transaction(Hex.decode(RLP_ENCODED_SIGNED_TX));
   	
   	assertEquals(HASH_TX, Hex.toHexString(txSigned.getHash()));
   	assertEquals(RLP_ENCODED_SIGNED_TX, Hex.toHexString(txSigned.getEncoded()));
   	
   	assertEquals(BigInteger.ZERO, new BigInteger(1, txSigned.getNonce()));
   	assertEquals(new BigInteger(1, testGasPrice), new BigInteger(1, txSigned.getGasPrice()));
   	assertEquals(new BigInteger(1, testGasLimit), new BigInteger(1, txSigned.getGasLimit()));
   	assertEquals(Hex.toHexString(testReceiveAddress), Hex.toHexString(txSigned.getReceiveAddress()));
   	assertEquals(new BigInteger(1, testValue), new BigInteger(1, txSigned.getValue()));
   	assertNull(txSigned.getData());
   	assertEquals(27, txSigned.getSignature().v);
   	assertEquals("eab47c1a49bf2fe5d40e01d313900e19ca485867d462fe06e139e3a536c6d4f4", Hex.toHexString(BigIntegers.asUnsignedByteArray(txSigned.getSignature().r)));
   	assertEquals("14a569d327dcda4b29f74f93c0e9729d2f49ad726e703f9cd90dbb0fbf6649f1", Hex.toHexString(BigIntegers.asUnsignedByteArray(txSigned.getSignature().s)));
}
 
Example #4
Source File: Transaction.java    From asf-sdk with GNU General Public License v3.0 6 votes vote down vote up
private void validate() {
  if (getNonce().length > HASH_LENGTH) throw new RuntimeException("Nonce is not valid");
  if (receiveAddress != null
      && receiveAddress.length != 0
      && receiveAddress.length != ADDRESS_LENGTH) {
    throw new RuntimeException("Receive address is not valid");
  }
  if (gasLimit.length > HASH_LENGTH) throw new RuntimeException("Gas Limit is not valid");
  if (gasPrice != null && gasPrice.length > HASH_LENGTH) {
    throw new RuntimeException("Gas Price is not valid");
  }
  if (value != null && value.length > HASH_LENGTH) {
    throw new RuntimeException("Value is not valid");
  }
  if (getSignature() != null) {
    if (BigIntegers.asUnsignedByteArray(signature.r).length > HASH_LENGTH) {
      throw new RuntimeException("Signature R is not valid");
    }
    if (BigIntegers.asUnsignedByteArray(signature.s).length > HASH_LENGTH) {
      throw new RuntimeException("Signature S is not valid");
    }
    if (getSender() != null && getSender().length != ADDRESS_LENGTH) {
      throw new RuntimeException("Sender is not valid");
    }
  }
}
 
Example #5
Source File: EthTransaction.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 6 votes vote down vote up
private void validate() {
        if (getNonce().length > HASH_LENGTH) throw new RuntimeException("Nonce is not valid");
        if (receiveAddress != null && receiveAddress.length != 0 && receiveAddress.length !=
                ADDRESS_LENGTH)
            throw new RuntimeException("Receive address is not valid");
        if (gasLimit.length > HASH_LENGTH)
            throw new RuntimeException("Gas Limit is not valid");
        if (gasPrice != null && gasPrice.length > HASH_LENGTH)
            throw new RuntimeException("Gas Price is not valid");
        if (value != null && value.length > HASH_LENGTH)
            throw new RuntimeException("Value is not valid");
        if (getSignature() != null) {
            if (BigIntegers.asUnsignedByteArray(signature.r).length > HASH_LENGTH)
                throw new RuntimeException("Signature R is not valid");
            if (BigIntegers.asUnsignedByteArray(signature.s).length > HASH_LENGTH)
                throw new RuntimeException("Signature S is not valid");
//            if (getSender() != null && getSender().length != ADDRESS_LENGTH)
//                throw new RuntimeException("Sender is not valid");
        }
    }
 
Example #6
Source File: EthTransaction.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 6 votes vote down vote up
public String toString(int maxDataSize) {
        rlpParse();
        String dataS;
        if (data == null) {
            dataS = "";
        } else if (data.length < maxDataSize) {
            dataS = ByteUtil.toHexString(data);
        } else {
            dataS = ByteUtil.toHexString(Arrays.copyOfRange(data, 0, maxDataSize)) +
                    "... (" + data.length + " bytes)";
        }
        return "TransactionData [" + "hash=" + ByteUtil.toHexString(hash) +
                "  nonce=" + ByteUtil.toHexString(nonce) +
                ", gasPrice=" + ByteUtil.toHexString(gasPrice) +
                ", gas=" + ByteUtil.toHexString(gasLimit) +
                ", receiveAddress=" + ByteUtil.toHexString(receiveAddress) +
//                ", sendAddress=" + ByteUtil.toHexString(getSender()) +
                ", value=" + ByteUtil.toHexString(value) +
                ", data=" + dataS +
                ", signatureV=" + (signature == null ? "" : signature.v) +
                ", signatureR=" + (signature == null ? "" : ByteUtil.toHexString(BigIntegers
                .asUnsignedByteArray(signature.r))) +
                ", signatureS=" + (signature == null ? "" : ByteUtil.toHexString(BigIntegers
                .asUnsignedByteArray(signature.s))) +
                "]";
    }
 
Example #7
Source File: TransactionTest.java    From ethereumj with MIT License 6 votes vote down vote up
@Test
public void testTransactionFromUnsignedRLP() throws Exception {
   	Transaction txUnsigned = new Transaction(Hex.decode(RLP_ENCODED_UNSIGNED_TX));
   	
   	assertEquals(HASH_TX, Hex.toHexString(txUnsigned.getHash()));
   	assertEquals(RLP_ENCODED_UNSIGNED_TX, Hex.toHexString(txUnsigned.getEncoded()));
   	txUnsigned.sign(Hex.decode(KEY));
   	assertEquals(RLP_ENCODED_SIGNED_TX, Hex.toHexString(txUnsigned.getEncoded()));   	
   	
   	assertEquals(BigInteger.ZERO, new BigInteger(1, txUnsigned.getNonce()));
   	assertEquals(new BigInteger(1, testGasPrice), new BigInteger(1, txUnsigned.getGasPrice()));
   	assertEquals(new BigInteger(1, testGasLimit), new BigInteger(1, txUnsigned.getGasLimit()));
   	assertEquals(Hex.toHexString(testReceiveAddress), Hex.toHexString(txUnsigned.getReceiveAddress()));
   	assertEquals(new BigInteger(1, testValue), new BigInteger(1, txUnsigned.getValue()));
   	assertNull(txUnsigned.getData());
   	assertEquals(27, txUnsigned.getSignature().v);
   	assertEquals("eab47c1a49bf2fe5d40e01d313900e19ca485867d462fe06e139e3a536c6d4f4", Hex.toHexString(BigIntegers.asUnsignedByteArray(txUnsigned.getSignature().r)));
   	assertEquals("14a569d327dcda4b29f74f93c0e9729d2f49ad726e703f9cd90dbb0fbf6649f1", Hex.toHexString(BigIntegers.asUnsignedByteArray(txUnsigned.getSignature().s)));
}
 
Example #8
Source File: Transaction.java    From asf-sdk with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @deprecated use {@link Transaction#create(String, BigInteger, BigInteger, BigInteger, * BigInteger, Integer)} instead
 */
public static Transaction create(String to, BigInteger amount, BigInteger nonce,
    BigInteger gasPrice, BigInteger gasLimit) {
  return new Transaction(BigIntegers.asUnsignedByteArray(nonce),
      BigIntegers.asUnsignedByteArray(gasPrice), BigIntegers.asUnsignedByteArray(gasLimit),
      Hex.decode(to), BigIntegers.asUnsignedByteArray(amount), null);
}
 
Example #9
Source File: Transaction.java    From wkcwallet-java with Apache License 2.0 5 votes vote down vote up
public byte[] getEncoded() {
    if(this.rlpEncoded != null) {
        return this.rlpEncoded;
    } else {
        byte[] nonce = null;
        if(this.nonce != null && (this.nonce.length != 1 || this.nonce[0] != 0)) {
            nonce = RLP.encodeElement(this.nonce);
        } else {
            nonce = RLP.encodeElement((byte[])null);
        }

        byte[] gasPrice = RLP.encodeElement(this.gasPrice);
        byte[] gasLimit = RLP.encodeElement(this.gasLimit);
        byte[] receiveAddress = RLP.encodeElement(this.receiveAddress);
        byte[] value = RLP.encodeElement(this.value);
        byte[] data = RLP.encodeElement(this.data);
        byte[] v;
        byte[] r;
        byte[] s;
        if(this.signature != null) {
            v = RLP.encodeByte(this.signature.v);
            r = RLP.encodeElement(BigIntegers.asUnsignedByteArray(this.signature.r));
            s = RLP.encodeElement(BigIntegers.asUnsignedByteArray(this.signature.s));
        } else {
            v = RLP.encodeElement(ByteUtil.EMPTY_BYTE_ARRAY);
            r = RLP.encodeElement(ByteUtil.EMPTY_BYTE_ARRAY);
            s = RLP.encodeElement(ByteUtil.EMPTY_BYTE_ARRAY);
        }

        this.rlpEncoded = RLP.encodeList(new byte[][]{nonce, gasPrice, gasLimit, receiveAddress, value, data, v, r, s});
        this.hash = this.getHash();
        return this.rlpEncoded;
    }
}
 
Example #10
Source File: ByteUtilExtendTest.java    From aion with MIT License 5 votes vote down vote up
/**
 * This test shows the difference between iterating over, and comparing byte[] vs BigInteger
 * value.
 *
 * <p>Results indicate that the former has ~15x better performance. Therefore this is used in
 * the Miner.mine() method.
 */
@Test
public void testIncrementPerformance() {
    boolean testEnabled = false;

    if (testEnabled) {
        byte[] counter1 = new byte[4];
        byte[] max = ByteBuffer.allocate(4).putInt(Integer.MAX_VALUE).array();
        long start1 = System.currentTimeMillis();
        while (ByteUtil.increment(counter1)) {
            if (compareTo(counter1, 0, 4, max, 0, 4) == 0) {
                break;
            }
        }
        System.out.println(
                System.currentTimeMillis()
                        - start1
                        + "ms to reach: "
                        + Hex.toHexString(counter1));

        BigInteger counter2 = BigInteger.ZERO;
        long start2 = System.currentTimeMillis();
        while (true) {
            if (counter2.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == 0) {
                break;
            }
            counter2 = counter2.add(BigInteger.ONE);
        }
        System.out.println(
                System.currentTimeMillis()
                        - start2
                        + "ms to reach: "
                        + Hex.toHexString(BigIntegers.asUnsignedByteArray(4, counter2)));
    }
}
 
Example #11
Source File: Transaction.java    From asf-sdk with GNU General Public License v3.0 5 votes vote down vote up
public String toString(int maxDataSize) {
  rlpParse();
  String dataS;
  if (data == null) {
    dataS = "";
  } else if (data.length < maxDataSize) {
    dataS = ByteUtil.toHexString(data);
  } else {
    dataS = ByteUtil.toHexString(Arrays.copyOfRange(data, 0, maxDataSize))
        + "... ("
        + data.length
        + " bytes)";
  }
  return "TransactionData ["
      + "hash="
      + ByteUtil.toHexString(hash)
      + "  nonce="
      + ByteUtil.toHexString(nonce)
      + ", gasPrice="
      + ByteUtil.toHexString(gasPrice)
      + ", gas="
      + ByteUtil.toHexString(gasLimit)
      + ", receiveAddress="
      + ByteUtil.toHexString(receiveAddress)
      + ", sendAddress="
      + ByteUtil.toHexString(getSender())
      + ", value="
      + ByteUtil.toHexString(value)
      + ", data="
      + dataS
      + ", signatureV="
      + (signature == null ? "" : signature.v)
      + ", signatureR="
      + (signature == null ? ""
      : ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(signature.r)))
      + ", signatureS="
      + (signature == null ? ""
      : ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(signature.s)))
      + "]";
}
 
Example #12
Source File: SerpentCompiler.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 *
 * @param code
 * @param init
 * @return encoded bytes
 */
public static byte[] encodeMachineCodeForVMRun(byte[] code, byte[] init) {

    if (code == null || code.length == 0) throw new RuntimeException("code can't be empty code: " + code);

    int numBytes = ByteUtil.numBytes(code.length + "");
    byte[] lenBytes = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(code.length));

    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < lenBytes.length; ++i) {
        sb.append(lenBytes[i]).append(" ");
    }

    // calc real code start position (after the init header)
    int pos = 10  + numBytes * 2;
    if (init != null) pos+=init.length;

    // @push_len @len PUSH1 @src_start  PUSH1 0 CODECOPY @push_len @len 0 PUSH1 0 RETURN
    String header =  String.format("[asm %s %s PUSH1 %d  PUSH1 0 CODECOPY %s %s PUSH1 0 RETURN asm]",
            "PUSH" + numBytes, sb.toString(), pos , "PUSH" + numBytes, sb.toString());

    byte[] headerMachine = compileAssemblyToMachine(header);

    byte[] result = init != null ? Arrays.concatenate(init, headerMachine, code) :
            Arrays.concatenate(headerMachine, code);

    return result;
}
 
Example #13
Source File: Transaction.java    From ethereumj with MIT License 5 votes vote down vote up
@Override
public String toString() {
    if (!parsed) rlpParse();
    return "TransactionData [" +  "hash=" + ByteUtil.toHexString(hash) +
            "  nonce=" + ByteUtil.toHexString(nonce) +
            ", gasPrice=" + ByteUtil.toHexString(gasPrice) +
            ", gas=" + ByteUtil.toHexString(gasLimit) +
            ", receiveAddress=" + ByteUtil.toHexString(receiveAddress) +
            ", value=" + ByteUtil.toHexString(value) +
            ", data=" + ByteUtil.toHexString(data) +
            ", signatureV=" + signature.v +
            ", signatureR=" + ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(signature.r)) +
            ", signatureS=" + ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(signature.s)) +
            "]";
}
 
Example #14
Source File: Transaction.java    From ethereumj with MIT License 5 votes vote down vote up
public String toStylishString() {
    if (!parsed) rlpParse();
    return " <font color=\"${sub_header_color}\"> TransactionData </font>[" +  "<font color=\"${attribute_color}\"> hash</font>=" + ByteUtil.toHexString(hash) + "<br/>" +
            "->  , <font color=\"${attribute_color}\"> nonce</font>=" + ByteUtil.toHexString(nonce) + "<br/>" +
            "->  , <font color=\"${attribute_color}\"> gasPrice</font>=" + ByteUtil.toHexString(gasPrice) + "<br/>" +
            "->  , <font color=\"${attribute_color}\"> gas</font>=" + ByteUtil.toHexString(gasLimit) + "<br/>" +
            "->  , <font color=\"${attribute_color}\"> receiveAddress</font>=" + ByteUtil.toHexString(receiveAddress) + "<br/>" +
            "->  , <font color=\"${attribute_color}\"> value</font>=" + ByteUtil.toHexString(value) + "<br/>" +
            "->  , <font color=\"${attribute_color}\"> data</font>=" + ByteUtil.toHexString(data) + "<br/>" +
            "->  , <font color=\"${attribute_color}\"> signatureV</font>=" + signature.v + "<br/>" +
            "->  , <font color=\"${attribute_color}\"> signatureR</font>=" + ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(signature.r)) + "<br/>" +
            "->  , <font color=\"${attribute_color}\"> signatureS</font>=" + ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(signature.s)) + "<br/>" +
            " ]";
}
 
Example #15
Source File: Transaction.java    From ethereumj with MIT License 5 votes vote down vote up
public byte[] getEncoded() {

        if(rlpEncoded != null) return rlpEncoded;

        // parse null as 0 for nonce
        byte[] nonce = null;
        if (this.nonce == null || this.nonce.length == 1 && this.nonce[0] == 0){
            nonce 				= RLP.encodeElement(null);
        } else {
            nonce 				= RLP.encodeElement(this.nonce);
        }
        byte[] gasPrice 			= RLP.encodeElement(this.gasPrice);
        byte[] gasLimit 			= RLP.encodeElement(this.gasLimit);
        byte[] receiveAddress 		= RLP.encodeElement(this.receiveAddress);
        byte[] value 				= RLP.encodeElement(this.value);
        byte[] data 				= RLP.encodeElement(this.data);

        byte[] v, r, s;
        
        if(signature != null) {
            v = RLP.encodeByte( signature.v );
            r = RLP.encodeElement(BigIntegers.asUnsignedByteArray(signature.r));
            s = RLP.encodeElement(BigIntegers.asUnsignedByteArray(signature.s));
        } else {
        	v = RLP.encodeElement(new byte[0]);
        	r = RLP.encodeElement(new byte[0]);
        	s = RLP.encodeElement(new byte[0]);
        }

		this.rlpEncoded = RLP.encodeList(nonce, gasPrice, gasLimit,
				receiveAddress, value, data, v, r, s);
        return rlpEncoded;
    }
 
Example #16
Source File: BlockHeader.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * Calculate Difficulty 
 * See Yellow Paper: http://www.gavwood.com/Paper.pdf - page 5, 4.3.4 (24)
 * @return byte array value of the difficulty
 */
public byte[] calcDifficulty() {
	if (this.isGenesis())
		return Genesis.DIFFICULTY;
	else {
		Block parent = this.getParent();
		long parentDifficulty = new BigInteger(1, parent.getDifficulty()).longValue();
		long newDifficulty = this.getTimestamp() < parent.getTimestamp() + 5 ? parentDifficulty - (parentDifficulty >> 10) : (parentDifficulty + (parentDifficulty >> 10));
		return BigIntegers.asUnsignedByteArray(BigInteger.valueOf(newDifficulty));
	}
}
 
Example #17
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 #18
Source File: ByteUtilTest.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * This test shows the difference between iterating over, 
 * and comparing byte[] vs BigInteger value.
 * 
 * Results indicate that the former has ~15x better performance.
 * Therefore this is used in the Miner.mine() method.
 */
@Test
public void testIncrementPerformance() {
	boolean testEnabled = false;
	
	if(testEnabled) {
		byte[] counter1 = new byte[4];
		byte[] max = ByteBuffer.allocate(4).putInt(Integer.MAX_VALUE).array();
		long start1 = System.currentTimeMillis();
		while(ByteUtil.increment(counter1)) {
			if(FastByteComparisons.compareTo(counter1, 0, 4, max, 0, 4) == 0) {
				break;
			}
		}
		System.out.println(System.currentTimeMillis() - start1 + "ms to reach: " + Hex.toHexString(counter1));
		
		BigInteger counter2 = BigInteger.ZERO;
		long start2 = System.currentTimeMillis();
		while(true) {
			if(counter2.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == 0) {
				break;
			}
			counter2 = counter2.add(BigInteger.ONE);
		}
		System.out.println(System.currentTimeMillis() - start2 + "ms to reach: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(4, counter2)));
	}
}
 
Example #19
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 #20
Source File: ECKey.java    From tron-wallet-android with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

  if (privKey == null) {
    throw new MissingPrivateKeyException();
  }
  if (!(privKey instanceof BCECPrivateKey)) {
    throw new UnsupportedOperationException("Cannot use the private " +
        "key as an AES key");
  }

  AESFastEngine engine = new AESFastEngine();
  SICBlockCipher ctrEngine = new SICBlockCipher(engine);

  KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray((
      (BCECPrivateKey) privKey).getD()));
  ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

  ctrEngine.init(false, params);

  int i = 0;
  byte[] out = new byte[cipher.length];
  while (i < cipher.length) {
    ctrEngine.processBlock(cipher, i, out, i);
    i += engine.getBlockSize();
    if (cipher.length - i < engine.getBlockSize()) {
      break;
    }
  }

  // process left bytes
  if (cipher.length - i > 0) {
    byte[] tmpBlock = new byte[16];
    System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
    ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
    System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
  }

  return out;
}
 
Example #21
Source File: ECKey.java    From wkcwallet-java with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher
 *            -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private key as an AES key");
    }

    AESFastEngine engine = new AESFastEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray(((BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize())
            break;
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}
 
Example #22
Source File: TransactionTest.java    From ethereumj with MIT License 5 votes vote down vote up
@Test
public void testTransactionFromNew2() throws MissingPrivateKeyException {
       byte[] privKeyBytes = Hex.decode("c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4");
       
       String RLP_TX_UNSIGNED = "eb8085e8d4a510008227109413978aee95f38490e9769c39b2773ed763d9cd5f872386f26fc1000080808080";
       String RLP_TX_SIGNED = "f86b8085e8d4a510008227109413978aee95f38490e9769c39b2773ed763d9cd5f872386f26fc10000801ba0eab47c1a49bf2fe5d40e01d313900e19ca485867d462fe06e139e3a536c6d4f4a014a569d327dcda4b29f74f93c0e9729d2f49ad726e703f9cd90dbb0fbf6649f1";
       String HASH_TX_UNSIGNED = "328ea6d24659dec48adea1aced9a136e5ebdf40258db30d1b1d97ed2b74be34e";
       
	byte[] nonce			= BigIntegers.asUnsignedByteArray(BigInteger.ZERO);
	byte[] gasPrice			= Hex.decode("e8d4a51000");		// 1000000000000
	byte[] gas				= Hex.decode("2710");			// 10000
	byte[] recieveAddress	= Hex.decode("13978aee95f38490e9769c39b2773ed763d9cd5f");
	byte[] value			= Hex.decode("2386f26fc10000"); //10000000000000000"
	byte[] data 			= new byte[0];
	
   	Transaction tx = new Transaction(nonce, gasPrice, gas, recieveAddress, value, data);
   	    	
   	// Testing unsigned
   	String encodedUnsigned = Hex.toHexString(tx.getEncoded());
       assertEquals(RLP_TX_UNSIGNED, encodedUnsigned);
       assertEquals(HASH_TX_UNSIGNED, Hex.toHexString(tx.getHash()));

       // Testing signed
       tx.sign(privKeyBytes);
       String encodedSigned = Hex.toHexString(tx.getEncoded());       
       assertEquals(RLP_TX_SIGNED, encodedSigned);
       assertEquals(HASH_TX_UNSIGNED, Hex.toHexString(tx.getHash()));
}
 
Example #23
Source File: EthTransaction.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 5 votes vote down vote up
public static EthTransaction create(String to, BigInteger amount, BigInteger nonce,
                                    BigInteger gasPrice,
                                    BigInteger gasLimit, Integer chainId) {
    return new EthTransaction(BigIntegers.asUnsignedByteArray(nonce),
            BigIntegers.asUnsignedByteArray(gasPrice),
            BigIntegers.asUnsignedByteArray(gasLimit),
            Hex.decode(to),
            BigIntegers.asUnsignedByteArray(amount),
            null,
            chainId);
}
 
Example #24
Source File: EthTransaction.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @deprecated use
 * {@link EthTransaction#create(String, BigInteger, BigInteger, BigInteger, BigInteger, Integer)} instead
 */
public static EthTransaction create(String to, BigInteger amount, BigInteger nonce,
                                    BigInteger gasPrice, BigInteger gasLimit) {
    return new EthTransaction(BigIntegers.asUnsignedByteArray(nonce),
            BigIntegers.asUnsignedByteArray(gasPrice),
            BigIntegers.asUnsignedByteArray(gasLimit),
            Hex.decode(to),
            BigIntegers.asUnsignedByteArray(amount),
            null);
}
 
Example #25
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 #26
Source File: CallTransaction.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 5 votes vote down vote up
public static EthTransaction createRawTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String toAddress,
                                                  BigInteger value, byte[] data) {
    EthTransaction tx = new EthTransaction(BigIntegers.asUnsignedByteArray(nonce),
            BigIntegers.asUnsignedByteArray(gasPrice),
            BigIntegers.asUnsignedByteArray(gasLimit),
            toAddress == null ? null : Hex.decode(toAddress),
            BigIntegers.asUnsignedByteArray(value),
            data,
            null);
    return tx;
}
 
Example #27
Source File: Peer.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public byte[] calcDistance(Peer toPeer) {

        BigInteger aaPeer = new BigInteger(getId());
        BigInteger bbPeer = new BigInteger(toPeer.getId());

        BigInteger distance = aaPeer.xor(bbPeer);
        return BigIntegers.asUnsignedByteArray(distance);
    }
 
Example #28
Source File: ECKey.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private " +
                "key as an AES key");
    }

    AESEngine engine = new AESEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray((
            (BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize()) {
            break;
        }
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}
 
Example #29
Source File: ProvisioningPublicKeyState.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void generateKeyPairs() {

        try {
            final ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec("secp256r1");
            final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDH", "SC");
            keyPairGenerator.initialize(parameterSpec);
            final KeyPair keyPair = keyPairGenerator.generateKeyPair();
            final ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();

            mProvisionerPrivaetKey = (ECPrivateKey) keyPair.getPrivate();

            final ECPoint point = publicKey.getQ();

            final BigInteger x = point.getXCoord().toBigInteger();
            final BigInteger y = point.getYCoord().toBigInteger();
            final byte[] tempX = BigIntegers.asUnsignedByteArray(32, x);
            final byte[] tempY = BigIntegers.asUnsignedByteArray(32, y);

            Log.v(TAG, "X: length: " + tempX.length + " " + MeshParserUtils.bytesToHex(tempX, false));
            Log.v(TAG, "Y: length: " + tempY.length + " " + MeshParserUtils.bytesToHex(tempY, false));

            final byte[] tempXY = new byte[64];
            System.arraycopy(tempX, 0, tempXY, 0, tempX.length);
            System.arraycopy(tempY, 0, tempXY, tempY.length, tempY.length);

            mUnprovisionedMeshNode.setProvisionerPublicKeyXY(tempXY);

            Log.v(TAG, "XY: " + MeshParserUtils.bytesToHex(tempXY, true));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example #30
Source File: ECKeySecp256k1.java    From aion with MIT License 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private key as an AES key");
    }

    AESFastEngine engine = new AESFastEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key =
            new KeyParameter(
                    BigIntegers.asUnsignedByteArray(((BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize()) {
            break;
        }
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}