コード例 #1
0
 @Test
 public void bloom() throws Exception {
   ECKey key1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
   ECKey key2 = new ECKey();
   BloomFilter filter =
       group.getBloomFilter(
           group.getBloomFilterElementCount(), 0.001, (long) (Math.random() * Long.MAX_VALUE));
   assertTrue(filter.contains(key1.getPubKeyHash()));
   assertTrue(filter.contains(key1.getPubKey()));
   assertFalse(filter.contains(key2.getPubKey()));
   // Check that the filter contains the lookahead buffer and threshold zone.
   for (int i = 0; i < LOOKAHEAD_SIZE + group.getLookaheadThreshold(); i++) {
     ECKey k = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
     assertTrue(filter.contains(k.getPubKeyHash()));
   }
   // We ran ahead of the lookahead buffer.
   assertFalse(filter.contains(group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKey()));
   group.importKeys(key2);
   filter =
       group.getBloomFilter(
           group.getBloomFilterElementCount(), 0.001, (long) (Math.random() * Long.MAX_VALUE));
   assertTrue(filter.contains(key1.getPubKeyHash()));
   assertTrue(filter.contains(key1.getPubKey()));
   assertTrue(filter.contains(key2.getPubKey()));
 }
コード例 #2
0
 @Test
 public void findKey() throws Exception {
   ECKey a = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
   ECKey b = group.freshKey(KeyChain.KeyPurpose.CHANGE);
   ECKey c = new ECKey();
   ECKey d = new ECKey(); // Not imported.
   group.importKeys(c);
   assertTrue(group.hasKey(a));
   assertTrue(group.hasKey(b));
   assertTrue(group.hasKey(c));
   assertFalse(group.hasKey(d));
   ECKey result = group.findKeyFromPubKey(a.getPubKey());
   assertEquals(a, result);
   result = group.findKeyFromPubKey(b.getPubKey());
   assertEquals(b, result);
   result = group.findKeyFromPubHash(a.getPubKeyHash());
   assertEquals(a, result);
   result = group.findKeyFromPubHash(b.getPubKeyHash());
   assertEquals(b, result);
   result = group.findKeyFromPubKey(c.getPubKey());
   assertEquals(c, result);
   result = group.findKeyFromPubHash(c.getPubKeyHash());
   assertEquals(c, result);
   assertNull(group.findKeyFromPubKey(d.getPubKey()));
   assertNull(group.findKeyFromPubHash(d.getPubKeyHash()));
 }
コード例 #3
0
 @Override
 public void showKey(ECKey key, String dir, boolean testnet) throws IOException {
   NetworkParameters params = LotteryTx.getNetworkParameters(testnet);
   writeln("Generated new <public key, secret key> pair" + (testnet ? " (for the testnet)" : ""));
   writeln("They were saved under the " + dir + " directory");
   writeln("The address, public key and the private key are:");
   writeln(key.toAddress(params).toString());
   writeln(Utils.bytesToHexString(key.getPubKey()));
   writeln(key.getPrivateKeyEncoded(params).toString());
 }
コード例 #4
0
 @Test
 public void encryptionWhilstEmpty() throws Exception {
   group = new KeyChainGroup(params);
   group.setLookaheadSize(5);
   KeyCrypterScrypt scrypt = new KeyCrypterScrypt(2);
   final KeyParameter aesKey = scrypt.deriveKey("password");
   group.encrypt(scrypt, aesKey);
   assertTrue(group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).isEncrypted());
   final ECKey key = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
   group.decrypt(aesKey);
   assertFalse(checkNotNull(group.findKeyFromPubKey(key.getPubKey())).isEncrypted());
 }
コード例 #5
0
  @Test
  public void freshCurrentKeys() throws Exception {
    int numKeys =
        ((group.getLookaheadSize() + group.getLookaheadThreshold())
                * 2) // * 2 because of internal/external
            + 1 // keys issued
            + 3 /* account key + int/ext parent keys */;
    assertEquals(numKeys, group.numKeys());
    assertEquals(2 * numKeys, group.getBloomFilterElementCount());
    ECKey r1 = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertEquals(numKeys, group.numKeys());
    assertEquals(2 * numKeys, group.getBloomFilterElementCount());

    ECKey i1 = new ECKey();
    group.importKeys(i1);
    numKeys++;
    assertEquals(numKeys, group.numKeys());
    assertEquals(2 * numKeys, group.getBloomFilterElementCount());

    ECKey r2 = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertEquals(r1, r2);
    ECKey c1 = group.currentKey(KeyChain.KeyPurpose.CHANGE);
    assertNotEquals(r1, c1);
    ECKey r3 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertNotEquals(r1, r3);
    ECKey c2 = group.freshKey(KeyChain.KeyPurpose.CHANGE);
    assertNotEquals(r3, c2);
    // Current key has not moved and will not under marked as used.
    ECKey r4 = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertEquals(r2, r4);
    ECKey c3 = group.currentKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals(c1, c3);
    // Mark as used. Current key is now different.
    group.markPubKeyAsUsed(r4.getPubKey());
    ECKey r5 = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertNotEquals(r4, r5);
  }
コード例 #6
0
  /**
   * Converts the given wallet to the object representation of the protocol buffers. This can be
   * modified, or additional data fields set, before serialization takes place.
   */
  public Protos.Wallet walletToProto(Wallet wallet) {
    Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder();
    walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId());
    if (wallet.getDescription() != null) {
      walletBuilder.setDescription(wallet.getDescription());
    }

    for (WalletTransaction wtx : wallet.getWalletTransactions()) {
      Protos.Transaction txProto = makeTxProto(wtx);
      walletBuilder.addTransaction(txProto);
    }

    for (ECKey key : wallet.getKeys()) {
      Protos.Key.Builder keyBuilder =
          Protos.Key.newBuilder()
              .setCreationTimestamp(key.getCreationTimeSeconds() * 1000)
              // .setLabel() TODO
              .setType(Protos.Key.Type.ORIGINAL);
      if (key.getPrivKeyBytes() != null)
        keyBuilder.setPrivateKey(ByteString.copyFrom(key.getPrivKeyBytes()));

      EncryptedPrivateKey encryptedPrivateKey = key.getEncryptedPrivateKey();
      if (encryptedPrivateKey != null) {
        // Key is encrypted.
        Protos.EncryptedPrivateKey.Builder encryptedKeyBuilder =
            Protos.EncryptedPrivateKey.newBuilder()
                .setEncryptedPrivateKey(
                    ByteString.copyFrom(encryptedPrivateKey.getEncryptedBytes()))
                .setInitialisationVector(
                    ByteString.copyFrom(encryptedPrivateKey.getInitialisationVector()));

        if (key.getKeyCrypter() == null) {
          throw new IllegalStateException(
              "The encrypted key " + key.toString() + " has no KeyCrypter.");
        } else {
          // If it is a Scrypt + AES encrypted key, set the persisted key type.
          if (key.getKeyCrypter().getUnderstoodEncryptionType()
              == Protos.Wallet.EncryptionType.ENCRYPTED_SCRYPT_AES) {
            keyBuilder.setType(Protos.Key.Type.ENCRYPTED_SCRYPT_AES);
          } else {
            throw new IllegalArgumentException(
                "The key "
                    + key.toString()
                    + " is encrypted with a KeyCrypter of type "
                    + key.getKeyCrypter().getUnderstoodEncryptionType()
                    + ". This WalletProtobufSerialiser does not understand that type of encryption.");
          }
        }
        keyBuilder.setEncryptedPrivateKey(encryptedKeyBuilder);
      }

      // We serialize the public key even if the private key is present for speed reasons: we don't
      // want to do
      // lots of slow EC math to load the wallet, we prefer to store the redundant data instead. It
      // matters more
      // on mobile platforms.
      keyBuilder.setPublicKey(ByteString.copyFrom(key.getPubKey()));
      walletBuilder.addKey(keyBuilder);
    }

    // Populate the lastSeenBlockHash field.
    Sha256Hash lastSeenBlockHash = wallet.getLastBlockSeenHash();
    if (lastSeenBlockHash != null) {
      walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash));
      walletBuilder.setLastSeenBlockHeight(wallet.getLastBlockSeenHeight());
    }

    // Populate the scrypt parameters.
    KeyCrypter keyCrypter = wallet.getKeyCrypter();
    if (keyCrypter == null) {
      // The wallet is unencrypted.
      walletBuilder.setEncryptionType(EncryptionType.UNENCRYPTED);
    } else {
      // The wallet is encrypted.
      walletBuilder.setEncryptionType(keyCrypter.getUnderstoodEncryptionType());
      if (keyCrypter instanceof KeyCrypterScrypt) {
        KeyCrypterScrypt keyCrypterScrypt = (KeyCrypterScrypt) keyCrypter;
        walletBuilder.setEncryptionParameters(keyCrypterScrypt.getScryptParameters());
      } else {
        // Some other form of encryption has been specified that we do not know how to persist.
        throw new RuntimeException(
            "The wallet has encryption of type '"
                + keyCrypter.getUnderstoodEncryptionType()
                + "' but this WalletProtobufSerializer does not know how to persist this.");
      }
    }

    populateExtensions(wallet, walletBuilder);

    // Populate the wallet version.
    walletBuilder.setVersion(wallet.getVersion());

    return walletBuilder.build();
  }
コード例 #7
0
  public void encryption(boolean withImported) throws Exception {
    Utils.rollMockClock(0);
    long now = Utils.currentTimeSeconds();
    ECKey a = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertEquals(now, group.getEarliestKeyCreationTime());
    Utils.rollMockClock(-86400);
    long yesterday = Utils.currentTimeSeconds();
    ECKey b = new ECKey();

    assertFalse(group.isEncrypted());
    try {
      group.checkPassword("foo"); // Cannot check password of an unencrypted group.
      fail();
    } catch (IllegalStateException e) {
    }
    if (withImported) {
      assertEquals(now, group.getEarliestKeyCreationTime());
      group.importKeys(b);
      assertEquals(yesterday, group.getEarliestKeyCreationTime());
    }
    KeyCrypterScrypt scrypt = new KeyCrypterScrypt(2);
    final KeyParameter aesKey = scrypt.deriveKey("password");
    group.encrypt(scrypt, aesKey);
    assertTrue(group.isEncrypted());
    assertTrue(group.checkPassword("password"));
    assertFalse(group.checkPassword("wrong password"));
    final ECKey ea = group.findKeyFromPubKey(a.getPubKey());
    assertTrue(checkNotNull(ea).isEncrypted());
    if (withImported) {
      assertTrue(checkNotNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
      assertEquals(yesterday, group.getEarliestKeyCreationTime());
    } else {
      assertEquals(now, group.getEarliestKeyCreationTime());
    }
    try {
      ea.sign(Sha256Hash.ZERO_HASH);
      fail();
    } catch (ECKey.KeyIsEncryptedException e) {
      // Ignored.
    }
    if (withImported) {
      ECKey c = new ECKey();
      try {
        group.importKeys(c);
        fail();
      } catch (KeyCrypterException e) {
      }
      group.importKeysAndEncrypt(ImmutableList.of(c), aesKey);
      ECKey ec = group.findKeyFromPubKey(c.getPubKey());
      try {
        group.importKeysAndEncrypt(ImmutableList.of(ec), aesKey);
        fail();
      } catch (IllegalArgumentException e) {
      }
    }

    try {
      group.decrypt(scrypt.deriveKey("WRONG PASSWORD"));
      fail();
    } catch (KeyCrypterException e) {
    }

    group.decrypt(aesKey);
    assertFalse(group.isEncrypted());
    assertFalse(checkNotNull(group.findKeyFromPubKey(a.getPubKey())).isEncrypted());
    if (withImported) {
      assertFalse(checkNotNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
      assertEquals(yesterday, group.getEarliestKeyCreationTime());
    } else {
      assertEquals(now, group.getEarliestKeyCreationTime());
    }
  }