org.bitcoinj.core.ECKey Java Examples

The following examples show how to use org.bitcoinj.core.ECKey. 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: EOSWalletTest.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
@Test
public void generatePrvPubKey() {

  byte[] prvWIF = Base58.decode(WIF);
  // have omitted the checksum verification
  prvWIF = Arrays.copyOfRange(prvWIF, 1, prvWIF.length - 4);

  // use the privateKey to calculate the compressed public key directly
  ECKey ecKey = ECKey.fromPrivate(new BigInteger(1, prvWIF));
  byte[] pubKeyData = ecKey.getPubKey();
  RIPEMD160Digest digest = new RIPEMD160Digest();
  digest.update(pubKeyData, 0, pubKeyData.length);
  byte[] out = new byte[20];
  digest.doFinal(out, 0);
  byte[] checksumBytes = Arrays.copyOfRange(out, 0, 4);

  pubKeyData = ByteUtil.concat(pubKeyData, checksumBytes);
  String eosPK = "EOS" + Base58.encode(pubKeyData);
  Assert.assertEquals(PUBLIC_KEY, eosPK);
}
 
Example #2
Source File: BasicKeyChain.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Override
public BasicKeyChain toDecrypted(KeyParameter aesKey) {
    lock.lock();
    try {
        checkState(keyCrypter != null, "Wallet is already decrypted");
        // Do an up-front check.
        if (numKeys() > 0 && !checkAESKey(aesKey))
            throw new KeyCrypterException("Password/key was incorrect.");
        BasicKeyChain decrypted = new BasicKeyChain();
        for (ECKey key : hashToKeys.values()) {
            decrypted.importKeyLocked(key.decrypt(aesKey));
        }
        return decrypted;
    } finally {
        lock.unlock();
    }
}
 
Example #3
Source File: PublicKey.java    From evt4j with MIT License 6 votes vote down vote up
@NotNull
@Contract("_ -> new")
private static Pair<Boolean, byte[]> validPublicKey(@NotNull String key) {
    if (key.length() < 8) {
        return new ImmutablePair<>(false, new byte[] {});
    }

    if (!key.startsWith(EVT)) {
        return new ImmutablePair<>(false, new byte[] {});
    }

    // key is invalid when checksum doesn't match
    String keyWithoutPrefix = key.substring(3);
    byte[] publicKeyInBytes;
    try {
        publicKeyInBytes = Utils.base58CheckDecode(keyWithoutPrefix);
    } catch (Base58CheckException ex) {
        return new ImmutablePair<>(false, new byte[] {});
    }

    LazyECPoint pub = new LazyECPoint(ECKey.CURVE.getCurve(), publicKeyInBytes);

    return new ImmutablePair<>(pub.isValid(), publicKeyInBytes);
}
 
Example #4
Source File: BasicKeyChain.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public BasicKeyChain toDecrypted(KeyParameter aesKey) {
    lock.lock();
    try {
        checkState(keyCrypter != null, "Wallet is already decrypted");
        // Do an up-front check.
        if (numKeys() > 0 && !checkAESKey(aesKey))
            throw new KeyCrypterException("Password/key was incorrect.");
        BasicKeyChain decrypted = new BasicKeyChain();
        for (ECKey key : hashToKeys.values()) {
            decrypted.importKeyLocked(key.decrypt(aesKey));
        }
        return decrypted;
    } finally {
        lock.unlock();
    }
}
 
Example #5
Source File: DefaultRiskAnalysis.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/** Checks if the given input passes some of the AreInputsStandard checks. Not complete. */
public static RuleViolation isInputStandard(TransactionInput input) {
    for (ScriptChunk chunk : input.getScriptSig().getChunks()) {
        if (chunk.data != null && !chunk.isShortestPossiblePushData())
            return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
        if (chunk.isPushData()) {
            ECDSASignature signature;
            try {
                signature = ECKey.ECDSASignature.decodeFromDER(chunk.data);
            } catch (RuntimeException x) {
                // Doesn't look like a signature.
                signature = null;
            }
            if (signature != null) {
                if (!TransactionSignature.isEncodingCanonical(chunk.data))
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
                if (!signature.isCanonical())
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
            }
        }
    }
    return RuleViolation.NONE;
}
 
Example #6
Source File: BisqRiskAnalysis.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
/** Checks if the given input passes some of the AreInputsStandard checks. Not complete. */
public static RuleViolation isInputStandard(TransactionInput input) {
    for (ScriptChunk chunk : input.getScriptSig().getChunks()) {
        if (chunk.data != null && !chunk.isShortestPossiblePushData())
            return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
        if (chunk.isPushData()) {
            ECDSASignature signature;
            try {
                signature = ECKey.ECDSASignature.decodeFromDER(chunk.data);
            } catch (RuntimeException x) {
                // Doesn't look like a signature.
                signature = null;
            }
            if (signature != null) {
                if (!TransactionSignature.isEncodingCanonical(chunk.data))
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
                if (!signature.isCanonical())
                    return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
            }
        }
    }
    return RuleViolation.NONE;
}
 
Example #7
Source File: BasicKeyChain.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/** Returns the first ECKey created after the given UNIX time, or null if there is none. */
@Nullable
public ECKey findOldestKeyAfter(long timeSecs) {
    lock.lock();
    try {
        ECKey oldest = null;
        for (ECKey key : hashToKeys.values()) {
            final long keyTime = key.getCreationTimeSeconds();
            if (keyTime > timeSecs) {
                if (oldest == null || oldest.getCreationTimeSeconds() > keyTime)
                    oldest = key;
            }
        }
        return oldest;
    } finally {
        lock.unlock();
    }
}
 
Example #8
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void upgradeToHDUnencrypted() throws Exception {
    // This isn't very deep because most of it is tested in KeyChainGroupTest and Wallet just forwards most logic
    // there. We're mostly concerned with the slightly different auto upgrade logic: KeyChainGroup won't do an
    // on-demand auto upgrade of the wallet to HD even in the unencrypted case, because the key rotation time is
    // a property of the Wallet, not the KeyChainGroup (it should perhaps be moved at some point - it doesn't matter
    // much where it goes). Wallet on the other hand will try to auto-upgrade you when possible.

    // Create an old-style random wallet.
    KeyChainGroup group = new KeyChainGroup(PARAMS);
    group.importKeys(new ECKey(), new ECKey());
    wallet = new Wallet(PARAMS, group);
    assertTrue(wallet.isDeterministicUpgradeRequired());
    // Use an HD feature.
    wallet.freshReceiveKey();
    assertFalse(wallet.isDeterministicUpgradeRequired());
}
 
Example #9
Source File: PrivateKeyValidator.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
@Override
public String validate() {
  try {
    // validating private key
    BigInteger pkNum = NumericUtil.hexToBigInteger(privateKey);
    if (NumericUtil.hexToBytes(this.privateKey).length != 32
        || pkNum.compareTo((ECKey.CURVE.getN().subtract(BigInteger.ONE))) >= 0
        || pkNum.compareTo(BigInteger.ONE) <= 0) {
      throw new TokenException(Messages.PRIVATE_KEY_INVALID);
    }

    // validating public key
    byte[] pubKeyBytes = ECKey.fromPrivate(pkNum).getPubKey();
    BigInteger pubKeyNum = new BigInteger(1, pubKeyBytes);
    if (pubKeyNum.compareTo(BigInteger.ZERO) == 0) {
      throw new TokenException(Messages.PRIVATE_KEY_INVALID);
    }
  } catch (Exception ex) {
    throw new TokenException(Messages.PRIVATE_KEY_INVALID);
  }
  return this.privateKey;
}
 
Example #10
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void pubkeyOnlyScripts() throws Exception {
    // Verify that we support outputs like OP_PUBKEY and the corresponding inputs.
    ECKey key1 = wallet.freshReceiveKey();
    Coin value = valueOf(5, 0);
    Transaction t1 = createFakeTx(PARAMS, value, key1);
    if (wallet.isPendingTransactionRelevant(t1))
        wallet.receivePending(t1, null);
    // TX should have been seen as relevant.
    assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
    assertEquals(ZERO, wallet.getBalance(Wallet.BalanceType.AVAILABLE));
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t1);
    // TX should have been seen as relevant, extracted and processed.
    assertEquals(value, wallet.getBalance(Wallet.BalanceType.AVAILABLE));
    // Spend it and ensure we can spend the <key> OP_CHECKSIG output correctly.
    Transaction t2 = wallet.createSend(OTHER_ADDRESS, value);
    assertNotNull(t2);
    // TODO: This code is messy, improve the Script class and fixinate!
    assertEquals(t2.toString(), 1, t2.getInputs().get(0).getScriptSig().getChunks().size());
    assertTrue(t2.getInputs().get(0).getScriptSig().getChunks().get(0).data.length > 50);
}
 
Example #11
Source File: EOSSign.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
private static SignatureData signAsRecoverable(byte[] value, ECKey ecKey) {
  int recId = -1;
  ECKey.ECDSASignature sig = eosSign(value, ecKey.getPrivKey());
  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 TokenException("Could not construct a recoverable key. This should never happen.");
  }
  int headerByte = recId + 27 + 4;
  // 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 #12
Source File: BasicKeyChainTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void serializationUnencrypted() throws UnreadableWalletException {
    Utils.setMockClock();
    Date now = Utils.now();
    final ECKey key1 = new ECKey();
    Utils.rollMockClock(5000);
    final ECKey key2 = new ECKey();
    chain.importKeys(ImmutableList.of(key1, key2));
    List<Protos.Key> keys = chain.serializeToProtobuf();
    assertEquals(2, keys.size());
    assertArrayEquals(key1.getPubKey(), keys.get(0).getPublicKey().toByteArray());
    assertArrayEquals(key2.getPubKey(), keys.get(1).getPublicKey().toByteArray());
    assertArrayEquals(key1.getPrivKeyBytes(), keys.get(0).getSecretBytes().toByteArray());
    assertArrayEquals(key2.getPrivKeyBytes(), keys.get(1).getSecretBytes().toByteArray());
    long normTime = (long) (Math.floor(now.getTime() / 1000) * 1000);
    assertEquals(normTime, keys.get(0).getCreationTimestamp());
    assertEquals(normTime + 5000 * 1000, keys.get(1).getCreationTimestamp());

    chain = BasicKeyChain.fromProtobufUnencrypted(keys);
    assertEquals(2, chain.getKeys().size());
    assertEquals(key1, chain.getKeys().get(0));
    assertEquals(key2, chain.getKeys().get(1));
}
 
Example #13
Source File: BasicKeyChain.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a list of all ECKeys created after the given UNIX time.
 */
public List<ECKey> findKeysBefore(long timeSecs) {
    lock.lock();
    try {
        List<ECKey> results = Lists.newLinkedList();
        for (ECKey key : hashToKeys.values()) {
            final long keyTime = key.getCreationTimeSeconds();
            if (keyTime < timeSecs) {
                results.add(key);
            }
        }
        return results;
    } finally {
        lock.unlock();
    }
}
 
Example #14
Source File: BasicKeyChain.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Encrypt the wallet using the KeyCrypter and the AES key. A good default KeyCrypter to use is
 * {@link KeyCrypterScrypt}.
 *
 * @param keyCrypter The KeyCrypter that specifies how to encrypt/ decrypt a key
 * @param aesKey     AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming
 *                   to create from a password)
 * @throws KeyCrypterException Thrown if the wallet encryption fails. If so, the wallet state is unchanged.
 */
@Override
public BasicKeyChain toEncrypted(KeyCrypter keyCrypter, KeyParameter aesKey) {
    lock.lock();
    try {
        checkNotNull(keyCrypter);
        checkState(this.keyCrypter == null, "Key chain is already encrypted");
        BasicKeyChain encrypted = new BasicKeyChain(keyCrypter);
        for (ECKey key : hashToKeys.values()) {
            ECKey encryptedKey = key.encrypt(keyCrypter, aesKey);
            // Check that the encrypted key can be successfully decrypted.
            // This is done as it is a critical failure if the private key cannot be decrypted successfully
            // (all bitcoin controlled by that private key is lost forever).
            // For a correctly constructed keyCrypter the encryption should always be reversible so it is just
            // being as cautious as possible.
            if (!ECKey.encryptionIsReversible(key, encryptedKey, keyCrypter, aesKey))
                throw new KeyCrypterException("The key " + key.toString() + " cannot be successfully decrypted after encryption so aborting wallet encryption.");
            encrypted.importKeyLocked(encryptedKey);
        }
        return encrypted;
    } finally {
        lock.unlock();
    }
}
 
Example #15
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void watchingScriptsBloomFilter() throws Exception {
    assertFalse(wallet.isRequiringUpdateAllBloomFilter());

    Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
    Transaction t1 = createFakeTx(UNITTEST, CENT, watchedAddress);
    TransactionOutPoint outPoint = new TransactionOutPoint(UNITTEST, 0, t1);
    wallet.addWatchedAddress(watchedAddress);

    assertTrue(wallet.isRequiringUpdateAllBloomFilter());
    // Note that this has a 1e-12 chance of failing this unit test due to a false positive
    assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));

    sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
    assertTrue(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));
}
 
Example #16
Source File: ECDH.java    From thunder with GNU Affero General Public License v3.0 6 votes vote down vote up
public static ECDHKeySet getSharedSecret (ECKey keyServer, ECKey keyClient) {
    try {

        ECPrivateKeySpec specPrivate = new ECPrivateKeySpec(keyServer.getPrivKey(), ecParameters);
        ECPublicKeySpec specPublic = new ECPublicKeySpec(new ECPoint(keyClient.getPubKeyPoint().getXCoord().toBigInteger(), keyClient.getPubKeyPoint()
                .getYCoord().toBigInteger()), ecParameters);

        ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(specPrivate);
        ECPublicKey publicKey = (ECPublicKey) kf.generatePublic(specPublic);

        JCEECPrivateKey ecPrivKey = new JCEECPrivateKey(privateKey);
        JCEECPublicKey ecPubKey = new JCEECPublicKey(publicKey);

        KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH");
        aKeyAgree.init(ecPrivKey);
        aKeyAgree.doPhase(ecPubKey, true);

        return new ECDHKeySet(aKeyAgree.generateSecret(), keyServer.getPubKey(), keyClient.getPubKey());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: TransactionsHelper.java    From smartcoins-wallet with MIT License 6 votes vote down vote up
private void decodeAllMemosInTransactionsReceived(final List<JSONObject> memosArray) {
        ECKey toKey;
        toKey = ECKey.fromPrivate(DumpedPrivateKey.fromBase58(null, wifkey).getKey().getPrivKeyBytes());

        for (JSONObject memoObject : memosArray) {
            try {
                String message = memoObject.get("message").toString();
                PublicKey fromKey = new Address(memoObject.get("from").toString()).getPublicKey();
                String nonce = memoObject.get("nonce").toString();
//                if (memosToDecodeHm.containsKey(memoObject)) {
//                    memosToDecodeHm.put(memoObject, Memo.decodeMessage(fromKey, toKey, message, nonce));
//                }
                decodingMemosComplete();

            } catch (JSONException | MalformedAddressException e) {
                e.printStackTrace();
            }
        }
    }
 
Example #18
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void upgradeToHDEncrypted() throws Exception {
    // Create an old-style random wallet.
    KeyChainGroup group = new KeyChainGroup(UNITTEST);
    group.importKeys(new ECKey(), new ECKey());
    wallet = new Wallet(UNITTEST, group);
    assertTrue(wallet.isDeterministicUpgradeRequired());
    KeyCrypter crypter = new KeyCrypterScrypt();
    KeyParameter aesKey = crypter.deriveKey("abc");
    wallet.encrypt(crypter, aesKey);
    try {
        wallet.freshReceiveKey();
    } catch (DeterministicUpgradeRequiresPassword e) {
        // Expected.
    }
    wallet.upgradeToDeterministic(aesKey);
    assertFalse(wallet.isDeterministicUpgradeRequired());
    wallet.freshReceiveKey();  // works.
}
 
Example #19
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void autosaveImmediate() throws Exception {
    // Test that the wallet will save itself automatically when it changes.
    File f = File.createTempFile("bitcoinj-unit-test", null);
    Sha256Hash hash1 = Sha256Hash.of(f);
    // Start with zero delay and ensure the wallet file changes after adding a key.
    wallet.autosaveToFile(f, 0, TimeUnit.SECONDS, null);
    ECKey key = wallet.freshReceiveKey();
    Sha256Hash hash2 = Sha256Hash.of(f);
    assertFalse("Wallet not saved after generating fresh key", hash1.equals(hash2));  // File has changed.

    Transaction t1 = createFakeTx(PARAMS, valueOf(5, 0), key);
    if (wallet.isPendingTransactionRelevant(t1))
        wallet.receivePending(t1, null);
    Sha256Hash hash3 = Sha256Hash.of(f);
    assertFalse("Wallet not saved after receivePending", hash2.equals(hash3));  // File has changed again.
}
 
Example #20
Source File: BasicKeyChain.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Imports a key to the key chain. If key is present in the key chain, ignore it.
 */
public void importKey(ECKey key) {
    lock.lock();
    try {
        checkKeyEncryptionStateMatches(key);
        if (hasKey(key)) return;
        importKeyLocked(key);
        queueOnKeysAdded(ImmutableList.of(key));
    } finally {
        lock.unlock();
    }
}
 
Example #21
Source File: BasicKeyChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public long getEarliestKeyCreationTime() {
    lock.lock();
    try {
        long time = Long.MAX_VALUE;
        for (ECKey key : hashToKeys.values())
            time = Math.min(key.getCreationTimeSeconds(), time);
        return time;
    } finally {
        lock.unlock();
    }
}
 
Example #22
Source File: BIP38PrivateKeyTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void bip38testvector_ecMultiply_noCompression_lotAndSequence_test1() throws Exception {
    BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(),
            "6PgNBNNzDkKdhkT6uJntUXwwzQV8Rr2tZcbkDcuC9DZRsS6AtHts4Ypo1j");
    ECKey key = encryptedKey.decrypt("MOLON LABE");
    assertEquals("5JLdxTtcTHcfYcmJsNVy1v2PMDx432JPoYcBTVVRHpPaxUrdtf8", key.getPrivateKeyEncoded(MAINNET)
            .toString());
}
 
Example #23
Source File: RedeemData.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the first key that has private bytes
 */
public ECKey getFullKey() {
    for (ECKey key : keys)
        if (key.hasPrivKey())
            return key;
    return null;
}
 
Example #24
Source File: KeycardTest.java    From status-keycard with Apache License 2.0 5 votes vote down vote up
private void verifyExportedKey(byte[] keyTemplate, KeyPair keyPair, byte[] chainCode, int[] path, boolean publicOnly, boolean noPubKey) {
  if (!cmdSet.getApplicationInfo().hasKeyManagementCapability()) {
    return;
  }

  ECKey key = deriveKey(keyPair, chainCode, path).decompress();
  assertEquals(KeycardApplet.TLV_KEY_TEMPLATE, keyTemplate[0]);
  int pubKeyLen = 0;

  if (!noPubKey) {
    assertEquals(KeycardApplet.TLV_PUB_KEY, keyTemplate[2]);
    byte[] pubKey = Arrays.copyOfRange(keyTemplate, 4, 4 + keyTemplate[3]);
    assertArrayEquals(key.getPubKey(), pubKey);
    pubKeyLen = 2 + pubKey.length;
  }

  if (publicOnly) {
    assertEquals(pubKeyLen, keyTemplate[1]);
    assertEquals(pubKeyLen + 2, keyTemplate.length);
  } else {
    assertEquals(KeycardApplet.TLV_PRIV_KEY, keyTemplate[2 + pubKeyLen]);
    byte[] privateKey = Arrays.copyOfRange(keyTemplate, 4 + pubKeyLen, 4 + pubKeyLen + keyTemplate[3 + pubKeyLen]);

    byte[] tPrivKey = key.getPrivKey().toByteArray();

    if (tPrivKey[0] == 0x00) {
      tPrivKey = Arrays.copyOfRange(tPrivKey, 1, tPrivKey.length);
    }

    assertArrayEquals(tPrivKey, privateKey);
  }
}
 
Example #25
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 #26
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void importAndEncrypt() throws InsufficientMoneyException {
    Wallet encryptedWallet = new Wallet(PARAMS);
    encryptedWallet.encrypt(PASSWORD1);

    final ECKey key = new ECKey();
    encryptedWallet.importKeysAndEncrypt(ImmutableList.of(key), PASSWORD1);
    assertEquals(1, encryptedWallet.getImportedKeys().size());
    assertEquals(key.getPubKeyPoint(), encryptedWallet.getImportedKeys().get(0).getPubKeyPoint());
    sendMoneyToWallet(encryptedWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN, key.toAddress(PARAMS));
    assertEquals(Coin.COIN, encryptedWallet.getBalance());
    SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
    req.aesKey = checkNotNull(encryptedWallet.getKeyCrypter()).deriveKey(PASSWORD1);
    encryptedWallet.sendCoinsOffline(req);
}
 
Example #27
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void sendRequestP2PKTest() {
    ECKey key = new ECKey();
    SendRequest req = SendRequest.to(UNITTEST, key, SATOSHI.multiply(12));
    assertArrayEquals(key.getPubKey(),
            ScriptPattern.extractKeyFromPayToPubKey(req.tx.getOutputs().get(0).getScriptPubKey()));
}
 
Example #28
Source File: RedeemData.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the first key that has private bytes
 */
public ECKey getFullKey() {
    for (ECKey key : keys)
        if (key.hasPrivKey())
            return key;
    return null;
}
 
Example #29
Source File: DeterministicKeyChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns only the external keys that have been issued by this chain, lookahead not included.
 */
public List<ECKey> getIssuedReceiveKeys() {
    final List<ECKey> keys = new ArrayList<>(getKeys(false, false));
    for (Iterator<ECKey> i = keys.iterator(); i.hasNext();) {
        DeterministicKey parent = ((DeterministicKey) i.next()).getParent();
        if (parent == null || !externalParentKey.equals(parent))
            i.remove();
    }
    return keys;
}
 
Example #30
Source File: BIP38PrivateKeyTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void bip38testvector_compression_noEcMultiply_test1() throws Exception {
    BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(),
            "6PYNKZ1EAgYgmQfmNVamxyXVWHzK5s6DGhwP4J5o44cvXdoY7sRzhtpUeo");
    ECKey key = encryptedKey.decrypt("TestingOneTwoThree");
    assertEquals("L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP", key.getPrivateKeyEncoded(MAINNET)
            .toString());
}