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

The following examples show how to use org.bitcoinj.core.ECKey#fromPrivate() . 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: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlockByXPRV2(String xprv, Runnable callback) {
    xprv = xprv.trim();
    try {
        DeterministicKey dk01 = DeterministicKey.deserializeB58(xprv, params);
        String privhex = dk01.getPrivateKeyAsHex();
        ECKey ecKey001 = ECKey.fromPrivate(Hex.decode(privhex));
        KeyChainGroup kcg = new KeyChainGroup(params, dk01.dropPrivateBytes().dropParent());
        kcg.importKeys(ecKey001);
        wallet = new Wallet(params, kcg);
        sharedManager.setLastSyncedBlock(Coders.encodeBase64(xprv));
        updateWalletFriendlyAddress();
        xprvKey = xprv;
    } catch (IllegalArgumentException iae) {
        FirebaseCrash.report(iae);
        Log.e("psd", "restoreFromBlockByXPRV2: " + iae.toString());
        callback.run();
        return;
    }

    callback.run();

    RequestorBtc.getUTXOListQtum(walletFriendlyAddress, new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example 2
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void sendCoinsWithBroadcasterTest() throws InsufficientMoneyException {
    ECKey key = ECKey.fromPrivate(BigInteger.TEN);
    receiveATransactionAmount(wallet, myAddress, Coin.COIN);
    MockTransactionBroadcaster broadcaster = new MockTransactionBroadcaster(wallet);
    wallet.setTransactionBroadcaster(broadcaster);
    SendRequest req = SendRequest.to(OTHER_ADDRESS.getParameters(), key, Coin.CENT);
    wallet.sendCoins(req);
}
 
Example 3
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlockByXPRV2(String xprv, Runnable callback) {
    xprv = xprv.trim();
    try {
        DeterministicKey dk01 = DeterministicKey.deserializeB58(xprv, params);
        String privhex = dk01.getPrivateKeyAsHex();
        ECKey ecKey001 = ECKey.fromPrivate(Hex.decode(privhex));
        KeyChainGroup kcg = new KeyChainGroup(params, dk01.dropPrivateBytes().dropParent());
        kcg.importKeys(ecKey001);
        wallet = new Wallet(params, kcg);
        sharedManager.setLastSyncedBlock(Coders.encodeBase64(xprv));
        walletFriendlyAddress = wallet.currentReceiveAddress().toString();
        xprvKey = xprv;
    } catch (IllegalArgumentException iae) {
        FirebaseCrash.report(iae);
        Log.e("psd", "restoreFromBlockByXPRV2: " + iae.toString());
        callback.run();
        return;
    }

    callback.run();

    RequestorBtc.getUTXOListBch(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example 4
Source File: private_key.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public sha512_object get_shared_secret(public_key publicKey) {
    ECKey ecPublicKey = ECKey.fromPublicOnly(publicKey.getKeyByte());
    ECKey ecPrivateKey = ECKey.fromPrivate(key_data);

    byte[] secret = ecPublicKey.getPubKeyPoint().multiply(ecPrivateKey.getPrivKey())
            .normalize().getXCoord().getEncoded();

    return sha512_object.create_from_byte_array(secret, 0, secret.length);
}
 
Example 5
Source File: FilterManager.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isKeyValid(String privKeyString) {
    try {
        filterSigningKey = ECKey.fromPrivate(new BigInteger(1, HEX.decode(privKeyString)));
        return pubKeyAsHex.equals(Utils.HEX.encode(filterSigningKey.getPubKey()));
    } catch (Throwable t) {
        return false;
    }
}
 
Example 6
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlockByXPRV2(String xprv, Runnable callback) {
    xprv = xprv.trim();
    try {
        DeterministicKey dk01 = DeterministicKey.deserializeB58(xprv, params);
        String privhex = dk01.getPrivateKeyAsHex();
        ECKey ecKey001 = ECKey.fromPrivate(Hex.decode(privhex));
        KeyChainGroup kcg = new KeyChainGroup(params, dk01.dropPrivateBytes().dropParent());
        kcg.importKeys(ecKey001);
        wallet = new Wallet(params, kcg);
        sharedManager.setLastSyncedBlock(Coders.encodeBase64(xprv));
        walletFriendlyAddress = wallet.currentReceiveAddress().toString();
        xprvKey = xprv;
    } catch (IllegalArgumentException iae) {
        FirebaseCrash.report(iae);
        Log.e("psd", "restoreFromBlockByXPRV2: " + iae.toString());
        callback.run();
        return;
    }

    callback.run();

    RequestorBtc.getUTXOListBtgNew(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example 7
Source File: AlertManager.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isKeyValid(String privKeyString) {
    try {
        alertSigningKey = ECKey.fromPrivate(new BigInteger(1, HEX.decode(privKeyString)));
        return pubKeyAsHex.equals(Utils.HEX.encode(alertSigningKey.getPubKey()));
    } catch (Throwable t) {
        return false;
    }
}
 
Example 8
Source File: PrivateNotificationManager.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isKeyValid(String privKeyString) {
    try {
        privateNotificationSigningKey = ECKey.fromPrivate(new BigInteger(1, HEX.decode(privKeyString)));
        return pubKeyAsHex.equals(Utils.HEX.encode(privateNotificationSigningKey.getPubKey()));
    } catch (Throwable t) {
        return false;
    }
}
 
Example 9
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void fromKeys() {
    ECKey key = ECKey.fromPrivate(Utils.HEX.decode("00905b93f990267f4104f316261fc10f9f983551f9ef160854f40102eb71cffdcc"));
    Wallet wallet = Wallet.fromKeys(UNITTEST, Arrays.asList(key));
    assertEquals(1, wallet.getImportedKeys().size());
    assertEquals(key, wallet.getImportedKeys().get(0));
    wallet.upgradeToDeterministic(null);
    String seed = wallet.getKeyChainSeed().toHexString();
    assertEquals("5ca8cd6c01aa004d3c5396c628b78a4a89462f412f460a845b594ac42eceaa264b0e14dcd4fe73d4ed08ce06f4c28facfa85042d26d784ab2798a870bb7af556", seed);
}
 
Example 10
Source File: AlertManager.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isKeyValid(String privKeyString) {
    try {
        alertSigningKey = ECKey.fromPrivate(new BigInteger(1, HEX.decode(privKeyString)));
        return pubKeyAsHex.equals(Utils.HEX.encode(alertSigningKey.getPubKey()));
    } catch (Throwable t) {
        return false;
    }
}
 
Example 11
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlockByXPRV2(String xprv, Runnable callback) {
    xprv = xprv.trim();
    try {
        DeterministicKey dk01 = DeterministicKey.deserializeB58(xprv, params);
        String privhex = dk01.getPrivateKeyAsHex();
        ECKey ecKey001 = ECKey.fromPrivate(Hex.decode(privhex));
        KeyChainGroup kcg = new KeyChainGroup(params, dk01.dropPrivateBytes().dropParent());
        kcg.importKeys(ecKey001);
        wallet = new Wallet(params, kcg);
        sharedManager.setLastSyncedBlock(Coders.encodeBase64(xprv));
        walletFriendlyAddress = wallet.currentReceiveAddress().toString();
        xprvKey = xprv;
    } catch (IllegalArgumentException iae) {
        FirebaseCrash.report(iae);
        Log.e("psd", "restoreFromBlockByXPRV2: " + iae.toString());
        callback.run();
        return;
    }

    callback.run();

    RequestorBtc.getUTXOListBch(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example 12
Source File: Secp256k1Context.java    From sawtooth-sdk-java with Apache License 2.0 4 votes vote down vote up
@Override
public final PublicKey getPublicKey(final PrivateKey privateKey) {
  ECKey privKey = ECKey.fromPrivate(privateKey.getBytes());
  byte[] publicKey = privKey.getPubKey();
  return new Secp256k1PublicKey(publicKey);
}
 
Example 13
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Test(expected = java.lang.IllegalStateException.class)
public void sendCoinsNoBroadcasterTest() throws InsufficientMoneyException {
    ECKey key = ECKey.fromPrivate(BigInteger.TEN);
    SendRequest req = SendRequest.to(OTHER_ADDRESS.getParameters(), key, SATOSHI.multiply(12));
    wallet.sendCoins(req);
}
 
Example 14
Source File: Crypto.java    From java-sdk with Apache License 2.0 4 votes vote down vote up
public static String getAddressFromPrivateKey(String privateKey, String hrp) {
    ECKey ecKey = ECKey.fromPrivate(new BigInteger(privateKey, 16));
    return getAddressFromECKey(ecKey, hrp);
}
 
Example 15
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("ConstantConditions")
@Test
public void keyRotationHD2() throws Exception {
    // Check we handle the following scenario: a weak random key is created, then some good random keys are created
    // but the weakness of the first isn't known yet. The wallet is upgraded to HD based on the weak key. Later, we
    // find out about the weakness and set the rotation time to after the bad key's creation date. A new HD chain
    // should be created based on the oldest known good key and the old chain + bad random key should rotate to it.

    // We fix the private keys just to make the test deterministic (last byte differs).
    Utils.setMockClock();
    ECKey badKey = ECKey.fromPrivate(Utils.HEX.decode("00905b93f990267f4104f316261fc10f9f983551f9ef160854f40102eb71cffdbb"));
    badKey.setCreationTimeSeconds(Utils.currentTimeSeconds());
    Utils.rollMockClock(86400);
    ECKey goodKey = ECKey.fromPrivate(Utils.HEX.decode("00905b93f990267f4104f316261fc10f9f983551f9ef160854f40102eb71cffdcc"));
    goodKey.setCreationTimeSeconds(Utils.currentTimeSeconds());

    // Do an upgrade based on the bad key.
    final AtomicReference<List<DeterministicKeyChain>> fChains = new AtomicReference<>();
    KeyChainGroup kcg = new KeyChainGroup(PARAMS) {

        {
            fChains.set(chains);
        }
    };
    kcg.importKeys(badKey, goodKey);
    Utils.rollMockClock(86400);
    wallet = new Wallet(PARAMS, kcg);   // This avoids the automatic HD initialisation
    assertTrue(fChains.get().isEmpty());
    wallet.upgradeToDeterministic(null);
    DeterministicKey badWatchingKey = wallet.getWatchingKey();
    assertEquals(badKey.getCreationTimeSeconds(), badWatchingKey.getCreationTimeSeconds());
    sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, badWatchingKey.toAddress(PARAMS));

    // Now we set the rotation time to the time we started making good keys. This should create a new HD chain.
    wallet.setKeyRotationTime(goodKey.getCreationTimeSeconds());
    List<Transaction> txns = wallet.doMaintenance(null, false).get();
    assertEquals(1, txns.size());
    Address output = txns.get(0).getOutput(0).getAddressFromP2PKHScript(PARAMS);
    ECKey usedKey = wallet.findKeyFromPubHash(output.getHash160());
    assertEquals(goodKey.getCreationTimeSeconds(), usedKey.getCreationTimeSeconds());
    assertEquals(goodKey.getCreationTimeSeconds(), wallet.freshReceiveKey().getCreationTimeSeconds());
    assertEquals("mrM3TpCnav5YQuVA1xLercCGJH4DXujMtv", usedKey.toAddress(PARAMS).toString());
    DeterministicKeyChain c = fChains.get().get(1);
    assertEquals(c.getEarliestKeyCreationTime(), goodKey.getCreationTimeSeconds());
    assertEquals(2, fChains.get().size());

    // Commit the maint txns.
    wallet.commitTx(txns.get(0));

    // Check next maintenance does nothing.
    assertTrue(wallet.doMaintenance(null, false).get().isEmpty());
    assertEquals(c, fChains.get().get(1));
    assertEquals(2, fChains.get().size());
}
 
Example 16
Source File: AbstractScriptBuilderWithVar.java    From balzac with Apache License 2.0 4 votes vote down vote up
/**
 * Replace all the signatures placeholder with the actual signatures. Each
 * placeholder is already associated with the key and the modifiers.
 * 
 * @param tx         the transaction to be signed
 * @param inputIndex the index of the input that will contain this script
 * @param outScript  the redeemed output script
 * @return a <b>copy</b> of this builder
 * @throws KeyStoreException if an error occurs retrieving private keys
 */
@SuppressWarnings("unchecked")
public T setAllSignatures(ECKeyStore keystore, Transaction tx, int inputIndex, byte[] outScript, boolean isP2PKH)
    throws KeyStoreException {

    List<ScriptChunk> newChunks = new ArrayList<>();

    for (ScriptChunk chunk : getChunks()) {

        ScriptBuilderWithVar sb = new ScriptBuilderWithVar();
        if (isSignature(chunk)) {
            String mapKey = getMapKey(chunk);
            SignatureUtil sig = this.signatures.get(mapKey);

            // check if the private key is a variable
            String keyID = sig.keyID;
            if (keyID.startsWith(FREEVAR_PREFIX)) {
                // check that the variable is bound
                String varName = keyID.substring(FREEVAR_PREFIX.length());
                checkState(isBound(varName), "variable " + varName + " must be bound to retrieve the key");
                keyID = getValue(varName, String.class);
            }

            checkState(keystore != null, "keystore must be set to retrieve the private keys");
            checkState(keystore.containsKey(keyID), "key " + keyID + " not found on the specified keystore");

            PrivateKey privkey = keystore.getKey(keyID);
            ECKey key = ECKey.fromPrivate(privkey.getBytes());
            SigHash hashType = sig.hashType;
            boolean anyoneCanPay = sig.anyoneCanPay;

            // create the signature
            TransactionSignature txSig = tx.calculateSignature(inputIndex, key, outScript, hashType, anyoneCanPay);
            Sha256Hash hash = tx.hashForSignature(inputIndex, outScript, (byte) txSig.sighashFlags);
            boolean isValid = ECKey.verify(hash.getBytes(), txSig, privkey.toPublicKey().getBytes());
            checkState(isValid);
            checkState(txSig.isCanonical());
            sb.data(txSig.encodeToBitcoin());
            if (isP2PKH) {
                sb.data(privkey.toPublicKey().getBytes());
            }
        }
        else {
            sb.addChunk(chunk);
        }

        newChunks.addAll(sb.getChunks());
    }
    super.getChunks().clear();
    super.getChunks().addAll(newChunks);

    this.signatures.clear();
    return (T) this;
}
 
Example 17
Source File: IdentityKeystore.java    From token-core-android with Apache License 2.0 4 votes vote down vote up
public IdentityKeystore(Metadata metadata, List<String> mnemonicCodes, String password) {
  MnemonicUtil.validateMnemonics(mnemonicCodes);

  DeterministicSeed seed = new DeterministicSeed(mnemonicCodes, null, "", 0L);

  DeterministicKey masterPrivateKey = HDKeyDerivation.createMasterPrivateKey(seed.getSeedBytes());
  byte[] masterKey = masterPrivateKey.getPrivKeyBytes();

  String salt = metadata.isMainNet() ? "Automatic Backup Key Mainnet" : "Automatic Backup Key Testnet";
  byte[] backupKey = Hash.hmacSHA256(masterKey, salt.getBytes(Charset.forName("ASCII")));
  byte[] authenticationKey = Hash.hmacSHA256(backupKey, "Authentication Key".getBytes(Charset.forName("UTF-8")));
  ECKey authKey = ECKey.fromPrivate(authenticationKey);

  NetworkParameters networkParameters = metadata.isMainNet() ? MainNetParams.get() : TestNet3Params.get();

  String aPubHashHex = NumericUtil.bytesToHex(authKey.getPubKeyHash());
  int networkHeader = networkParameters.getAddressHeader();
  int version = 2;
  // this magic hex will start with 'im' after base58check
  String magicHex = "0fdc0c";
  String fullIdentifier = String.format("%s%02x%02x%s", magicHex, (byte) networkHeader, (byte) version, aPubHashHex);
  byte[] fullIdentifierBytes = NumericUtil.hexToBytes(fullIdentifier);
  byte[] checksumBytes = Arrays.copyOfRange(Sha256Hash.hashTwice(fullIdentifierBytes), 0, 4);
  byte[] identifierWithChecksum = ByteUtil.concat(fullIdentifierBytes, checksumBytes);
  this.identifier = Base58.encode(identifierWithChecksum);

  byte[] encKeyFullBytes = Hash.hmacSHA256(backupKey, "Encryption Key".getBytes(Charset.forName("UTF-8")));
  this.encKey = NumericUtil.bytesToHex(encKeyFullBytes);

  ECKey ecKey = ECKey.fromPrivate(encKeyFullBytes, false);
  this.ipfsId = new Multihash(Multihash.Type.sha2_256, Hash.sha256(ecKey.getPubKey())).toBase58();
  Crypto crypto = Crypto.createPBKDF2CryptoWithKDFCached(password, masterPrivateKey.serializePrivB58(networkParameters).getBytes(Charset.forName("UTF-8")));

  this.encAuthKey = crypto.deriveEncPair(password, authenticationKey);
  this.encMnemonic = crypto.deriveEncPair(password, Joiner.on(" ").join(mnemonicCodes).getBytes());
  crypto.clearCachedDerivedKey();
  metadata.setTimestamp(DateUtil.getUTCTime());

  metadata.setSegWit(null);
  this.metadata = metadata;
  this.crypto = crypto;

  this.version = VERSION;
  this.walletIDs = new ArrayList<>();
}
 
Example 18
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();
  }

}
 
Example 19
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("ConstantConditions")
@Test
public void keyRotationHD2() throws Exception {
    // Check we handle the following scenario: a weak random key is created, then some good random keys are created
    // but the weakness of the first isn't known yet. The wallet is upgraded to HD based on the weak key. Later, we
    // find out about the weakness and set the rotation time to after the bad key's creation date. A new HD chain
    // should be created based on the oldest known good key and the old chain + bad random key should rotate to it.

    // We fix the private keys just to make the test deterministic (last byte differs).
    Utils.setMockClock();
    ECKey badKey = ECKey.fromPrivate(Utils.HEX.decode("00905b93f990267f4104f316261fc10f9f983551f9ef160854f40102eb71cffdbb"));
    badKey.setCreationTimeSeconds(Utils.currentTimeSeconds());
    Utils.rollMockClock(86400);
    ECKey goodKey = ECKey.fromPrivate(Utils.HEX.decode("00905b93f990267f4104f316261fc10f9f983551f9ef160854f40102eb71cffdcc"));
    goodKey.setCreationTimeSeconds(Utils.currentTimeSeconds());

    // Do an upgrade based on the bad key.
    final AtomicReference<List<DeterministicKeyChain>> fChains = new AtomicReference<>();
    KeyChainGroup kcg = new KeyChainGroup(PARAMS) {

        {
            fChains.set(chains);
        }
    };
    kcg.importKeys(badKey, goodKey);
    Utils.rollMockClock(86400);
    wallet = new Wallet(PARAMS, kcg);   // This avoids the automatic HD initialisation
    assertTrue(fChains.get().isEmpty());
    wallet.upgradeToDeterministic(null);
    DeterministicKey badWatchingKey = wallet.getWatchingKey();
    assertEquals(badKey.getCreationTimeSeconds(), badWatchingKey.getCreationTimeSeconds());
    sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, badWatchingKey.toAddress(PARAMS));

    // Now we set the rotation time to the time we started making good keys. This should create a new HD chain.
    wallet.setKeyRotationTime(goodKey.getCreationTimeSeconds());
    List<Transaction> txns = wallet.doMaintenance(null, false).get();
    assertEquals(1, txns.size());
    Address output = txns.get(0).getOutput(0).getAddressFromP2PKHScript(PARAMS);
    ECKey usedKey = wallet.findKeyFromPubHash(output.getHash160());
    assertEquals(goodKey.getCreationTimeSeconds(), usedKey.getCreationTimeSeconds());
    assertEquals(goodKey.getCreationTimeSeconds(), wallet.freshReceiveKey().getCreationTimeSeconds());
    assertEquals("mrM3TpCnav5YQuVA1xLercCGJH4DXujMtv", usedKey.toAddress(PARAMS).toString());
    DeterministicKeyChain c = fChains.get().get(1);
    assertEquals(c.getEarliestKeyCreationTime(), goodKey.getCreationTimeSeconds());
    assertEquals(2, fChains.get().size());

    // Commit the maint txns.
    wallet.commitTx(txns.get(0));

    // Check next maintenance does nothing.
    assertTrue(wallet.doMaintenance(null, false).get().isEmpty());
    assertEquals(c, fChains.get().get(1));
    assertEquals(2, fChains.get().size());
}
 
Example 20
Source File: PreUtils.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static String ECDH(String pub, String priv) {
    ECKey pubKey = ECKey.fromPublicOnly(HexUtil.fromHexString(pub));
    ECKey privKey = ECKey.fromPrivate(HexUtil.fromHexString(priv));

    return HexUtil.toHexString(pubKey.getPubKeyPoint().multiply(privKey.getPrivKey()).getEncoded());
}