org.bitcoinj.params.TestNet3Params Java Examples

The following examples show how to use org.bitcoinj.params.TestNet3Params. 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: BlockTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testCoinbaseHeightTestnet() throws Exception {
    // Testnet block 21066 (hash 0000000004053156021d8e42459d284220a7f6e087bf78f30179c3703ca4eefa)
    // contains a coinbase transaction whose height is two bytes, which is
    // shorter than we see in most other cases.

    Block block = TestNet3Params.get().getDefaultSerializer().makeBlock(
        ByteStreams.toByteArray(getClass().getResourceAsStream("block_testnet21066.dat")));

    // Check block.
    assertEquals("0000000004053156021d8e42459d284220a7f6e087bf78f30179c3703ca4eefa", block.getHashAsString());
    block.verify(21066, EnumSet.of(Block.VerifyFlag.HEIGHT_IN_COINBASE));

    // Testnet block 32768 (hash 000000007590ba495b58338a5806c2b6f10af921a70dbd814e0da3c6957c0c03)
    // contains a coinbase transaction whose height is three bytes, but could
    // fit in two bytes. This test primarily ensures script encoding checks
    // are applied correctly.

    block = TestNet3Params.get().getDefaultSerializer().makeBlock(
        ByteStreams.toByteArray(getClass().getResourceAsStream("block_testnet32768.dat")));

    // Check block.
    assertEquals("000000007590ba495b58338a5806c2b6f10af921a70dbd814e0da3c6957c0c03", block.getHashAsString());
    block.verify(32768, EnumSet.of(Block.VerifyFlag.HEIGHT_IN_COINBASE));
}
 
Example #2
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 #3
Source File: AddressTest.java    From GreenBits 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 #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: NetworkThreadFactoryTest.java    From cate with MIT License 6 votes vote down vote up
/**
 * Generate a thread and confirm the context is set on it.
 */
@Test
public void shouldSetContextOnThread() throws InterruptedException {
    final Context expected = new Context(TestNet3Params.get());
    final Context broken = new Context(DogecoinTestNet3Params.get());
    final NetworkThreadFactory factory = new NetworkThreadFactory(expected);

    // Progagate the wrong context onto this thread
    Context.propagate(broken);
    assertEquals(broken, Context.get());

    final ThreadMonitor monitor = new ThreadMonitor();
    final Thread thread = factory.newThread(monitor);
    thread.run();
    thread.join();
    
    assertEquals(expected, monitor.actual);
}
 
Example #6
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 #7
Source File: BlockTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testCoinbaseHeightTestnet() throws Exception {
    // Testnet block 21066 (hash 0000000004053156021d8e42459d284220a7f6e087bf78f30179c3703ca4eefa)
    // contains a coinbase transaction whose height is two bytes, which is
    // shorter than we see in most other cases.

    Block block = TestNet3Params.get().getDefaultSerializer().makeBlock(
        ByteStreams.toByteArray(getClass().getResourceAsStream("block_testnet21066.dat")));

    // Check block.
    assertEquals("0000000004053156021d8e42459d284220a7f6e087bf78f30179c3703ca4eefa", block.getHashAsString());
    block.verify(21066, EnumSet.of(Block.VerifyFlag.HEIGHT_IN_COINBASE));

    // Testnet block 32768 (hash 000000007590ba495b58338a5806c2b6f10af921a70dbd814e0da3c6957c0c03)
    // contains a coinbase transaction whose height is three bytes, but could
    // fit in two bytes. This test primarily ensures script encoding checks
    // are applied correctly.

    block = TestNet3Params.get().getDefaultSerializer().makeBlock(
        ByteStreams.toByteArray(getClass().getResourceAsStream("block_testnet32768.dat")));

    // Check block.
    assertEquals("000000007590ba495b58338a5806c2b6f10af921a70dbd814e0da3c6957c0c03", block.getHashAsString());
    block.verify(32768, EnumSet.of(Block.VerifyFlag.HEIGHT_IN_COINBASE));
}
 
Example #8
Source File: SegWitP2WPKHTransaction.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    NetworkParameters params = TestNet3Params.get();
    final Coin fee = Coin.SATOSHI.times(10000);
    final Coin fundAmount = Coin.SATOSHI.times(405000000);

    final String segwitWIF = "cRynQP5ysWF3jmz5bFy16kqKRoSYzzArJru5349ADBwsoyKoh8aq";
    final ECKey segwitKey = DumpedPrivateKey.fromBase58(params, segwitWIF).getKey();
    final Script segwitPkScript = ScriptBuilder.createP2WPKHOutputScript(segwitKey);

    final Sha256Hash fundTxHash =
        Sha256Hash.wrap("e7e953f119179f71a58865f3d1ae2157847778404f89b48d0f695f786fba1dd4");

    // Sign segwit transaction
    final Address sendTo = Address.fromBase58(params, "mvpr4mkDSPYcbN6XW6xCveCLa38x23fs7B");
    final Coin outAmount = fundAmount.minus(fee);
    final Script outPkScript = ScriptBuilder.createOutputScript(sendTo);
    final TransactionOutPoint segwitOutPoint = new TransactionOutPoint(params, 0L, fundTxHash, fundAmount);
    final Transaction outTx = new Transaction(params);
    outTx.addOutput(outAmount, outPkScript);
    outTx.addSignedInput(segwitOutPoint, segwitPkScript, segwitKey);
    final Sha256Hash outTxHash = outTx.getHash();
    System.out.println(Hex.toHexString(outTx.bitcoinSerialize()));
    System.out.println(Hex.toHexString(outTxHash.getBytes()));
}
 
Example #9
Source File: PaymentProtocolTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testPaymentRequest() throws Exception {
    // Create
    PaymentRequest paymentRequest = PaymentProtocol.createPaymentRequest(TestNet3Params.get(), AMOUNT, TO_ADDRESS, MEMO,
            PAYMENT_URL, MERCHANT_DATA).build();
    byte[] paymentRequestBytes = paymentRequest.toByteArray();

    // Parse
    PaymentSession parsedPaymentRequest = PaymentProtocol.parsePaymentRequest(PaymentRequest
            .parseFrom(paymentRequestBytes));
    final List<Output> parsedOutputs = parsedPaymentRequest.getOutputs();
    assertEquals(1, parsedOutputs.size());
    assertEquals(AMOUNT, parsedOutputs.get(0).amount);
    assertArrayEquals(ScriptBuilder.createOutputScript(TO_ADDRESS).getProgram(), parsedOutputs.get(0).scriptData);
    assertEquals(MEMO, parsedPaymentRequest.getMemo());
    assertEquals(PAYMENT_URL, parsedPaymentRequest.getPaymentUrl());
    assertArrayEquals(MERCHANT_DATA, parsedPaymentRequest.getMerchantData());
}
 
Example #10
Source File: SimpleTransaction.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    NetworkParameters params = TestNet3Params.get();

    final String wif = "cVXrjQt281reTcZ6eieWnbDgZsFHKApoKnU4P7j82jEBrecJB75G";
    final ECKey key = DumpedPrivateKey.fromBase58(params, wif).getKey();
    final Address address = key.toAddress(params); // mhrwYyunFdkP7RuBZLMND7fhu8aH1QETfE
    final Sha256Hash txid = Sha256Hash.wrap("488d7c1595a8aee30ccf7bd82b2cc5b7fb94c5f256b55baa519675b72cbf2fdd");
    final Long index = 1L;
    final Coin amount = Coin.MILLICOIN;
    final TransactionOutPoint outPoint = new TransactionOutPoint(params, index, txid);
    final Script pkScript = ScriptBuilder.createOutputScript(address);

    // Build transaction
    final Address spendto = Address.fromBase58(params, "mpeoG6pjLH6yDodyjqTaLZuEz7LEjEbYa5");
    final Transaction transaction = new Transaction(params);
    final Coin fee = Coin.SATOSHI.times(10000);
    transaction.addOutput(amount.minus(fee), spendto);
    transaction.addSignedInput(outPoint, pkScript, key);
    final String id = Hex.toHexString(transaction.getHash().getBytes());
    System.out.println(Hex.toHexString(transaction.bitcoinSerialize()));
}
 
Example #11
Source File: FetchBlock.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();
    System.out.println("Connecting to node");
    final NetworkParameters params = TestNet3Params.get();

    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, blockStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.start();
    PeerAddress addr = new PeerAddress(params, InetAddress.getLocalHost());
    peerGroup.addAddress(addr);
    peerGroup.waitForPeers(1).get();
    Peer peer = peerGroup.getConnectedPeers().get(0);

    Sha256Hash blockHash = Sha256Hash.wrap(args[0]);
    Future<Block> future = peer.getBlock(blockHash);
    System.out.println("Waiting for node to send us the requested block: " + blockHash);
    Block block = future.get();
    System.out.println(block);
    peerGroup.stopAsync();
}
 
Example #12
Source File: SimpleTransaction.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    NetworkParameters params = TestNet3Params.get();

    final String wif = "cVXrjQt281reTcZ6eieWnbDgZsFHKApoKnU4P7j82jEBrecJB75G";
    final ECKey key = DumpedPrivateKey.fromBase58(params, wif).getKey();
    final Address address = key.toAddress(params); // mhrwYyunFdkP7RuBZLMND7fhu8aH1QETfE
    final Sha256Hash txid = Sha256Hash.wrap("488d7c1595a8aee30ccf7bd82b2cc5b7fb94c5f256b55baa519675b72cbf2fdd");
    final Long index = 1L;
    final Coin amount = Coin.MILLICOIN;
    final TransactionOutPoint outPoint = new TransactionOutPoint(params, index, txid);
    final Script pkScript = ScriptBuilder.createOutputScript(address);

    // Build transaction
    final Address spendto = Address.fromBase58(params, "mpeoG6pjLH6yDodyjqTaLZuEz7LEjEbYa5");
    final Transaction transaction = new Transaction(params);
    final Coin fee = Coin.SATOSHI.times(10000);
    transaction.addOutput(amount.minus(fee), spendto);
    transaction.addSignedInput(outPoint, pkScript, key);
    final String id = Hex.toHexString(transaction.getHash().getBytes());
    System.out.println(Hex.toHexString(transaction.bitcoinSerialize()));
}
 
Example #13
Source File: PaymentSession.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generates a Payment message based on the information in the PaymentRequest.
 * Provide transactions built by the wallet.
 * If the PaymentRequest did not specify a payment_url, returns null.
 * @param txns list of transactions to be included with the Payment message.
 * @param refundAddr will be used by the merchant to send money back if there was a problem.
 * @param memo is a message to include in the payment message sent to the merchant.
 */
@Nullable
public Protos.Payment getPayment(List<Transaction> txns, @Nullable Address refundAddr, @Nullable String memo)
        throws IOException, PaymentProtocolException.InvalidNetwork {
    if (paymentDetails.hasPaymentUrl()) {
        for (Transaction tx : txns) {
            // BIP70 doesn't allow for regtest in its network type. If we mismatch,
            // treat regtest transactions for a testnet payment request as a match.
            if (!tx.getParams().equals(params) &&
                (!tx.getParams().equals(RegTestParams.get()) || !params.equals(TestNet3Params.get())))
                throw new PaymentProtocolException.InvalidNetwork(params.getPaymentProtocolId());
        }
        return PaymentProtocol.createPaymentMessage(txns, totalValue, refundAddr, memo, getMerchantData());
    } else {
        return null;
    }
}
 
Example #14
Source File: PaymentProtocolTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testPaymentRequest() throws Exception {
    // Create
    PaymentRequest paymentRequest = PaymentProtocol.createPaymentRequest(TestNet3Params.get(), AMOUNT, TO_ADDRESS, MEMO,
            PAYMENT_URL, MERCHANT_DATA).build();
    byte[] paymentRequestBytes = paymentRequest.toByteArray();

    // Parse
    PaymentSession parsedPaymentRequest = PaymentProtocol.parsePaymentRequest(PaymentRequest
            .parseFrom(paymentRequestBytes));
    final List<Output> parsedOutputs = parsedPaymentRequest.getOutputs();
    assertEquals(1, parsedOutputs.size());
    assertEquals(AMOUNT, parsedOutputs.get(0).amount);
    assertArrayEquals(ScriptBuilder.createOutputScript(TO_ADDRESS).getProgram(), parsedOutputs.get(0).scriptData);
    assertEquals(MEMO, parsedPaymentRequest.getMemo());
    assertEquals(PAYMENT_URL, parsedPaymentRequest.getPaymentUrl());
    assertArrayEquals(MERCHANT_DATA, parsedPaymentRequest.getMerchantData());
}
 
Example #15
Source File: SegWitP2WPKHTransaction.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    NetworkParameters params = TestNet3Params.get();
    final Coin fee = Coin.SATOSHI.times(10000);
    final Coin fundAmount = Coin.SATOSHI.times(405000000);

    final String segwitWIF = "cRynQP5ysWF3jmz5bFy16kqKRoSYzzArJru5349ADBwsoyKoh8aq";
    final ECKey segwitKey = DumpedPrivateKey.fromBase58(params, segwitWIF).getKey();
    final Script segwitPkScript = ScriptBuilder.createP2WPKHOutputScript(segwitKey);

    final Sha256Hash fundTxHash =
        Sha256Hash.wrap("e7e953f119179f71a58865f3d1ae2157847778404f89b48d0f695f786fba1dd4");

    // Sign segwit transaction
    final Address sendTo = Address.fromBase58(params, "mvpr4mkDSPYcbN6XW6xCveCLa38x23fs7B");
    final Coin outAmount = fundAmount.minus(fee);
    final Script outPkScript = ScriptBuilder.createOutputScript(sendTo);
    final TransactionOutPoint segwitOutPoint = new TransactionOutPoint(params, 0L, fundTxHash, fundAmount);
    final Transaction outTx = new Transaction(params);
    outTx.addOutput(outAmount, outPkScript);
    outTx.addSignedInput(segwitOutPoint, segwitPkScript, segwitKey);
    final Sha256Hash outTxHash = outTx.getHash();
    System.out.println(Hex.toHexString(outTx.bitcoinSerialize()));
    System.out.println(Hex.toHexString(outTxHash.getBytes()));
}
 
Example #16
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 #17
Source File: FetchBlock.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();
    System.out.println("Connecting to node");
    final NetworkParameters params = TestNet3Params.get();

    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, blockStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.start();
    PeerAddress addr = new PeerAddress(params, InetAddress.getLocalHost());
    peerGroup.addAddress(addr);
    peerGroup.waitForPeers(1).get();
    Peer peer = peerGroup.getConnectedPeers().get(0);

    Sha256Hash blockHash = Sha256Hash.wrap(args[0]);
    Future<Block> future = peer.getBlock(blockHash);
    System.out.println("Waiting for node to send us the requested block: " + blockHash);
    Block block = future.get();
    System.out.println(block);
    peerGroup.stopAsync();
}
 
Example #18
Source File: PaymentSession.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generates a Payment message based on the information in the PaymentRequest.
 * Provide transactions built by the wallet.
 * If the PaymentRequest did not specify a payment_url, returns null.
 * @param txns list of transactions to be included with the Payment message.
 * @param refundAddr will be used by the merchant to send money back if there was a problem.
 * @param memo is a message to include in the payment message sent to the merchant.
 */
@Nullable
public Protos.Payment getPayment(List<Transaction> txns, @Nullable Address refundAddr, @Nullable String memo)
        throws IOException, PaymentProtocolException.InvalidNetwork {
    if (paymentDetails.hasPaymentUrl()) {
        for (Transaction tx : txns) {
            // BIP70 doesn't allow for regtest in its network type. If we mismatch,
            // treat regtest transactions for a testnet payment request as a match.
            if (!tx.getParams().equals(params) &&
                (!tx.getParams().equals(RegTestParams.get()) || !params.equals(TestNet3Params.get())))
                throw new PaymentProtocolException.InvalidNetwork(params.getPaymentProtocolId());
        }
        return PaymentProtocol.createPaymentMessage(txns, totalValue, refundAddr, memo, getMerchantData());
    } else {
        return null;
    }
}
 
Example #19
Source File: Util.java    From jelectrum with MIT License 5 votes vote down vote up
public static NetworkParameters getNetworkParameters(Config config)
{
  NetworkParameters network_params = MainNetParams.get();
  if (config.getBoolean("testnet"))
  { 
    network_params = TestNet3Params.get();
  }
  return network_params;

}
 
Example #20
Source File: SegWitP2WSHTransaction.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    NetworkParameters params = TestNet3Params.get();
    final Coin fee = Coin.SATOSHI.times(10000);
    final Coin fundAmount = Coin.SATOSHI.times(60700000);

    // Funding segwit address
    final String segwitWIF = "cU4tWJk3BGymoJgbGbxNA6NJapTwrbfWWaPsz1bCZBzkoeszb4ML";
    final ECKey segwitKey = DumpedPrivateKey.fromBase58(params, segwitWIF).getKey();
    final Script segwitScript = ScriptBuilder.createOutputScript(segwitKey);
    final Sha256Hash fundTxHash =
        Sha256Hash.wrap("09888a2fcfb9b982e2765e56c866f12c426687fc35be2a6de52ea956501c7778");

    // Sign segwit transaction
    final Address sendTo = Address.fromBase58(params, "mkoC1zHJJeNnyr8ttonNzh2ZZV4b9qAJtd");
    final Coin outAmount = fundAmount.minus(fee);
    final Script outPkScript = ScriptBuilder.createOutputScript(sendTo);
    final Transaction outTx = new Transaction(params);
    outTx.addOutput(outAmount, outPkScript);

    final TransactionInput input = outTx.addInput(fundTxHash, 0L, new Script(new byte[0]));
    final TransactionWitness witness = new TransactionWitness(2);
    Sha256Hash sigHash =
        outTx.hashForSignatureWitness(0, segwitScript, fundAmount, Transaction.SigHash.ALL, false);
    ECKey.ECDSASignature sig = segwitKey.sign(sigHash);
    TransactionSignature txSig = new TransactionSignature(sig, Transaction.SigHash.ALL, false);
    witness.setPush(0, txSig.encodeToBitcoin());
    witness.setPush(1, segwitScript.getProgram());

    outTx.setWitness(0, witness);

    final Sha256Hash outTxHash = outTx.getHash();
    System.out.println("Has witnesses: " + outTx.hasWitness());
    System.out.println(Hex.toHexString(outTx.bitcoinSerialize()));
    System.out.println(Hex.toHexString(outTxHash.getBytes()));
}
 
Example #21
Source File: BackupToMnemonicSeed.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {

        NetworkParameters params = TestNet3Params.get();
        Wallet wallet = new Wallet(params);

        DeterministicSeed seed = wallet.getKeyChainSeed();
        System.out.println("seed: " + seed.toString());

        System.out.println("creation time: " + seed.getCreationTimeSeconds());
        System.out.println("mnemonicCode: " + Utils.join(seed.getMnemonicCode()));
    }
 
Example #22
Source File: ECKeyTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void base58Encoding_leadingZero() throws Exception {
    String privkey = "91axuYLa8xK796DnBXXsMbjuc8pDYxYgJyQMvFzrZ6UfXaGYuqL";
    ECKey key = DumpedPrivateKey.fromBase58(TestNet3Params.get(), privkey).getKey();
    assertEquals(privkey, key.getPrivateKeyEncoded(TestNet3Params.get()).toString());
    assertEquals(0, key.getPrivKeyBytes()[0]);
}
 
Example #23
Source File: ECKeyTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void base58Encoding_stress() throws Exception {
    // Replace the loop bound with 1000 to get some keys with leading zero byte
    for (int i = 0 ; i < 20 ; i++) {
        ECKey key = new ECKey();
        ECKey key1 = DumpedPrivateKey.fromBase58(TestNet3Params.get(),
                key.getPrivateKeyEncoded(TestNet3Params.get()).toString()).getKey();
        assertEquals(Utils.HEX.encode(key.getPrivKeyBytes()),
                Utils.HEX.encode(key1.getPrivKeyBytes()));
    }
}
 
Example #24
Source File: ECKeyTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void base58Encoding() throws Exception {
    String addr = "mqAJmaxMcG5pPHHc3H3NtyXzY7kGbJLuMF";
    String privkey = "92shANodC6Y4evT5kFzjNFQAdjqTtHAnDTLzqBBq4BbKUPyx6CD";
    ECKey key = DumpedPrivateKey.fromBase58(TestNet3Params.get(), privkey).getKey();
    assertEquals(privkey, key.getPrivateKeyEncoded(TestNet3Params.get()).toString());
    assertEquals(addr, key.toAddress(TestNet3Params.get()).toString());
}
 
Example #25
Source File: RefreshWallet.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    File file = new File(args[0]);
    Wallet wallet = Wallet.loadFromFile(file);
    System.out.println(wallet.toString());

    // Set up the components and link them together.
    final NetworkParameters params = TestNet3Params.get();
    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, wallet, blockStore);

    final PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.startAsync();

    wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
        @Override
        public synchronized void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
            System.out.println("\nReceived tx " + tx.getHashAsString());
            System.out.println(tx.toString());
        }
    });

    // Now download and process the block chain.
    peerGroup.downloadBlockChain();
    peerGroup.stopAsync();
    wallet.saveToFile(file);
    System.out.println("\nDone!\n");
    System.out.println(wallet.toString());
}
 
Example #26
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 #27
Source File: BitcoinURITest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUnescapedPaymentProtocolReq() throws Exception {
    BitcoinURI uri = new BitcoinURI(TestNet3Params.get(),
            "bitcoin:?r=https://merchant.com/pay.php?h%3D2a8628fc2fbe");
    assertEquals("https://merchant.com/pay.php?h=2a8628fc2fbe", uri.getPaymentRequestUrl());
    assertEquals(ImmutableList.of("https://merchant.com/pay.php?h=2a8628fc2fbe"), uri.getPaymentRequestUrls());
    assertNull(uri.getAddress());
}
 
Example #28
Source File: AddressTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void getNetwork() throws Exception {
    NetworkParameters params = Address.getParametersFromAddress("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL");
    assertEquals(MainNetParams.get().getId(), params.getId());
    params = Address.getParametersFromAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv");
    assertEquals(TestNet3Params.get().getId(), params.getId());
}
 
Example #29
Source File: BitcoinURITest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test a broken URI (bad address type)
 */
@Test
public void testBad_IncorrectAddressType() {
    try {
        testObject = new BitcoinURI(TestNet3Params.get(), BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS);
        fail("Expecting BitcoinURIParseException");
    } catch (BitcoinURIParseException e) {
        assertTrue(e.getMessage().contains("Bad address"));
    }
}
 
Example #30
Source File: AddressTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void getNetwork() throws Exception {
    NetworkParameters params = Address.getParametersFromAddress("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL");
    assertEquals(MainNetParams.get().getId(), params.getId());
    params = Address.getParametersFromAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv");
    assertEquals(TestNet3Params.get().getId(), params.getId());
}