Java Code Examples for org.bitcoinj.core.Utils

The following examples show how to use org.bitcoinj.core.Utils. These examples are extracted from open source projects. 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 Project: bcm-android   Source File: MnemonicCode.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Convert mnemonic word list to seed.
 */
public static byte[] toSeed(List<String> words, String passphrase) {
    checkNotNull(passphrase, "A null passphrase is not allowed.");

    // To create binary seed from mnemonic, we use PBKDF2 function
    // with mnemonic sentence (in UTF-8) used as a password and
    // string "mnemonic" + passphrase (again in UTF-8) used as a
    // salt. Iteration count is set to 4096 and HMAC-SHA512 is
    // used as a pseudo-random function. Desired length of the
    // derived key is 512 bits (= 64 bytes).
    //
    String pass = Utils.SPACE_JOINER.join(words);
    String salt = "mnemonic" + passphrase;

    final Stopwatch watch = Stopwatch.createStarted();
    byte[] seed = PBKDF2SHA512.derive(pass, salt, PBKDF2_ROUNDS, 64);
    watch.stop();
    log.info("PBKDF2 took {}", watch);
    return seed;
}
 
Example 2
public String toString(boolean includePrivateKeys, @Nullable KeyParameter aesKey, NetworkParameters params) {
    final DeterministicKey watchingKey = getWatchingKey();
    final StringBuilder builder = new StringBuilder();
    if (seed != null) {
        if (includePrivateKeys) {
            DeterministicSeed decryptedSeed = seed.isEncrypted()
                    ? seed.decrypt(getKeyCrypter(), DEFAULT_PASSPHRASE_FOR_MNEMONIC, aesKey) : seed;
            final List<String> words = decryptedSeed.getMnemonicCode();
            builder.append("Seed as words: ").append(Utils.SPACE_JOINER.join(words)).append('\n');
            builder.append("Seed as hex:   ").append(decryptedSeed.toHexString()).append('\n');
        } else {
            if (seed.isEncrypted())
                builder.append("Seed is encrypted\n");
        }
        builder.append("Seed birthday: ").append(seed.getCreationTimeSeconds()).append("  [")
                .append(Utils.dateTimeFormat(seed.getCreationTimeSeconds() * 1000)).append("]\n");
    } else {
        builder.append("Key birthday:  ").append(watchingKey.getCreationTimeSeconds()).append("  [")
                .append(Utils.dateTimeFormat(watchingKey.getCreationTimeSeconds() * 1000)).append("]\n");
    }
    builder.append("Key to watch:  ").append(watchingKey.serializePubB58(params)).append('\n');
    formatAddresses(includePrivateKeys, aesKey, params, builder);
    return builder.toString();
}
 
Example 3
@Test
public void shouldAllowExactTimeWindow() {
    final TwoWayChannelMessage message = createClientVersionMessage();
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
    connection.sendToClient(capture(initiateCapture));
    replay(connection);
    final int expire = 24 * 60 * 60 - 60;  // This the default defined in paymentchannel.proto

    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, new PaymentChannelServer.DefaultServerChannelProperties(){
        @Override
        public long getMaxTimeWindow() { return expire; }
        @Override
        public long getMinTimeWindow() { return expire; }
    }, connection);
    dut.connectionOpen();
    long expectedExpire = Utils.currentTimeSeconds() + expire;
    dut.receiveMessage(message);

    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
Example 4
@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 5
@Test
public void shouldAllowExactTimeWindow() {
    final TwoWayChannelMessage message = createClientVersionMessage();
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
    connection.sendToClient(capture(initiateCapture));
    replay(connection);
    final int expire = 24 * 60 * 60 - 60;  // This the default defined in paymentchannel.proto

    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, new PaymentChannelServer.DefaultServerChannelProperties() {
        @Override
        public long getMaxTimeWindow() {
            return expire;
        }

        @Override
        public long getMinTimeWindow() {
            return expire;
        }
    }, connection);
    dut.connectionOpen();
    long expectedExpire = Utils.currentTimeSeconds() + expire;
    dut.receiveMessage(message);

    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
Example 6
Source Project: GreenBits   Source File: MnemonicCode.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Convert mnemonic word list to seed.
 */
public static byte[] toSeed(List<String> words, String passphrase) {

    // To create binary seed from mnemonic, we use PBKDF2 function
    // with mnemonic sentence (in UTF-8) used as a password and
    // string "mnemonic" + passphrase (again in UTF-8) used as a
    // salt. Iteration count is set to 4096 and HMAC-SHA512 is
    // used as a pseudo-random function. Desired length of the
    // derived key is 512 bits (= 64 bytes).
    //
    String pass = Utils.join(words);
    String salt = "mnemonic" + passphrase;

    final Stopwatch watch = Stopwatch.createStarted();
    byte[] seed = PBKDF2SHA512.derive(pass, salt, PBKDF2_ROUNDS, 64);
    watch.stop();
    log.info("PBKDF2 took {}", watch);
    return seed;
}
 
Example 7
Source Project: GreenBits   Source File: MnemonicCodeTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testVectors() throws Exception {
    for (int ii = 0; ii < vectors.length; ii += 3) {
        String vecData = vectors[ii];
        String vecCode = vectors[ii+1];
        String vecSeed = vectors[ii+2];

        List<String> code = mc.toMnemonic(HEX.decode(vecData));
        byte[] seed = MnemonicCode.toSeed(code, "TREZOR");
        byte[] entropy = mc.toEntropy(split(vecCode));

        assertEquals(vecData, HEX.encode(entropy));
        assertEquals(vecCode, Utils.join(code));
        assertEquals(vecSeed, HEX.encode(seed));
    }
}
 
Example 8
@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 9
@Test
public void keysBeforeAndAfter() throws Exception {
    Utils.setMockClock();
    long now = Utils.currentTimeSeconds();
    final ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    final ECKey key2 = new ECKey();
    final List<ECKey> keys = Lists.newArrayList(key1, key2);
    assertEquals(2, chain.importKeys(keys));

    assertNull(chain.findOldestKeyAfter(now + 86400 * 2));
    assertEquals(key1, chain.findOldestKeyAfter(now - 1));
    assertEquals(key2, chain.findOldestKeyAfter(now + 86400 - 1));

    assertEquals(2, chain.findKeysBefore(now + 86400 * 2).size());
    assertEquals(1, chain.findKeysBefore(now + 1).size());
    assertEquals(0, chain.findKeysBefore(now - 1).size());
}
 
Example 10
@Test
public void deterministicUpgradeRotating() throws Exception {
    group = new KeyChainGroup(MAINNET);
    group.setLookaheadSize(LOOKAHEAD_SIZE);   // Don't want slow tests.
    long now = Utils.currentTimeSeconds();
    ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    ECKey key2 = new ECKey();
    Utils.rollMockClock(86400);
    ECKey key3 = new ECKey();
    group.importKeys(key2, key1, key3);
    group.upgradeToDeterministic(now + 10, null);
    DeterministicSeed seed = group.getActiveKeyChain().getSeed();
    assertNotNull(seed);
    // Check we used the right key: oldest non rotating.
    byte[] truncatedBytes = Arrays.copyOfRange(key2.getSecretBytes(), 0, 16);
    assertArrayEquals(seed.getEntropyBytes(), truncatedBytes);
}
 
Example 11
private void addAccountsToSignContent() {
    removeContent();
    addECKeyField();

    headLineLabel.setText(Res.get("popup.accountSigning.signAccounts.headline"));
    descriptionLabel.setText(Res.get("popup.accountSigning.signAccounts.description", selectedPaymentAccountsList.getItems().size()));
    ((AutoTooltipButton) actionButton).updateText(Res.get("popup.accountSigning.signAccounts.button"));
    actionButton.setOnAction(a -> {
        ECKey arbitratorKey = arbitratorManager.getRegistrationKey(privateKey.getText());
        if (arbitratorKey != null) {
            String arbitratorPubKeyAsHex = Utils.HEX.encode(arbitratorKey.getPubKey());
            boolean isKeyValid = arbitratorManager.isPublicKeyInList(arbitratorPubKeyAsHex);
            if (isKeyValid) {
                selectedPaymentAccountsList.getItems().forEach(item ->
                        accountAgeWitnessService.arbitratorSignAccountAgeWitness(item.getTradeAmount(),
                                item.getAccountAgeWitness(),
                                arbitratorKey,
                                item.getPeersPubKey()));
                addSuccessContent();
            }
        } else {
            new Popup().error(Res.get("popup.accountSigning.signAccounts.ECKey.error")).onClose(this::hide).show();
        }

    });
}
 
Example 12
Source Project: GreenBits   Source File: GenerateLowSTests.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Convert a script to a string format that suits the style expected in
 * tx_valid.json and tx_invalid.json.
 */
private static String scriptToString(Script scriptPubKey) {
    final StringBuilder buf = new StringBuilder();
    for (ScriptChunk chunk: scriptPubKey.getChunks()) {
        if (buf.length() > 0) {
            buf.append(" ");
        }
        if (chunk.isOpCode()) {
            buf.append(getOpCodeName(chunk.opcode));
        } else if (chunk.data != null) {
            // Data chunk
            buf.append("0x")
                .append(Integer.toString(chunk.opcode, 16)).append(" 0x")
                .append(Utils.HEX.encode(chunk.data));
        } else {
            buf.append(chunk.toString());
        }
    }
    return buf.toString();
}
 
Example 13
@Test
public void shouldAllowExactTimeWindow() {
    final TwoWayChannelMessage message = createClientVersionMessage();
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
    connection.sendToClient(capture(initiateCapture));
    replay(connection);
    final int expire = 24 * 60 * 60 - 60;  // This the default defined in paymentchannel.proto

    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, new PaymentChannelServer.DefaultServerChannelProperties(){
        @Override
        public long getMaxTimeWindow() { return expire; }
        @Override
        public long getMinTimeWindow() { return expire; }
    }, connection);
    dut.connectionOpen();
    long expectedExpire = Utils.currentTimeSeconds() + expire;
    dut.receiveMessage(message);

    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
Example 14
public String toString(boolean includePrivateKeys, NetworkParameters params) {
    final DeterministicKey watchingKey = getWatchingKey();
    final StringBuilder builder = new StringBuilder();
    if (seed != null) {
        if (seed.isEncrypted()) {
            builder.append("Seed is encrypted\n");
        } else if (includePrivateKeys) {
            final List<String> words = seed.getMnemonicCode();
            builder.append("Seed as words: ").append(Utils.join(words)).append('\n');
            builder.append("Seed as hex:   ").append(seed.toHexString()).append('\n');
        }
        builder.append("Seed birthday: ").append(seed.getCreationTimeSeconds()).append("  [")
                .append(Utils.dateTimeFormat(seed.getCreationTimeSeconds() * 1000)).append("]\n");
    } else {
        builder.append("Key birthday:  ").append(watchingKey.getCreationTimeSeconds()).append("  [")
                .append(Utils.dateTimeFormat(watchingKey.getCreationTimeSeconds() * 1000)).append("]\n");
    }
    builder.append("Key to watch:  ").append(watchingKey.serializePubB58(params)).append('\n');
    formatAddresses(includePrivateKeys, params, builder);
    return builder.toString();
}
 
Example 15
Source Project: bcm-android   Source File: ScriptChunk.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void write(OutputStream stream) throws IOException {
    if (isOpCode()) {
        checkState(data == null);
        stream.write(opcode);
    } else if (data != null) {
        if (opcode < OP_PUSHDATA1) {
            checkState(data.length == opcode);
            stream.write(opcode);
        } else if (opcode == OP_PUSHDATA1) {
            checkState(data.length <= 0xFF);
            stream.write(OP_PUSHDATA1);
            stream.write(data.length);
        } else if (opcode == OP_PUSHDATA2) {
            checkState(data.length <= 0xFFFF);
            stream.write(OP_PUSHDATA2);
            Utils.uint16ToByteStreamLE(data.length, stream);
        } else if (opcode == OP_PUSHDATA4) {
            checkState(data.length <= Script.MAX_SCRIPT_ELEMENT_SIZE);
            stream.write(OP_PUSHDATA4);
            Utils.uint32ToByteStreamLE(data.length, stream);
        } else {
            throw new RuntimeException("Unimplemented");
        }
        stream.write(data);
    } else {
        stream.write(opcode); // smallNum
    }
}
 
Example 16
Source Project: bcm-android   Source File: ScriptChunk.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder();
    if (isOpCode()) {
        buf.append(getOpCodeName(opcode));
    } else if (data != null) {
        // Data chunk
        buf.append(getPushDataName(opcode)).append("[").append(Utils.HEX.encode(data)).append("]");
    } else {
        // Small num
        buf.append(Script.decodeFromOpN(opcode));
    }
    return buf.toString();
}
 
Example 17
Source Project: bcm-android   Source File: TestNet3Params.java    License: GNU General Public License v3.0 5 votes vote down vote up
public TestNet3Params() {
    super();
    id = ID_TESTNET;
    packetMagic = 0x0b110907;
    interval = INTERVAL;
    targetTimespan = TARGET_TIMESPAN;
    maxTarget = Utils.decodeCompactBits(0x1d00ffffL);
    port = 18333;
    addressHeader = 111;
    p2shHeader = 196;
    dumpedPrivateKeyHeader = 239;
    segwitAddressHrp = "tb";
    genesisBlock.setTime(1296688602L);
    genesisBlock.setDifficultyTarget(0x1d00ffffL);
    genesisBlock.setNonce(414098458);
    spendableCoinbaseDepth = 100;
    subsidyDecreaseBlockCount = 210000;
    String genesisHash = genesisBlock.getHashAsString();
    checkState(genesisHash.equals("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"));
    alertSigningKey = Utils.HEX.decode("04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a");

    dnsSeeds = new String[]{
            "testnet-seed.bitcoin.jonasschnelli.ch", // Jonas Schnelli
            "testnet-seed.bluematt.me",              // Matt Corallo
            "testnet-seed.bitcoin.petertodd.org",    // Peter Todd
            "testnet-seed.bitcoin.schildbach.de",    // Andreas Schildbach
            "bitcoin-testnet.bloqseeds.net",         // Bloq
    };
    addrSeeds = null;
    bip32HeaderPub = 0x043587CF;
    bip32HeaderPriv = 0x04358394;

    majorityEnforceBlockUpgrade = TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE;
    majorityRejectBlockOutdated = TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED;
    majorityWindow = TESTNET_MAJORITY_WINDOW;
}
 
Example 18
Source Project: bisq   Source File: FilterManager.java    License: 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 19
Source Project: bcm-android   Source File: DRMWorkaround.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void maybeDisableExportControls() {
    // This sorry story is documented in https://bugs.openjdk.java.net/browse/JDK-7024850
    // Oracle received permission to ship AES-256 by default in 2011, but didn't get around to it for Java 8
    // even though that shipped in 2014! That's dumb. So we disable the ridiculous US government mandated DRM
    // for AES-256 here, as Tor/BIP38 requires it.

    if (done)
        return;
    done = true;

    if (Utils.isAndroidRuntime())
        return;
    try {
        Field gate = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
        gate.setAccessible(true);
        gate.setBoolean(null, false);
        final Field allPerm = Class.forName("javax.crypto.CryptoAllPermission").getDeclaredField("INSTANCE");
        allPerm.setAccessible(true);
        Object accessAllAreasCard = allPerm.get(null);
        final Constructor<?> constructor = Class.forName("javax.crypto.CryptoPermissions").getDeclaredConstructor();
        constructor.setAccessible(true);
        Object coll = constructor.newInstance();
        Method addPerm = Class.forName("javax.crypto.CryptoPermissions").getDeclaredMethod("add", java.security.Permission.class);
        addPerm.setAccessible(true);
        addPerm.invoke(coll, accessAllAreasCard);
        Field defaultPolicy = Class.forName("javax.crypto.JceSecurity").getDeclaredField("defaultPolicy");
        defaultPolicy.setAccessible(true);
        defaultPolicy.set(null, coll);
    } catch (Exception e) {
        log.warn("Failed to deactivate AES-256 barrier logic, Tor mode/BIP38 decryption may crash if this JVM requires it: " + e.getMessage());
    }
}
 
Example 20
Source Project: green_android   Source File: ScriptChunk.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void write(OutputStream stream) throws IOException {
    if (isOpCode()) {
        checkState(data == null);
        stream.write(opcode);
    } else if (data != null) {
        if (opcode < OP_PUSHDATA1) {
            checkState(data.length == opcode);
            stream.write(opcode);
        } else if (opcode == OP_PUSHDATA1) {
            checkState(data.length <= 0xFF);
            stream.write(OP_PUSHDATA1);
            stream.write(data.length);
        } else if (opcode == OP_PUSHDATA2) {
            checkState(data.length <= 0xFFFF);
            stream.write(OP_PUSHDATA2);
            stream.write(0xFF & data.length);
            stream.write(0xFF & (data.length >> 8));
        } else if (opcode == OP_PUSHDATA4) {
            checkState(data.length <= Script.MAX_SCRIPT_ELEMENT_SIZE);
            stream.write(OP_PUSHDATA4);
            Utils.uint32ToByteStreamLE(data.length, stream);
        } else {
            throw new RuntimeException("Unimplemented");
        }
        stream.write(data);
    } else {
        stream.write(opcode); // smallNum
    }
}
 
Example 21
/**
 * <p>Writes the given message to the other side of the connection, prefixing it with the proper 4-byte prefix.</p>
 * <p>
 * <p>Provides a write-order guarantee.</p>
 *
 * @throws IllegalStateException If the encoded message is larger than the maximum message size.
 */
public void write(MessageType msg) throws IllegalStateException {
    byte[] messageBytes = msg.toByteArray();
    checkState(messageBytes.length <= maxMessageSize);
    byte[] messageLength = new byte[4];
    Utils.uint32ToByteArrayBE(messageBytes.length, messageLength, 0);
    try {
        MessageWriteTarget target = writeTarget.get();
        target.writeBytes(messageLength);
        target.writeBytes(messageBytes);
    } catch (IOException e) {
        closeConnection();
    }
}
 
Example 22
Source Project: bcm-android   Source File: MarriedKeyChain.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void formatScript(Script script, StringBuilder builder, NetworkParameters params) {
    builder.append("  addr:");
    builder.append(script.getToAddress(params));
    builder.append("  hash160:");
    builder.append(Utils.HEX.encode(script.getPubKeyHash()));
    if (script.getCreationTimeSeconds() > 0)
        builder.append("  creationTimeSeconds:").append(script.getCreationTimeSeconds());
    builder.append('\n');
}
 
Example 23
Source Project: green_android   Source File: TestNet2Params.java    License: GNU General Public License v3.0 5 votes vote down vote up
public TestNet2Params() {
    super();
    id = ID_TESTNET;
    packetMagic = 0xfabfb5daL;
    port = 18333;
    addressHeader = 111;
    p2shHeader = 196;
    acceptableAddressCodes = new int[] { addressHeader, p2shHeader };
    interval = INTERVAL;
    targetTimespan = TARGET_TIMESPAN;
    maxTarget = Utils.decodeCompactBits(0x1d0fffffL);
    dumpedPrivateKeyHeader = 239;
    genesisBlock.setTime(1296688602L);
    genesisBlock.setDifficultyTarget(0x1d07fff8L);
    genesisBlock.setNonce(384568319);
    spendableCoinbaseDepth = 100;
    subsidyDecreaseBlockCount = 210000;
    String genesisHash = genesisBlock.getHashAsString();
    checkState(genesisHash.equals("00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008"));
    dnsSeeds = null;
    addrSeeds = null;
    bip32HeaderPub = 0x043587CF;
    bip32HeaderPriv = 0x04358394;

    majorityEnforceBlockUpgrade = TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE;
    majorityRejectBlockOutdated = TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED;
    majorityWindow = TESTNET_MAJORITY_WINDOW;
}
 
Example 24
@Before
public void setUp() {
    broadcaster = createMock(TransactionBroadcaster.class);
    wallet = createMock(Wallet.class);
    connection = createMock(PaymentChannelServer.ServerConnection.class);
    serverVersionCapture = new Capture<TwoWayChannelMessage>();
    connection.sendToClient(capture(serverVersionCapture));
    Utils.setMockClock();
}
 
Example 25
@Test
public void testKeyCrypterGood1() throws KeyCrypterException {
    KeyCrypterScrypt keyCrypter = new KeyCrypterScrypt(scryptParameters);

    // Encrypt.
    EncryptedData data = keyCrypter.encrypt(TEST_BYTES1, keyCrypter.deriveKey(PASSWORD1));
    assertNotNull(data);

    // Decrypt.
    byte[] reborn = keyCrypter.decrypt(data, keyCrypter.deriveKey(PASSWORD1));
    log.debug("Original: " + Utils.HEX.encode(TEST_BYTES1));
    log.debug("Reborn  : " + Utils.HEX.encode(reborn));
    assertEquals(Utils.HEX.encode(TEST_BYTES1), Utils.HEX.encode(reborn));
}
 
Example 26
Source Project: green_android   Source File: WalletTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void keyCreationTime() throws Exception {
    Utils.setMockClock();
    long now = Utils.currentTimeSeconds();
    wallet = new Wallet(PARAMS);
    assertEquals(now, wallet.getEarliestKeyCreationTime());
    Utils.rollMockClock(60);
    wallet.freshReceiveKey();
    assertEquals(now, wallet.getEarliestKeyCreationTime());
}
 
Example 27
Source Project: green_android   Source File: WalletTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void transactionsList() throws Exception {
    // Check the wallet can give us an ordered list of all received transactions.
    Utils.setMockClock();
    Transaction tx1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
    Utils.rollMockClock(60 * 10);
    Transaction tx2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(0, 5));
    // Check we got them back in order.
    List<Transaction> transactions = wallet.getTransactionsByTime();
    assertEquals(tx2, transactions.get(0));
    assertEquals(tx1, transactions.get(1));
    assertEquals(2, transactions.size());
    // Check we get only the last transaction if we request a subrage.
    transactions = wallet.getRecentTransactions(1, false);
    assertEquals(1, transactions.size());
    assertEquals(tx2,  transactions.get(0));

    // Create a spend five minutes later.
    Utils.rollMockClock(60 * 5);
    Transaction tx3 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 5));
    // Does not appear in list yet.
    assertEquals(2, wallet.getTransactionsByTime().size());
    wallet.commitTx(tx3);
    // Now it does.
    transactions = wallet.getTransactionsByTime();
    assertEquals(3, transactions.size());
    assertEquals(tx3, transactions.get(0));

    // Verify we can handle the case of older wallets in which the timestamp is null (guessed from the
    // block appearances list).
    tx1.setUpdateTime(null);
    tx3.setUpdateTime(null);
    // Check we got them back in order.
    transactions = wallet.getTransactionsByTime();
    assertEquals(tx2,  transactions.get(0));
    assertEquals(3, transactions.size());
}
 
Example 28
@Test
public void masterKeyAccount() throws UnreadableWalletException {
    Utils.setMockClock();
    long secs = 1389353062L;
    DeterministicKey firstReceiveKey = bip44chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicKey secondReceiveKey = bip44chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicKey firstChangeKey = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE);
    DeterministicKey secondChangeKey = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE);

    NetworkParameters params = MainNetParams.get();
    DeterministicKey watchingKey = bip44chain.getWatchingKey(); //m/44'/1'/0'
    DeterministicKey coinLevelKey = bip44chain.getWatchingKey().getParent(); //m/44'/1'

    //Simulate Wallet.fromSpendingKeyB58(PARAMS, prv58, secs)
    final String prv58 = watchingKey.serializePrivB58(params);
    assertEquals("xprv9yYQhynAmWWuz62PScx5Q2frBET2F1raaXna5A2E9Lj8XWgmKBL7S98Yand8F736j9UCTNWQeiB4yL5pLZP7JDY2tY8eszGQkiKDwBkezeS", prv58);
    watchingKey = DeterministicKey.deserializeB58(null, prv58, params);
    watchingKey.setCreationTimeSeconds(secs);
    DeterministicKeyChain fromPrivBase58Chain = DeterministicKeyChain.spend(watchingKey);
    assertEquals(secs, fromPrivBase58Chain.getEarliestKeyCreationTime());
    fromPrivBase58Chain.setLookaheadSize(10);
    fromPrivBase58Chain.maybeLookAhead();

    verifySpendableKeyChain(firstReceiveKey, secondReceiveKey, firstChangeKey, secondChangeKey, fromPrivBase58Chain, "spending-wallet-from-bip44-serialization.txt");

    //Simulate Wallet.fromMasterKey(params, coinLevelKey, 0)
    DeterministicKey accountKey = HDKeyDerivation.deriveChildKey(coinLevelKey, new ChildNumber(0, true));
    accountKey = accountKey.dropParent();
    accountKey.setCreationTimeSeconds(watchingKey.getCreationTimeSeconds());
    KeyChainGroup group = new KeyChainGroup(params, accountKey, false);
    DeterministicKeyChain fromMasterKeyChain = group.getActiveKeyChain();
    assertEquals(secs, fromMasterKeyChain.getEarliestKeyCreationTime());
    fromMasterKeyChain.setLookaheadSize(10);
    fromMasterKeyChain.maybeLookAhead();

    verifySpendableKeyChain(firstReceiveKey, secondReceiveKey, firstChangeKey, secondChangeKey, fromMasterKeyChain, "spending-wallet-from-bip44-serialization-two.txt");
}
 
Example 29
@Before
public void setUp() {
    broadcaster = createMock(TransactionBroadcaster.class);
    wallet = createMock(Wallet.class);
    connection = createMock(PaymentChannelServer.ServerConnection.class);
    serverVersionCapture = new Capture<TwoWayChannelMessage>();
    connection.sendToClient(capture(serverVersionCapture));
    Utils.setMockClock();
}
 
Example 30
@Before
public void setUp() {
    broadcaster = createMock(TransactionBroadcaster.class);
    wallet = createMock(Wallet.class);
    connection = createMock(PaymentChannelServer.ServerConnection.class);
    serverVersionCapture = new Capture<TwoWayChannelMessage>();
    connection.sendToClient(capture(serverVersionCapture));
    Utils.setMockClock();
}