Java Code Examples for org.bitcoinj.core.ECKey#sign()

The following examples show how to use org.bitcoinj.core.ECKey#sign() . 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: DeterministicKeyChainTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void derive() throws Exception {
    ECKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertFalse(key1.isPubKeyOnly());
    ECKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertFalse(key2.isPubKeyOnly());

    final Address address = LegacyAddress.fromBase58(UNITTEST, "n1bQNoEx8uhmCzzA5JPG6sFdtsUQhwiQJV");
    assertEquals(address, LegacyAddress.fromKey(UNITTEST, key1));
    assertEquals("mnHUcqUVvrfi5kAaXJDQzBb9HsWs78b42R", LegacyAddress.fromKey(UNITTEST, key2).toString());
    assertEquals(key1, chain.findKeyFromPubHash(address.getHash()));
    assertEquals(key2, chain.findKeyFromPubKey(key2.getPubKey()));

    key1.sign(Sha256Hash.ZERO_HASH);
    assertFalse(key1.isPubKeyOnly());

    ECKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
    assertFalse(key3.isPubKeyOnly());
    assertEquals("mqumHgVDqNzuXNrszBmi7A2UpmwaPMx4HQ", LegacyAddress.fromKey(UNITTEST, key3).toString());
    key3.sign(Sha256Hash.ZERO_HASH);
    assertFalse(key3.isPubKeyOnly());
}
 
Example 2
Source File: DeterministicKeyChainTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void deriveAccountOne() throws Exception {
    long secs = 1389353062L;
    DeterministicKeyChain chain1 = new AccountOneChain(ENTROPY, "", secs);
    ECKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    ECKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);

    final Address address = LegacyAddress.fromBase58(UNITTEST, "n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X");
    assertEquals(address, LegacyAddress.fromKey(UNITTEST, key1));
    assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", LegacyAddress.fromKey(UNITTEST, key2).toString());
    assertEquals(key1, chain1.findKeyFromPubHash(address.getHash()));
    assertEquals(key2, chain1.findKeyFromPubKey(key2.getPubKey()));

    key1.sign(Sha256Hash.ZERO_HASH);

    ECKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", LegacyAddress.fromKey(UNITTEST, key3).toString());
    key3.sign(Sha256Hash.ZERO_HASH);
}
 
Example 3
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signInput(Transaction transaction, TransactionInput input, int inputIndex) throws SigningException {
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    Script scriptPubKey = input.getConnectedOutput().getScriptPubKey();
    checkNotNull(wallet);
    ECKey sigKey = input.getOutpoint().getConnectedKey(wallet);
    checkNotNull(sigKey, "signInput: sigKey must not be null. input.getOutpoint()=" + input.getOutpoint().toString());
    if (sigKey.isEncrypted())
        checkNotNull(aesKey);
    Sha256Hash hash = transaction.hashForSignature(inputIndex, scriptPubKey, Transaction.SigHash.ALL, false);
    ECKey.ECDSASignature signature = sigKey.sign(hash, aesKey);
    TransactionSignature txSig = new TransactionSignature(signature, Transaction.SigHash.ALL, false);
    if (scriptPubKey.isSentToRawPubKey()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig));
    } else if (scriptPubKey.isSentToAddress()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey));
    } else {
        throw new SigningException("Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey);
    }
}
 
Example 4
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signInput(Transaction transaction, TransactionInput input, int inputIndex) throws SigningException {
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    Script scriptPubKey = input.getConnectedOutput().getScriptPubKey();
    checkNotNull(wallet);
    ECKey sigKey = input.getOutpoint().getConnectedKey(wallet);
    checkNotNull(sigKey, "signInput: sigKey must not be null. input.getOutpoint()=" +
            input.getOutpoint().toString());
    if (sigKey.isEncrypted()) {
        checkNotNull(aesKey);
    }
    Sha256Hash hash = transaction.hashForSignature(inputIndex, scriptPubKey, Transaction.SigHash.ALL, false);
    ECKey.ECDSASignature signature = sigKey.sign(hash, aesKey);
    TransactionSignature txSig = new TransactionSignature(signature, Transaction.SigHash.ALL, false);
    if (scriptPubKey.isSentToRawPubKey()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig));
    } else if (scriptPubKey.isSentToAddress()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey));
    } else {
        throw new SigningException("Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey);
    }
}
 
Example 5
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = ECKey.MissingPrivateKeyException.class)
public void watchingWalletWithCreationTime() throws Exception {
    DeterministicKey watchKey = wallet.getWatchingKey();
    String serialized = watchKey.serializePubB58(UNITTEST);
    Wallet watchingWallet = Wallet.fromWatchingKeyB58(UNITTEST, serialized, 1415282801);
    DeterministicKey key2 = watchingWallet.freshReceiveKey();
    assertEquals(myKey, key2);

    ECKey key = wallet.freshKey(KeyChain.KeyPurpose.CHANGE);
    key2 = watchingWallet.freshKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals(key, key2);
    key.sign(Sha256Hash.ZERO_HASH);
    key2.sign(Sha256Hash.ZERO_HASH);
}
 
Example 6
Source File: Crypto.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
public static byte[] sign(byte[] msg, ECKey k) throws NoSuchAlgorithmException {

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] msgHash = digest.digest(msg);

        ECKey.ECDSASignature signature = k.sign(Sha256Hash.wrap(msgHash));

        byte[] result = new byte[64];
        System.arraycopy(Utils.bigIntegerToBytes(signature.r, 32), 0, result, 0, 32);
        System.arraycopy(Utils.bigIntegerToBytes(signature.s, 32), 0, result, 32, 32);
        return result;
    }
 
Example 7
Source File: TransactionUtil.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Signature btcCoinSign(byte[] data, byte[] privateKey) {
	byte[] sha256 = TransactionUtil.Sha256(data);
	Sha256Hash sha256Hash = Sha256Hash.wrap(sha256);
	ECKey ecKey = ECKey.fromPrivate(privateKey);
	ECKey.ECDSASignature ecdsas = ecKey.sign(sha256Hash);
	byte[] signByte = ecdsas.encodeToDER();
	Signature signature = new Signature();
	signature.setPubkey(ecKey.getPubKey());
	signature.setSignature(signByte);
	signature.setTy(SignType.SECP256K1.getType());
	return signature;
}
 
Example 8
Source File: EthereumSign.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
public static SignatureData signAsRecoverable(byte[] value, ECKey ecKey) {

    ECKey.ECDSASignature sig = ecKey.sign(Sha256Hash.wrap(value));

    // Now we have to work backwards to figure out the recId needed to recover the signature.
    int recId = -1;
    for (int i = 0; i < 4; i++) {
      ECKey recoverKey = ECKey.recoverFromSignature(i, sig, Sha256Hash.wrap(value), false);
      if (recoverKey != null && recoverKey.getPubKeyPoint().equals(ecKey.getPubKeyPoint())) {
        recId = i;
        break;
      }
    }
    if (recId == -1) {
      throw new RuntimeException(
          "Could not construct a recoverable key. This should never happen.");
    }

    int headerByte = recId + 27;

    // 1 header + 32 bytes for R + 32 bytes for S
    byte v = (byte) headerByte;
    byte[] r = NumericUtil.bigIntegerToBytesWithZeroPadded(sig.r, 32);
    byte[] s = NumericUtil.bigIntegerToBytesWithZeroPadded(sig.s, 32);

    return new SignatureData(v, r, s);
  }
 
Example 9
Source File: Secp256k1Context.java    From sawtooth-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a bitcoin-style compact signature.
 *
 * @param privateKey ECKey private key
 * @param data the raw message bytes
 * @return the raw signature bytes
 */
private static byte[] generateCompactSig(final ECKey privateKey, final byte[] data) {
  Sha256Hash hash = Sha256Hash.of(data);
  ECKey.ECDSASignature sig = privateKey.sign(hash);

  byte[] csig = new byte[NUM_SIGNATURE_BYTES];

  System.arraycopy(Utils.bigIntegerToBytes(sig.r, HALF_NUM_SIGNATURE_BYTES), 0,
                                           csig, 0, HALF_NUM_SIGNATURE_BYTES);
  System.arraycopy(Utils.bigIntegerToBytes(sig.s, HALF_NUM_SIGNATURE_BYTES), 0,
                                           csig, HALF_NUM_SIGNATURE_BYTES, HALF_NUM_SIGNATURE_BYTES);

  return csig;
}
 
Example 10
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = ECKey.MissingPrivateKeyException.class)
public void watchingWalletWithCreationTime() throws Exception {
    DeterministicKey watchKey = wallet.getWatchingKey();
    String serialized = watchKey.serializePubB58(PARAMS);
    Wallet watchingWallet = Wallet.fromWatchingKeyB58(PARAMS, serialized, 1415282801);
    DeterministicKey key2 = watchingWallet.freshReceiveKey();
    assertEquals(myKey, key2);

    ECKey key = wallet.freshKey(KeyChain.KeyPurpose.CHANGE);
    key2 = watchingWallet.freshKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals(key, key2);
    key.sign(Sha256Hash.ZERO_HASH);
    key2.sign(Sha256Hash.ZERO_HASH);
}
 
Example 11
Source File: Crypto.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
public static byte[] sign(byte[] msg, ECKey k) throws NoSuchAlgorithmException {

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] msgHash = digest.digest(msg);

        ECKey.ECDSASignature signature = k.sign(Sha256Hash.wrap(msgHash));

        byte[] result = new byte[64];
        System.arraycopy(Utils.bigIntegerToBytes(signature.r, 32), 0, result, 0, 32);
        System.arraycopy(Utils.bigIntegerToBytes(signature.s, 32), 0, result, 32, 32);
        return result;
    }
 
Example 12
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = ECKey.MissingPrivateKeyException.class)
public void watchingWalletWithCreationTime() throws Exception {
    DeterministicKey watchKey = wallet.getWatchingKey();
    String serialized = watchKey.serializePubB58(PARAMS);
    Wallet watchingWallet = Wallet.fromWatchingKeyB58(PARAMS, serialized, 1415282801);
    DeterministicKey key2 = watchingWallet.freshReceiveKey();
    assertEquals(myKey, key2);

    ECKey key = wallet.freshKey(KeyChain.KeyPurpose.CHANGE);
    key2 = watchingWallet.freshKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals(key, key2);
    key.sign(Sha256Hash.ZERO_HASH);
    key2.sign(Sha256Hash.ZERO_HASH);
}
 
Example 13
Source File: SegWitWalletTest.java    From token-core-android with Apache License 2.0 4 votes vote down vote up
@Test
public void transactionSignTest() {
  String address = "1Fyxts6r24DpEieygQiNnWxUdb18ANa5p7";
  byte[] hash160 = Address.fromBase58(MainNetParams.get(), address).getHash160();
  System.out.println("Public Key: " + NumericUtil.bytesToHex(hash160));

  String privateKey = "eb696a065ef48a2192da5b28b694f87544b30fae8327c4510137a922f32c6dcf";
  ECKey ecKey = ECKey.fromPrivate(NumericUtil.hexToBytes(privateKey), true);
  assertEquals("public key", "03ad1d8e89212f0b92c74d23bb710c00662ad1470198ac48c43f7d6f93a2a26873", ecKey.getPublicKeyAsHex());
  byte[] pubKeyHash = ecKey.getPubKeyHash();
  String redeemScript = String.format("0x0014%s", NumericUtil.bytesToHex(pubKeyHash));
  assertEquals("redeem script", "0x001479091972186c449eb1ded22b78e40d009bdf0089", redeemScript);
  byte[] redeemScriptBytes = Utils.sha256hash160(NumericUtil.hexToBytes(redeemScript));
  byte[] scriptCode = NumericUtil.hexToBytes(String.format("0x1976a914%s88ac", NumericUtil.bytesToHex(pubKeyHash)));
  String scriptPub = Integer.toHexString(169) + Integer.toHexString(redeemScriptBytes.length) + NumericUtil.bytesToHex(redeemScriptBytes) + Integer.toHexString(135);
  assertEquals("scriptPubKey", "a9144733f37cf4db86fbc2efed2500b4f4e49f31202387", scriptPub);
  byte[] hashPrevouts = Sha256Hash.hashTwice(NumericUtil.hexToBytes("db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a547701000000"));
  assertEquals("hash Prevouts", "b0287b4a252ac05af83d2dcef00ba313af78a3e9c329afa216eb3aa2a7b4613a", NumericUtil.bytesToHex(hashPrevouts));
  byte[] hashSequence = Sha256Hash.hashTwice(NumericUtil.hexToBytes("feffffff"));
  assertEquals("hashSequence", "18606b350cd8bf565266bc352f0caddcf01e8fa789dd8a15386327cf8cabe198", NumericUtil.bytesToHex(hashSequence));
  byte[] hashOutputs = Sha256Hash.hashTwice(NumericUtil.hexToBytes("b8b4eb0b000000001976a914a457b684d7f0d539a46a45bbc043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac"));
  assertEquals("hashOutputs", "de984f44532e2173ca0d64314fcefe6d30da6f8cf27bafa706da61df8a226c83", NumericUtil.bytesToHex(hashOutputs));

  UnsafeByteArrayOutputStream stream = new UnsafeByteArrayOutputStream();
  try {
    Utils.uint32ToByteStreamLE(1L, stream);
    stream.write(hashPrevouts);
    stream.write(hashSequence);
    stream.write(NumericUtil.hexToBytes("db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a547701000000"));
    stream.write(scriptCode);
    stream.write(NumericUtil.hexToBytes("00ca9a3b00000000"));
    stream.write(NumericUtil.hexToBytes("feffffff"));
    stream.write(hashOutputs);
    Utils.uint32ToByteStreamLE(1170, stream);
    Utils.uint32ToByteStreamLE(1, stream);
    String hashPreimage = NumericUtil.bytesToHex(stream.toByteArray());
    String expectedHashPreimage = "01000000b0287b4a252ac05af83d2dcef00ba313af78a3e9c329afa216eb3aa2a7b4613a18606b350cd8bf565266bc352f0caddcf01e8fa789dd8a15386327cf8cabe198db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a5477010000001976a91479091972186c449eb1ded22b78e40d009bdf008988ac00ca9a3b00000000feffffffde984f44532e2173ca0d64314fcefe6d30da6f8cf27bafa706da61df8a226c839204000001000000";
    assertEquals(hashPreimage, expectedHashPreimage);
    byte[] sigHash = Sha256Hash.hashTwice(stream.toByteArray());
    assertEquals("64f3b0f4dd2bb3aa1ce8566d220cc74dda9df97d8490cc81d89d735c92e59fb6", NumericUtil.bytesToHex(sigHash));
    ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.wrap(sigHash));
    byte hashType = 0x01;
    System.out.println(NumericUtil.bytesToHex(ByteUtil.concat(signature.encodeToDER(), new byte[]{hashType})));

  } catch (IOException e) {
    e.printStackTrace();
  }

}