org.bitcoinj.params.MainNetParams Java Examples

The following examples show how to use org.bitcoinj.params.MainNetParams. 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: AddressTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void p2shAddress() throws Exception {
    // Test that we can construct P2SH addresses
    Address mainNetP2SHAddress = Address.fromBase58(MainNetParams.get(), "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU");
    assertEquals(mainNetP2SHAddress.version, MainNetParams.get().p2shHeader);
    assertTrue(mainNetP2SHAddress.isP2SHAddress());
    Address testNetP2SHAddress = Address.fromBase58(TestNet3Params.get(), "2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe");
    assertEquals(testNetP2SHAddress.version, TestNet3Params.get().p2shHeader);
    assertTrue(testNetP2SHAddress.isP2SHAddress());

    // Test that we can determine what network a P2SH address belongs to
    NetworkParameters mainNetParams = Address.getParametersFromAddress("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU");
    assertEquals(MainNetParams.get().getId(), mainNetParams.getId());
    NetworkParameters testNetParams = Address.getParametersFromAddress("2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe");
    assertEquals(TestNet3Params.get().getId(), testNetParams.getId());

    // Test that we can convert them from hashes
    byte[] hex = HEX.decode("2ac4b0b501117cc8119c5797b519538d4942e90e");
    Address a = Address.fromP2SHHash(mainParams, hex);
    assertEquals("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU", a.toString());
    Address b = Address.fromP2SHHash(testParams, HEX.decode("18a0e827269b5211eb51a4af1b2fa69333efa722"));
    assertEquals("2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe", b.toString());
    Address c = Address.fromP2SHScript(mainParams, ScriptBuilder.createP2SHOutputScript(hex));
    assertEquals("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU", c.toString());
}
 
Example #2
Source File: BitcoinSerializerTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get 1 header of the block number 1 (the first one is 0) in the chain
 */
@Test
public void testHeaders1() throws Exception {
    MessageSerializer serializer = MainNetParams.get().getDefaultSerializer();

    byte[] headersMessageBytes = HEX.decode("f9beb4d9686561" +
            "646572730000000000520000005d4fab8101010000006fe28c0ab6f1b372c1a6a246ae6" +
            "3f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677b" +
            "a1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e3629900");
    HeadersMessage headersMessage = (HeadersMessage) serializer.deserialize(ByteBuffer.wrap(headersMessageBytes));

    // The first block after the genesis
    // http://blockexplorer.com/b/1
    Block block = headersMessage.getBlockHeaders().get(0);
    assertEquals("00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048", block.getHashAsString());
    assertNotNull(block.transactions);
    assertEquals("0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098", Utils.HEX.encode(block.getMerkleRoot().getBytes()));

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    serializer.serialize(headersMessage, byteArrayOutputStream);
    byte[] serializedBytes = byteArrayOutputStream.toByteArray();
    assertArrayEquals(headersMessageBytes, serializedBytes);
}
 
Example #3
Source File: LegacyAddressTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void p2shAddress() throws Exception {
    // Test that we can construct P2SH addresses
    LegacyAddress mainNetP2SHAddress = LegacyAddress.fromBase58(MainNetParams.get(), "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU");
    assertEquals(mainNetP2SHAddress.getVersion(), MAINNET.p2shHeader);
    assertEquals(ScriptType.P2SH, mainNetP2SHAddress.getOutputScriptType());
    LegacyAddress testNetP2SHAddress = LegacyAddress.fromBase58(TestNet3Params.get(), "2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe");
    assertEquals(testNetP2SHAddress.getVersion(), TESTNET.p2shHeader);
    assertEquals(ScriptType.P2SH, testNetP2SHAddress.getOutputScriptType());

    // Test that we can determine what network a P2SH address belongs to
    NetworkParameters mainNetParams = LegacyAddress.getParametersFromAddress("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU");
    assertEquals(MAINNET.getId(), mainNetParams.getId());
    NetworkParameters testNetParams = LegacyAddress.getParametersFromAddress("2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe");
    assertEquals(TESTNET.getId(), testNetParams.getId());

    // Test that we can convert them from hashes
    byte[] hex = HEX.decode("2ac4b0b501117cc8119c5797b519538d4942e90e");
    LegacyAddress a = LegacyAddress.fromScriptHash(MAINNET, hex);
    assertEquals("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU", a.toString());
    LegacyAddress b = LegacyAddress.fromScriptHash(TESTNET, HEX.decode("18a0e827269b5211eb51a4af1b2fa69333efa722"));
    assertEquals("2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe", b.toString());
    LegacyAddress c = LegacyAddress.fromScriptHash(MAINNET,
            ScriptPattern.extractHashFromPayToScriptHash(ScriptBuilder.createP2SHOutputScript(hex)));
    assertEquals("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU", c.toString());
}
 
Example #4
Source File: BitcoinCLITool.java    From consensusj with Apache License 2.0 6 votes vote down vote up
public RpcConfig getRPCConfig() {
    RpcConfig confFileConfig = BitcoinConfFile.readDefaultConfig().getRPCConfig();
    URI uri = getServerURI(confFileConfig.getURI());
    String user = line.getOptionValue("rpcuser", confFileConfig.getUsername());
    String pass = line.getOptionValue("rpcpassword", confFileConfig.getPassword());
    NetworkParameters netParams;
    if (line.hasOption("regtest")) {
        netParams = RegTestParams.get();
    } else if (line.hasOption(("testnet"))) {
        netParams = TestNet3Params.get();
    } else {
        netParams = MainNetParams.get();
    }
    RpcConfig cfg = new RpcConfig(netParams, uri, user, pass);
    return cfg;
}
 
Example #5
Source File: WalletNetworkConfig.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
void proposePeers(List<PeerAddress> peers) {
    if (!peers.isEmpty()) {
        log.info("You connect with peerAddresses: {}", peers);
        PeerAddress[] peerAddresses = peers.toArray(new PeerAddress[peers.size()]);
        delegate.setPeerNodes(peerAddresses);
    } else if (proxy != null) {
        if (log.isWarnEnabled()) {
            MainNetParams mainNetParams = MainNetParams.get();
            if (parameters.equals(mainNetParams)) {
                log.warn("You use the public Bitcoin network and are exposed to privacy issues " +
                        "caused by the broken bloom filters. See https://bisq.network/blog/privacy-in-bitsquare/ " +
                        "for more info. It is recommended to use the provided nodes.");
            }
        }
        // SeedPeers uses hard coded stable addresses (from MainNetParams). It should be updated from time to time.
        delegate.setDiscovery(new Socks5MultiDiscovery(proxy, parameters, socks5DiscoverMode));
    } else {
        log.warn("You don't use tor and use the public Bitcoin network and are exposed to privacy issues " +
                "caused by the broken bloom filters. See https://bisq.network/blog/privacy-in-bitsquare/ " +
                "for more info. It is recommended to use Tor and the provided nodes.");
    }
}
 
Example #6
Source File: BitcoinSerializerTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testAddr() throws Exception {
    final NetworkParameters params = MainNetParams.get();
    MessageSerializer serializer = params.getDefaultSerializer();
    // the actual data from https://en.bitcoin.it/wiki/Protocol_specification#addr
    AddressMessage addressMessage = (AddressMessage) serializer.deserialize(ByteBuffer.wrap(ADDRESS_MESSAGE_BYTES));
    assertEquals(1, addressMessage.getAddresses().size());
    PeerAddress peerAddress = addressMessage.getAddresses().get(0);
    assertEquals(8333, peerAddress.getPort());
    assertEquals("10.0.0.1", peerAddress.getAddr().getHostAddress());
    ByteArrayOutputStream bos = new ByteArrayOutputStream(ADDRESS_MESSAGE_BYTES.length);
    serializer.serialize(addressMessage, bos);

    assertEquals(31, addressMessage.getMessageSize());
    addressMessage.addAddress(new PeerAddress(params, InetAddress.getLocalHost()));
    assertEquals(61, addressMessage.getMessageSize());
    addressMessage.removeAddress(0);
    assertEquals(31, addressMessage.getMessageSize());

    //this wont be true due to dynamic timestamps.
    //assertTrue(LazyParseByteCacheTest.arrayContains(bos.toByteArray(), addrMessage));
}
 
Example #7
Source File: BloomFilterTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void walletTest() throws Exception {
    NetworkParameters params = MainNetParams.get();
    Context.propagate(new Context(params));

    DumpedPrivateKey privKey = DumpedPrivateKey.fromBase58(params, "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C");

    Address addr = privKey.getKey().toAddress(params);
    assertTrue(addr.toString().equals("17Wx1GQfyPTNWpQMHrTwRSMTCAonSiZx9e"));

    KeyChainGroup group = new KeyChainGroup(params);
    // Add a random key which happens to have been used in a recent generation
    group.importKeys(ECKey.fromPublicOnly(privKey.getKey().getPubKeyPoint()), ECKey.fromPublicOnly(HEX.decode("03cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99")));
    Wallet wallet = new Wallet(params, group);
    wallet.commitTx(new Transaction(params, HEX.decode("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0d038754030114062f503253482fffffffff01c05e559500000000232103cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99ac00000000")));
    
    // We should have 2 per pubkey, and one for the pay-2-pubkey output we have
    assertEquals(5, wallet.getBloomFilterElementCount());
    
    BloomFilter filter = wallet.getBloomFilter(wallet.getBloomFilterElementCount(), 0.001, 0);
    
    // Value generated by Bitcoin Core
    assertTrue(Arrays.equals(HEX.decode("082ae5edc8e51d4a03080000000000000002"), filter.unsafeBitcoinSerialize()));
}
 
Example #8
Source File: V3Keystore.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
public V3Keystore(Metadata metadata, String password, String prvKeyHex, String id) {
  byte[] prvKeyBytes;
  if (metadata.getChainType().equals(ChainType.BITCOIN)) {
    NetworkParameters network = metadata.isMainNet() ? MainNetParams.get() : TestNet3Params.get();
    prvKeyBytes = prvKeyHex.getBytes();
    new WIFValidator(prvKeyHex, network).validate();
    if (Metadata.P2WPKH.equals(metadata.getSegWit())) {
      this.address = new SegWitBitcoinAddressCreator(network).fromPrivateKey(prvKeyHex);
    } else {
      this.address = new BitcoinAddressCreator(network).fromPrivateKey(prvKeyHex);
    }
  } else if (metadata.getChainType().equals(ChainType.ETHEREUM)) {
    prvKeyBytes = NumericUtil.hexToBytes(prvKeyHex);
    new PrivateKeyValidator(prvKeyHex).validate();
    this.address = new EthereumAddressCreator().fromPrivateKey(prvKeyBytes);
  } else {
    throw new TokenException("Can't init eos keystore in this constructor");
  }
  this.crypto = Crypto.createPBKDF2Crypto(password, prvKeyBytes);
  metadata.setWalletType(Metadata.V3);
  this.metadata = metadata;
  this.version = VERSION;
  this.id = Strings.isNullOrEmpty(id) ? UUID.randomUUID().toString() : id;
}
 
Example #9
Source File: LevelDB.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    /*
     * This is just a test runner that will download blockchain till block
     * 390000 then exit.
     */
    FullPrunedBlockStore store = new LevelDBFullPrunedBlockStore(
            MainNetParams.get(), args[0], 1000, 100 * 1024 * 1024l,
            10 * 1024 * 1024, 100000, true, 390000);

    FullPrunedBlockChain vChain = new FullPrunedBlockChain(
            MainNetParams.get(), store);
    vChain.setRunScripts(false);

    PeerGroup vPeerGroup = new PeerGroup(MainNetParams.get(), vChain);
    vPeerGroup.setUseLocalhostPeerWhenPossible(true);
    vPeerGroup.addAddress(InetAddress.getLocalHost());

    vPeerGroup.start();
    vPeerGroup.downloadBlockChain();
}
 
Example #10
Source File: BIP32Test.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
private void testVector(int testCase) {
    log.info("=======  Test vector {}", testCase);
    HDWTestVector tv = tvs[testCase];
    NetworkParameters params = MainNetParams.get();
    DeterministicKey masterPrivateKey = HDKeyDerivation.createMasterPrivateKey(HEX.decode(tv.seed));
    assertEquals(testEncode(tv.priv), testEncode(masterPrivateKey.serializePrivB58(params)));
    assertEquals(testEncode(tv.pub), testEncode(masterPrivateKey.serializePubB58(params)));
    DeterministicHierarchy dh = new DeterministicHierarchy(masterPrivateKey);
    for (int i = 0; i < tv.derived.size(); i++) {
        HDWTestVector.DerivedTestCase tc = tv.derived.get(i);
        log.info("{}", tc.name);
        assertEquals(tc.name, String.format(Locale.US, "Test%d %s", testCase + 1, tc.getPathDescription()));
        int depth = tc.path.length - 1;
        DeterministicKey ehkey = dh.deriveChild(Arrays.asList(tc.path).subList(0, depth), false, true, tc.path[depth]);
        assertEquals(testEncode(tc.priv), testEncode(ehkey.serializePrivB58(params)));
        assertEquals(testEncode(tc.pub), testEncode(ehkey.serializePubB58(params)));
    }
}
 
Example #11
Source File: BloomFilterTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void walletTest() throws Exception {
    NetworkParameters params = MainNetParams.get();
    Context.propagate(new Context(params));

    DumpedPrivateKey privKey = DumpedPrivateKey.fromBase58(params, "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C");

    Address addr = privKey.getKey().toAddress(params);
    assertTrue(addr.toString().equals("17Wx1GQfyPTNWpQMHrTwRSMTCAonSiZx9e"));

    KeyChainGroup group = new KeyChainGroup(params);
    // Add a random key which happens to have been used in a recent generation
    group.importKeys(ECKey.fromPublicOnly(privKey.getKey().getPubKeyPoint()), ECKey.fromPublicOnly(HEX.decode("03cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99")));
    Wallet wallet = new Wallet(params, group);
    wallet.commitTx(new Transaction(params, HEX.decode("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0d038754030114062f503253482fffffffff01c05e559500000000232103cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99ac00000000")));
    
    // We should have 2 per pubkey, and one for the pay-2-pubkey output we have
    assertEquals(5, wallet.getBloomFilterElementCount());
    
    BloomFilter filter = wallet.getBloomFilter(wallet.getBloomFilterElementCount(), 0.001, 0);
    
    // Value generated by Bitcoin Core
    assertTrue(Arrays.equals(HEX.decode("082ae5edc8e51d4a03080000000000000002"), filter.unsafeBitcoinSerialize()));
}
 
Example #12
Source File: AbstractFullPrunedBlockChainTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testFirst100KBlocks() throws Exception {
    NetworkParameters params = MainNetParams.get();
    Context context = new Context(params);
    File blockFile = new File(getClass().getResource("first-100k-blocks.dat").getFile());
    BlockFileLoader loader = new BlockFileLoader(params, Arrays.asList(blockFile));
    
    store = createStore(params, 10);
    resetStore(store);
    chain = new FullPrunedBlockChain(context, store);
    for (Block block : loader)
        chain.add(block);
    try {
        store.close();
    } catch (Exception e) {}
}
 
Example #13
Source File: BitcoinSerializerTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testAddr() throws Exception {
    final NetworkParameters params = MainNetParams.get();
    MessageSerializer serializer = params.getDefaultSerializer();
    // the actual data from https://en.bitcoin.it/wiki/Protocol_specification#addr
    AddressMessage addressMessage = (AddressMessage) serializer.deserialize(ByteBuffer.wrap(ADDRESS_MESSAGE_BYTES));
    assertEquals(1, addressMessage.getAddresses().size());
    PeerAddress peerAddress = addressMessage.getAddresses().get(0);
    assertEquals(8333, peerAddress.getPort());
    assertEquals("10.0.0.1", peerAddress.getAddr().getHostAddress());
    ByteArrayOutputStream bos = new ByteArrayOutputStream(ADDRESS_MESSAGE_BYTES.length);
    serializer.serialize(addressMessage, bos);

    assertEquals(31, addressMessage.getMessageSize());
    addressMessage.addAddress(new PeerAddress(params, InetAddress.getLocalHost()));
    assertEquals(61, addressMessage.getMessageSize());
    addressMessage.removeAddress(0);
    assertEquals(31, addressMessage.getMessageSize());

    //this wont be true due to dynamic timestamps.
    //assertTrue(LazyParseByteCacheTest.arrayContains(bos.toByteArray(), addrMessage));
}
 
Example #14
Source File: ScriptRunner.java    From consensusj with Apache License 2.0 6 votes vote down vote up
public ScriptRunner() throws ScriptException {
    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    engine = factory.getScriptEngine("-scripting");
    BitcoinExtendedClient client = new BitcoinExtendedClient(MainNetParams.get(),
            RpcURI.getDefaultMainNetURI(),
            TestServers.getInstance().getRpcTestUser(),
            TestServers.getInstance().getRpcTestPassword());
    RegTestEnvironment env = new RegTestEnvironment(client);
    RegTestFundingSource funder = new RegTestFundingSource(client);
    engine.put("client", client);
    engine.put("env", env);
    engine.put("funder", funder);
    engine.put("satoshi", (Function<Number, Coin>) satoshis -> Coin.valueOf(satoshis.longValue()));
    engine.put("btc", (Function<Number, Coin>) btc -> Coin.valueOf(btc.longValue() * Coin.COIN.longValue()));
    engine.put("coin", (BiFunction<Number, Number, Coin>) (btc, cents) -> Coin.valueOf(btc.intValue(), cents.intValue()));
    engine.put("getBlockCount", (Supplier<Integer>)() -> {
        try { return client.getBlockCount(); }
        catch (Exception e) { log.error("Exception: ", e); throw new RuntimeException(e); }
    });
}
 
Example #15
Source File: SeedPeersTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void getPeer_all() throws Exception{
    SeedPeers seedPeers = new SeedPeers(MainNetParams.get());
    for (int i = 0; i < MainNetParams.get().getAddrSeeds().length; ++i) {
        assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue());
    }
    assertThat(seedPeers.getPeer(), equalTo(null));
}
 
Example #16
Source File: BIP38PrivateKeyTest.java    From green_android 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 #17
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 #18
Source File: PaymentSession.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void parsePaymentRequest(Protos.PaymentRequest request) throws PaymentProtocolException {
    try {
        if (request == null)
            throw new PaymentProtocolException("request cannot be null");
        if (request.getPaymentDetailsVersion() != 1)
            throw new PaymentProtocolException.InvalidVersion("Version 1 required. Received version " + request.getPaymentDetailsVersion());
        paymentRequest = request;
        if (!request.hasSerializedPaymentDetails())
            throw new PaymentProtocolException("No PaymentDetails");
        paymentDetails = Protos.PaymentDetails.newBuilder().mergeFrom(request.getSerializedPaymentDetails()).build();
        if (paymentDetails == null)
            throw new PaymentProtocolException("Invalid PaymentDetails");
        if (!paymentDetails.hasNetwork())
            params = MainNetParams.get();
        else
            params = NetworkParameters.fromPmtProtocolID(paymentDetails.getNetwork());
        if (params == null)
            throw new PaymentProtocolException.InvalidNetwork("Invalid network " + paymentDetails.getNetwork());
        if (paymentDetails.getOutputsCount() < 1)
            throw new PaymentProtocolException.InvalidOutputs("No outputs");
        for (Protos.Output output : paymentDetails.getOutputsList()) {
            if (output.hasAmount())
                totalValue = totalValue.add(Coin.valueOf(output.getAmount()));
        }
        // This won't ever happen in practice. It would only happen if the user provided outputs
        // that are obviously invalid. Still, we don't want to silently overflow.
        if (params.hasMaxMoney() && totalValue.compareTo(params.getMaxMoney()) > 0)
            throw new PaymentProtocolException.InvalidOutputs("The outputs are way too big.");
    } catch (InvalidProtocolBufferException e) {
        throw new PaymentProtocolException(e);
    }
}
 
Example #19
Source File: DeterministicKeyChainTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void watchingChain() throws UnreadableWalletException {
    Utils.setMockClock();
    DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
    DeterministicKey key4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);

    NetworkParameters params = MainNetParams.get();
    DeterministicKey watchingKey = chain.getWatchingKey();
    final String pub58 = watchingKey.serializePubB58(params);
    assertEquals("xpub69KR9epSNBM59KLuasxMU5CyKytMJjBP5HEZ5p8YoGUCpM6cM9hqxB9DDPCpUUtqmw5duTckvPfwpoWGQUFPmRLpxs5jYiTf2u6xRMcdhDf", pub58);
    watchingKey = DeterministicKey.deserializeB58(null, pub58, params);
    watchingKey.setCreationTimeSeconds(100000);
    chain = DeterministicKeyChain.watch(watchingKey);
    assertEquals(100000, chain.getEarliestKeyCreationTime());
    chain.setLookaheadSize(10);
    chain.maybeLookAhead();

    assertEquals(key1.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
    assertEquals(key2.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
    final DeterministicKey key = chain.getKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals(key3.getPubKeyPoint(), key.getPubKeyPoint());
    try {
        // Can't sign with a key from a watching chain.
        key.sign(Sha256Hash.ZERO_HASH);
        fail();
    } catch (ECKey.MissingPrivateKeyException e) {
        // Ignored.
    }
    // Test we can serialize and deserialize a watching chain OK.
    List<Protos.Key> serialization = chain.serializeToProtobuf();
    checkSerialization(serialization, "watching-wallet-serialization.txt");
    chain = DeterministicKeyChain.fromProtobuf(serialization, null).get(0);
    final DeterministicKey rekey4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals(key4.getPubKeyPoint(), rekey4.getPubKeyPoint());
}
 
Example #20
Source File: ECKeyTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testToString() throws Exception {
    ECKey key = ECKey.fromPrivate(BigInteger.TEN).decompress(); // An example private key.
    NetworkParameters params = MainNetParams.get();
    assertEquals("ECKey{pub HEX=04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7, isEncrypted=false, isPubKeyOnly=false}", key.toString());
    assertEquals("ECKey{pub HEX=04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7, priv HEX=000000000000000000000000000000000000000000000000000000000000000a, priv WIF=5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreBoNWTw6, isEncrypted=false, isPubKeyOnly=false}", key.toStringWithPrivate(params));
}
 
Example #21
Source File: ECKeyTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void signTextMessage() throws Exception {
    ECKey key = new ECKey();
    String message = "聡中本";
    String signatureBase64 = key.signMessage(message);
    log.info("Message signed with " + key.toAddress(MainNetParams.get()) + ": " + signatureBase64);
    // Should verify correctly.
    key.verifyMessage(message, signatureBase64);
    try {
        key.verifyMessage("Evil attacker says hello!", signatureBase64);
        fail();
    } catch (SignatureException e) {
        // OK.
    }
}
 
Example #22
Source File: GaService.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static String getBech32Prefix(final NetworkParameters params) {
    if (params == MainNetParams.get())
        return "bc";
    if (params == TestNet3Params.get())
        return "tb";
    return "bcrt";
}
 
Example #23
Source File: BIP38PrivateKeyTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void bip38testvector_ecMultiply_noCompression_noLotAndSequence_test2() throws Exception {
    BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(),
            "6PfLGnQs6VZnrNpmVKfjotbnQuaJK4KZoPFrAjx1JMJUa1Ft8gnf5WxfKd");
    ECKey key = encryptedKey.decrypt("Satoshi");
    assertEquals("5KJ51SgxWaAYR13zd9ReMhJpwrcX47xTJh2D3fGPG9CM8vkv5sH", key.getPrivateKeyEncoded(MAINNET)
            .toString());
}
 
Example #24
Source File: BIP38PrivateKeyTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void bip38testvector_ecMultiply_noCompression_noLotAndSequence_test1() throws Exception {
    BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(),
            "6PfQu77ygVyJLZjfvMLyhLMQbYnu5uguoJJ4kMCLqWwPEdfpwANVS76gTX");
    ECKey key = encryptedKey.decrypt("TestingOneTwoThree");
    assertEquals("5K4caxezwjGCGfnoPTZ8tMcJBLB7Jvyjv4xxeacadhq8nLisLR2", key.getPrivateKeyEncoded(MAINNET)
            .toString());
}
 
Example #25
Source File: BlockChainTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void estimatedBlockTime() throws Exception {
    NetworkParameters params = MainNetParams.get();
    BlockChain prod = new BlockChain(new Context(params), new MemoryBlockStore(params));
    Date d = prod.estimateBlockTime(200000);
    // The actual date of block 200,000 was 2012-09-22 10:47:00
    assertEquals(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US).parse("2012-10-23T08:35:05.000-0700"), d);
}
 
Example #26
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_test2() throws Exception {
    BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MainNetParams.get(),
            "6PYLtMnXvfG3oJde97zRyLYFZCYizPU5T3LwgdYJz1fRhh16bU7u6PPmY7");
    ECKey key = encryptedKey.decrypt("Satoshi");
    assertEquals("KwYgW8gcxj1JWJXhPSu4Fqwzfhp5Yfi42mdYmMa4XqK7NJxXUSK7", key.getPrivateKeyEncoded(MAINNET)
            .toString());
}
 
Example #27
Source File: ECKeyTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void signTextMessage() throws Exception {
    ECKey key = new ECKey();
    String message = "聡中本";
    String signatureBase64 = key.signMessage(message);
    log.info("Message signed with " + key.toAddress(MainNetParams.get()) + ": " + signatureBase64);
    // Should verify correctly.
    key.verifyMessage(message, signatureBase64);
    try {
        key.verifyMessage("Evil attacker says hello!", signatureBase64);
        fail();
    } catch (SignatureException e) {
        // OK.
    }
}
 
Example #28
Source File: PaymentSessionTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = PaymentProtocolException.InvalidNetwork.class)
public void testWrongNetwork() throws Exception {
    // Create a PaymentRequest and make sure the correct values are parsed by the PaymentSession.
    MockPaymentSession paymentSession = new MockPaymentSession(newSimplePaymentRequest("main"));
    assertEquals(MainNetParams.get(), paymentSession.getNetworkParameters());

    // Send the payment and verify that the correct information is sent.
    // Add a dummy input to tx so it is considered valid.
    tx.addInput(new TransactionInput(PARAMS, tx, outputToMe.getScriptBytes()));
    ArrayList<Transaction> txns = new ArrayList<>();
    txns.add(tx);
    Address refundAddr = new Address(PARAMS, serverKey.getPubKeyHash());
    paymentSession.sendPayment(txns, refundAddr, paymentMemo);
    assertEquals(1, paymentSession.getPaymentLog().size());
}
 
Example #29
Source File: TransactionOutputTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testP2SHOutputScript() throws Exception {
    String P2SHAddressString = "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU";
    Address P2SHAddress = Address.fromBase58(MainNetParams.get(), P2SHAddressString);
    Script script = ScriptBuilder.createOutputScript(P2SHAddress);
    Transaction tx = new Transaction(MainNetParams.get());
    tx.addOutput(Coin.COIN, script);
    assertEquals(P2SHAddressString, tx.getOutput(0).getAddressFromP2SH(MainNetParams.get()).toString());
}
 
Example #30
Source File: ECKeyTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void verifyMessage() throws Exception {
    // Test vector generated by Bitcoin-Qt.
    String message = "hello";
    String sigBase64 = "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8=";
    Address expectedAddress = Address.fromBase58(MainNetParams.get(), "14YPSNPi6NSXnUxtPAsyJSuw3pv7AU3Cag");
    ECKey key = ECKey.signedMessageToKey(message, sigBase64);
    Address gotAddress = key.toAddress(MainNetParams.get());
    assertEquals(expectedAddress, gotAddress);
}