当前位置: 首页>>代码示例>>Java>>正文


Java Utils类代码示例

本文整理汇总了Java中org.bitcoinj.core.Utils的典型用法代码示例。如果您正苦于以下问题:Java Utils类的具体用法?Java Utils怎么用?Java Utils使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Utils类属于org.bitcoinj.core包,在下文中一共展示了Utils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: toSeed

import org.bitcoinj.core.Utils; //导入依赖的package包/类
/**
 * 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.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;
}
 
开发者ID:guodroid,项目名称:okwallet,代码行数:22,代码来源:MnemonicCode.java

示例2: toString

import org.bitcoinj.core.Utils; //导入依赖的package包/类
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();
}
 
开发者ID:guodroid,项目名称:okwallet,代码行数:25,代码来源:DeterministicKeyChain.java

示例3: initAddresses

import org.bitcoinj.core.Utils; //导入依赖的package包/类
private void initAddresses() throws CoinbleskException {
    loadAddresses();
    try {
        // new address: no address yet or current receive address expires soon.
        boolean needToCreateNewAddress = false;
        if (addresses.isEmpty()) {
            Log.d(TAG, "No address yet. Create new address.");
            needToCreateNewAddress = true;
        } else {
            long nowSec = org.bitcoinj.core.Utils.currentTimeSeconds();
            long currentExpiresInSec = addresses.last().getLockTime() - nowSec;
            if (currentExpiresInSec < Constants.MIN_LOCKTIME_SPAN_SECONDS) {
                Log.d(TAG, "Current address expires soon (in "+currentExpiresInSec+" seconds). Create new address.");
                needToCreateNewAddress = true;
            }
        }

        if (needToCreateNewAddress) {
            createTimeLockedAddress();
        }
    } catch (Exception e) {
        Log.w(TAG, "Could not initialize addresses. ", e);
        throw new CoinbleskException("Could not initialize addresses: " + e.getMessage(), e);
    }
}
 
开发者ID:coinblesk,项目名称:coinblesk-client-gui,代码行数:26,代码来源:WalletService.java

示例4: addAddress

import org.bitcoinj.core.Utils; //导入依赖的package包/类
private TimeLockedAddress addAddress(LockTime lockTime) {
    // Note: do not use in loop, adding to wallet is slow!
    TimeLockedAddress address = new TimeLockedAddress(
            multisigClientKey.getPubKey(),
            multisigServerKey.getPubKey(),
            lockTime.getLockTime());
    addresses.add(lockTime);
    addressHashes.put(
            Utils.HEX.encode(address.getAddressHash()),
            address);
    Script pubKeyScript = address.createPubkeyScript();
    pubKeyScript.setCreationTimeSeconds(lockTime.getTimeCreatedSeconds());
    wallet.addWatchedScripts(ImmutableList.of(pubKeyScript));
    Log.d(TAG, "Added address: " + address.toString(getNetworkParameters()));
    return address;
}
 
开发者ID:coinblesk,项目名称:coinblesk-client-gui,代码行数:17,代码来源:WalletService.java

示例5: getUnlockedUnspentOutputs

import org.bitcoinj.core.Utils; //导入依赖的package包/类
private List<TransactionOutput> getUnlockedUnspentOutputs() {
    final List<TransactionOutput> outputs = new ArrayList<>();
    final List<TransactionOutput> candidates = wallet.calculateAllSpendCandidates(false, false);
    final long currentTimeSec = org.bitcoinj.core.Utils.currentTimeSeconds();
    for (TransactionOutput txOut : candidates) {
        byte[] addressHash = txOut.getScriptPubKey().getPubKeyHash();
        TimeLockedAddress tla = findTimeLockedAddressByHash(addressHash);
        if (tla != null) {
            long lockTime = tla.getLockTime();
            if (BitcoinUtils.isAfterLockTime(currentTimeSec, lockTime)) {
                outputs.add(txOut);
                Log.d(TAG, "getUnlockedUnspentOutputs - unlocked output: " + txOut);
            }
        }
    }
    return outputs;
}
 
开发者ID:coinblesk,项目名称:coinblesk-client-gui,代码行数:18,代码来源:WalletService.java

示例6: signTransaction

import org.bitcoinj.core.Utils; //导入依赖的package包/类
private List<TransactionSignature> signTransaction(Transaction tx) throws CoinbleskException {
    final List<TransactionInput> inputs = tx.getInputs();
    final List<TransactionSignature> signatures = new ArrayList<>(inputs.size());
    for (int i = 0; i < inputs.size(); ++i) {
        TransactionInput txIn = inputs.get(i);
        TransactionOutput prevTxOut = txIn.getConnectedOutput();
        byte[] sentToHash = prevTxOut.getScriptPubKey().getPubKeyHash();
        TimeLockedAddress tla = findTimeLockedAddressByHash(sentToHash);
        if (tla == null) {
            throw new CoinbleskException(String.format(Locale.US,
                    "Could not sign input (index=%d, pubKeyHash=%s)",
                    i, org.bitcoinj.core.Utils.HEX.encode(sentToHash)));
        }
        byte[] redeemScript = tla.createRedeemScript().getProgram();
        TransactionSignature signature = tx.calculateSignature(
                i, multisigClientKey, redeemScript, Transaction.SigHash.ALL, false);
        signatures.add(signature);
    }
    return signatures;
}
 
开发者ID:coinblesk,项目名称:coinblesk-client-gui,代码行数:21,代码来源:WalletService.java

示例7: toSeed

import org.bitcoinj.core.Utils; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:Grant-Redmond,项目名称:cryptwallet,代码行数:22,代码来源:MnemonicCode.java

示例8: toString

import org.bitcoinj.core.Utils; //导入依赖的package包/类
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();
}
 
开发者ID:Grant-Redmond,项目名称:cryptwallet,代码行数:22,代码来源:DeterministicKeyChain.java

示例9: shouldAcceptDefaultTimeWindow

import org.bitcoinj.core.Utils; //导入依赖的package包/类
@Test
public void shouldAcceptDefaultTimeWindow() {
    final TwoWayChannelMessage message = createClientVersionMessage();
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<TwoWayChannelMessage>();
    connection.sendToClient(capture(initiateCapture));
    replay(connection);

    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, connection);

    dut.connectionOpen();
    dut.receiveMessage(message);

    long expectedExpire = Utils.currentTimeSeconds() + 24 * 60 * 60 - 60;  // This the default defined in paymentchannel.proto
    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
开发者ID:Grant-Redmond,项目名称:cryptwallet,代码行数:17,代码来源:PaymentChannelServerTest.java

示例10: shouldTruncateTooLargeTimeWindow

import org.bitcoinj.core.Utils; //导入依赖的package包/类
@Test
public void shouldTruncateTooLargeTimeWindow() {
    final int maxTimeWindow = 40000;
    final int timeWindow = maxTimeWindow + 1;
    final TwoWayChannelMessage message = createClientVersionMessage(timeWindow);
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<TwoWayChannelMessage>();
    connection.sendToClient(capture(initiateCapture));
    replay(connection);

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

    dut.connectionOpen();
    dut.receiveMessage(message);

    long expectedExpire = Utils.currentTimeSeconds() + maxTimeWindow;
    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
开发者ID:Grant-Redmond,项目名称:cryptwallet,代码行数:26,代码来源:PaymentChannelServerTest.java

示例11: shouldAllowExactTimeWindow

import org.bitcoinj.core.Utils; //导入依赖的package包/类
@Test
public void shouldAllowExactTimeWindow() {
    final TwoWayChannelMessage message = createClientVersionMessage();
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<TwoWayChannelMessage>();
    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);
}
 
开发者ID:Grant-Redmond,项目名称:cryptwallet,代码行数:22,代码来源:PaymentChannelServerTest.java

示例12: testVectors

import org.bitcoinj.core.Utils; //导入依赖的package包/类
@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));
    }
}
 
开发者ID:Grant-Redmond,项目名称:cryptwallet,代码行数:17,代码来源:MnemonicCodeTest.java

示例13: testKeyCrypterGood2

import org.bitcoinj.core.Utils; //导入依赖的package包/类
/**
 * Test with random plain text strings and random passwords.
 * UUIDs are used and hence will only cover hex characters (and the separator hyphen).
 * @throws KeyCrypterException
 */
@Test
public void testKeyCrypterGood2() {
    KeyCrypterScrypt keyCrypter = new KeyCrypterScrypt(scryptParameters);

    // Trying random UUIDs for plainText and passwords.
    int numberOfTests = 16;
    for (int i = 0; i < numberOfTests; i++) {
        // Create a UUID as the plaintext and use another for the password.
        String plainText = UUID.randomUUID().toString();
        CharSequence password = UUID.randomUUID().toString();

        EncryptedData data = keyCrypter.encrypt(plainText.getBytes(), keyCrypter.deriveKey(password));

        assertNotNull(data);

        byte[] reconstructedPlainBytes = keyCrypter.decrypt(data,keyCrypter.deriveKey(password));
        assertEquals(Utils.HEX.encode(plainText.getBytes()), Utils.HEX.encode(reconstructedPlainBytes));
    }
}
 
开发者ID:Grant-Redmond,项目名称:cryptwallet,代码行数:25,代码来源:KeyCrypterScryptTest.java

示例14: testEncryptDecryptBytes2

import org.bitcoinj.core.Utils; //导入依赖的package包/类
@Test
public void testEncryptDecryptBytes2() throws KeyCrypterException {
    KeyCrypterScrypt keyCrypter = new KeyCrypterScrypt(scryptParameters);

    // Encrypt random bytes of various lengths up to length 50.
    Random random = new Random();

    for (int i = 0; i < 50; i++) {
        byte[] plainBytes = new byte[i];
        random.nextBytes(plainBytes);

        EncryptedData data = keyCrypter.encrypt(plainBytes, keyCrypter.deriveKey(PASSWORD1));
        assertNotNull(data);
        //log.debug("\nEncrypterDecrypterTest: cipherBytes = \nlength = " + cipherBytes.length + "\n---------------\n" + Utils.HEX.encode(cipherBytes) + "\n---------------\n");

        byte[] rebornPlainBytes = keyCrypter.decrypt(data, keyCrypter.deriveKey(PASSWORD1));

        log.debug("Original: (" + i + ") " + Utils.HEX.encode(plainBytes));
        log.debug("Reborn1 : (" + i + ") " + Utils.HEX.encode(rebornPlainBytes));
        assertEquals(Utils.HEX.encode(plainBytes), Utils.HEX.encode(rebornPlainBytes));
    }
}
 
开发者ID:Grant-Redmond,项目名称:cryptwallet,代码行数:23,代码来源:KeyCrypterScryptTest.java

示例15: serializationUnencrypted

import org.bitcoinj.core.Utils; //导入依赖的package包/类
@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));
}
 
开发者ID:Grant-Redmond,项目名称:cryptwallet,代码行数:24,代码来源:BasicKeyChainTest.java


注:本文中的org.bitcoinj.core.Utils类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。