org.bitcoinj.params.RegTestParams Java Examples

The following examples show how to use org.bitcoinj.params.RegTestParams. 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: BitcoinExtendedClient.java    From consensusj with Apache License 2.0 6 votes vote down vote up
public BitcoinExtendedClient(NetworkParameters netParams, URI server, String rpcuser, String rpcpassword) {
        super(netParams, server, rpcuser, rpcpassword);
        if (netParams.getId().equals(RegTestParams.ID_REGTEST)) {
// TODO: If we want to do store mined coins on the client side, we might try this in the future
//
//            regTestMiningKey = new ECKey();
//            regTestMiningAddress = Address.fromKey(RegTestParams.get(), regTestMiningKey, defaultScriptType);
            try {
                regTestMiningAddress = this.getNewAddress();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            regTestMiningAddress = null;
        }
    }
 
Example #2
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 #3
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 #4
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 #5
Source File: NetworkData.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@JsonIgnore
public NetworkParameters getNetworkParameters() {
    switch (network == null ? "mainnet" : network) {
    case "mainnet":
        return MainNetParams.get();
    case "testnet":
        return TestNet3Params.get();
    case "regtest":
    case "localtest":
        return RegTestParams.get();
    default:
        return null;
    }
}
 
Example #6
Source File: ExamplePaymentChannelServer.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
public void run(NetworkParameters params) throws Exception {

        // Bring up all the objects we need, create/load a wallet, sync the chain, etc. We override WalletAppKit so we
        // can customize it by adding the extension objects - we have to do this before the wallet file is loaded so
        // the plugin that knows how to parse all the additional data is present during the load.
        appKit = new WalletAppKit(params, new File("."), "payment_channel_example_server") {
            @Override
            protected List<WalletExtension> provideWalletExtensions() {
                // The StoredPaymentChannelClientStates object is responsible for, amongst other things, broadcasting
                // the refund transaction if its lock time has expired. It also persists channels so we can resume them
                // after a restart.
                return ImmutableList.<WalletExtension>of(new StoredPaymentChannelServerStates(null));
            }
        };
        // Broadcasting can take a bit of time so we up the timeout for "real" networks
        final int timeoutSeconds = params.getId().equals(NetworkParameters.ID_REGTEST) ? 15 : 150;
        if (params == RegTestParams.get()) {
            appKit.connectToLocalHost();
        }
        appKit.startAsync();
        appKit.awaitRunning();

        System.out.println(appKit.wallet());

        // We provide a peer group, a wallet, a timeout in seconds, the amount we require to start a channel and
        // an implementation of HandlerFactory, which we just implement ourselves.
        new PaymentChannelServerListener(appKit.peerGroup(), appKit.wallet(), timeoutSeconds, Coin.valueOf(100000), this).bindAndStart(4242);
    }
 
Example #7
Source File: ExamplePaymentChannelServer.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public void run(NetworkParameters params) throws Exception {

        // Bring up all the objects we need, create/load a wallet, sync the chain, etc. We override WalletAppKit so we
        // can customize it by adding the extension objects - we have to do this before the wallet file is loaded so
        // the plugin that knows how to parse all the additional data is present during the load.
        appKit = new WalletAppKit(params, new File("."), "payment_channel_example_server") {
            @Override
            protected List<WalletExtension> provideWalletExtensions() {
                // The StoredPaymentChannelClientStates object is responsible for, amongst other things, broadcasting
                // the refund transaction if its lock time has expired. It also persists channels so we can resume them
                // after a restart.
                return ImmutableList.<WalletExtension>of(new StoredPaymentChannelServerStates(null));
            }
        };
        // Broadcasting can take a bit of time so we up the timeout for "real" networks
        final int timeoutSeconds = params.getId().equals(NetworkParameters.ID_REGTEST) ? 15 : 150;
        if (params == RegTestParams.get()) {
            appKit.connectToLocalHost();
        }
        appKit.startAsync();
        appKit.awaitRunning();

        System.out.println(appKit.wallet());

        // We provide a peer group, a wallet, a timeout in seconds, the amount we require to start a channel and
        // an implementation of HandlerFactory, which we just implement ourselves.
        new PaymentChannelServerListener(appKit.peerGroup(), appKit.wallet(), timeoutSeconds, Coin.valueOf(100000), this).bindAndStart(4242);
    }
 
Example #8
Source File: MockTestnetCoin.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public Regtest() {
    super(Network.REGTEST, RegTestParams.get());
}
 
Example #9
Source File: WalletsSetup.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public void initialize(@Nullable DeterministicSeed seed, ResultHandler resultHandler, ExceptionHandler exceptionHandler) {
    Log.traceCall();

    // Tell bitcoinj to execute event handlers on the JavaFX UI thread. This keeps things simple and means
    // we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener
    // we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in
    // a future version.

    Threading.USER_THREAD = UserThread.getExecutor();

    Timer timeoutTimer = UserThread.runAfter(() ->
            exceptionHandler.handleException(new TimeoutException("Wallet did not initialize in " +
                    STARTUP_TIMEOUT + " seconds.")), STARTUP_TIMEOUT);

    backupWallets();

    final Socks5Proxy socks5Proxy = preferences.getUseTorForBitcoinJ() ? socks5ProxyProvider.getSocks5Proxy() : null;
    log.info("Socks5Proxy for bitcoinj: socks5Proxy=" + socks5Proxy);

    walletConfig = new WalletConfig(params,
            socks5Proxy,
            walletDir,
            bisqEnvironment,
            userAgent,
            numConnectionForBtc,
            btcWalletFileName,
            BSQ_WALLET_FILE_NAME,
            SPV_CHAIN_FILE_NAME) {
        @Override
        protected void onSetupCompleted() {
            //We are here in the btcj thread Thread[ STARTING,5,main]
            super.onSetupCompleted();

            final PeerGroup peerGroup = walletConfig.peerGroup();

            // We don't want to get our node white list polluted with nodes from AddressMessage calls.
            if (preferences.getBitcoinNodes() != null && !preferences.getBitcoinNodes().isEmpty())
                peerGroup.setAddPeersFromAddressMessage(false);

            peerGroup.addConnectedEventListener((peer, peerCount) -> {
                // We get called here on our user thread
                numPeers.set(peerCount);
                connectedPeers.set(peerGroup.getConnectedPeers());
            });
            peerGroup.addDisconnectedEventListener((peer, peerCount) -> {
                // We get called here on our user thread
                numPeers.set(peerCount);
                connectedPeers.set(peerGroup.getConnectedPeers());
            });

            // Map to user thread
            UserThread.execute(() -> {
                addressEntryList.onWalletReady(walletConfig.getBtcWallet());
                timeoutTimer.stop();
                setupCompletedHandlers.stream().forEach(Runnable::run);
            });

            // onSetupCompleted in walletAppKit is not the called on the last invocations, so we add a bit of delay
            UserThread.runAfter(resultHandler::handleResult, 100, TimeUnit.MILLISECONDS);
        }
    };

    if (params == RegTestParams.get()) {
        walletConfig.setMinBroadcastConnections(1);
        if (regTestHost == RegTestHost.LOCALHOST) {
            walletConfig.setPeerNodesForLocalHost();
        } else if (regTestHost == RegTestHost.REG_TEST_SERVER) {
            walletConfig.setMinBroadcastConnections(1);
            configPeerNodesForRegTestServer();
        } else {
            configPeerNodes(socks5Proxy);
        }
    } else if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) {
        walletConfig.setMinBroadcastConnections(1);
        walletConfig.setPeerNodesForLocalHost();
    } else {
        configPeerNodes(socks5Proxy);
    }

    walletConfig.setDownloadListener(downloadListener)
            .setBlockingStartup(false);

    // If seed is non-null it means we are restoring from backup.
    walletConfig.setSeed(seed);

    walletConfig.addListener(new Service.Listener() {
        @Override
        public void failed(@NotNull Service.State from, @NotNull Throwable failure) {
            walletConfig = null;
            log.error("Service failure from state: {}; failure={}", from, failure);
            timeoutTimer.stop();
            UserThread.execute(() -> exceptionHandler.handleException(failure));
        }
    }, Threading.USER_THREAD);

    walletConfig.startAsync();
}
 
Example #10
Source File: Bitcoin.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public Regtest() {
    super(Network.REGTEST, RegTestParams.get());
}
 
Example #11
Source File: BSQ.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public Regtest() {
    super(Network.REGTEST, RegTestParams.get());
}
 
Example #12
Source File: RpcConfig.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Deprecated
public RpcConfig(URI uri, String username, String password) {
    this(RegTestParams.get(), uri, username, password);
}
 
Example #13
Source File: BitcoinExtendedClient.java    From consensusj with Apache License 2.0 4 votes vote down vote up
public BitcoinExtendedClient(RpcConfig config) {
    this(RegTestParams.get(), config.getURI(), config.getUsername(), config.getPassword());
}
 
Example #14
Source File: BitcoinExtendedClient.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Deprecated
public BitcoinExtendedClient(URI server, String rpcuser, String rpcpassword) {
    this(RegTestParams.get(), server, rpcuser, rpcpassword);
}
 
Example #15
Source File: WalletTool.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
private static void setup() throws BlockStoreException {
    if (store != null) return;  // Already done.
    // Will create a fresh chain if one doesn't exist or there is an issue with this one.
    boolean reset = !chainFileName.exists();
    if (reset) {
        // No chain, so reset the wallet as we will be downloading from scratch.
        System.out.println("Chain file is missing so resetting the wallet.");
        reset();
    }
    if (mode == ValidationMode.SPV) {
        store = new SPVBlockStore(params, chainFileName);
        chain = new BlockChain(params, wallet, store);
        if (reset) {
            try {
                CheckpointManager.checkpoint(params, CheckpointManager.openStream(params), store,
                        wallet.getEarliestKeyCreationTime());
                StoredBlock head = store.getChainHead();
                System.out.println("Skipped to checkpoint " + head.getHeight() + " at "
                        + Utils.dateTimeFormat(head.getHeader().getTimeSeconds() * 1000));
            } catch (IOException x) {
                System.out.println("Could not load checkpoints: " + x.getMessage());
            }
        }
    } else if (mode == ValidationMode.FULL) {
        FullPrunedBlockStore s = new H2FullPrunedBlockStore(params, chainFileName.getAbsolutePath(), 5000);
        store = s;
        chain = new FullPrunedBlockChain(params, wallet, s);
    }
    // This will ensure the wallet is saved when it changes.
    wallet.autosaveToFile(walletFile, 5, TimeUnit.SECONDS, null);
    if (peers == null) {
        peers = new PeerGroup(params, chain);
    }
    peers.setUserAgent("WalletTool", "1.0");
    if (params == RegTestParams.get())
        peers.setMinBroadcastConnections(1);
    peers.addWallet(wallet);
    if (options.has("peers")) {
        String peersFlag = (String) options.valueOf("peers");
        String[] peerAddrs = peersFlag.split(",");
        for (String peer : peerAddrs) {
            try {
                peers.addAddress(new PeerAddress(params, InetAddress.getByName(peer)));
            } catch (UnknownHostException e) {
                System.err.println("Could not understand peer domain name/IP address: " + peer + ": " + e.getMessage());
                System.exit(1);
            }
        }
    }
}
 
Example #16
Source File: ExamplePaymentChannelClient.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public void run(final String host, IPaymentChannelClient.ClientChannelProperties clientChannelProperties, final NetworkParameters params) throws Exception {
    // Bring up all the objects we need, create/load a wallet, sync the chain, etc. We override WalletAppKit so we
    // can customize it by adding the extension objects - we have to do this before the wallet file is loaded so
    // the plugin that knows how to parse all the additional data is present during the load.
    appKit = new WalletAppKit(params, new File("."), "payment_channel_example_client") {
        @Override
        protected List<WalletExtension> provideWalletExtensions() {
            // The StoredPaymentChannelClientStates object is responsible for, amongst other things, broadcasting
            // the refund transaction if its lock time has expired. It also persists channels so we can resume them
            // after a restart.
            // We should not send a PeerGroup in the StoredPaymentChannelClientStates constructor
            // since WalletAppKit will find it for us.
            return ImmutableList.<WalletExtension>of(new StoredPaymentChannelClientStates(null));
        }
    };
    // Broadcasting can take a bit of time so we up the timeout for "real" networks
    final int timeoutSeconds = params.getId().equals(NetworkParameters.ID_REGTEST) ? 15 : 150;
    if (params == RegTestParams.get()) {
        appKit.connectToLocalHost();
    }
    appKit.startAsync();
    appKit.awaitRunning();
    // We now have active network connections and a fully synced wallet.
    // Add a new key which will be used for the multisig contract.
    appKit.wallet().importKey(myKey);
    appKit.wallet().allowSpendingUnconfirmedTransactions();

    System.out.println(appKit.wallet());

    // Create the object which manages the payment channels protocol, client side. Tell it where the server to
    // connect to is, along with some reasonable network timeouts, the wallet and our temporary key. We also have
    // to pick an amount of value to lock up for the duration of the channel.
    //
    // Note that this may or may not actually construct a new channel. If an existing unclosed channel is found in
    // the wallet, then it'll re-use that one instead.
    final InetSocketAddress server = new InetSocketAddress(host, 4242);

    waitForSufficientBalance(channelSize);
    final String channelID = host;
    // Do this twice as each one sends 1/10th of a bitcent 5 times, so to send a bitcent, we do it twice. This
    // demonstrates resuming a channel that wasn't closed yet. It should close automatically once we run out
    // of money on the channel.
    log.info("Round one ...");
    openAndSend(timeoutSeconds, server, channelID, 5, clientChannelProperties);
    log.info("Round two ...");
    log.info(appKit.wallet().toString());
    openAndSend(timeoutSeconds, server, channelID, 4, clientChannelProperties);   // 4 times because the opening of the channel made a payment.
    log.info("Stopping ...");
    appKit.stopAsync();
    appKit.awaitTerminated();
}
 
Example #17
Source File: ExamplePaymentChannelClient.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public ExamplePaymentChannelClient() {
    channelSize = CENT;
    myKey = new ECKey();
    params = RegTestParams.get();
}
 
Example #18
Source File: ForwardingService.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    // This line makes the log output more compact and easily read, especially when using the JDK log adapter.
    BriefLogFormatter.init();
    if (args.length < 1) {
        System.err.println("Usage: address-to-send-back-to [regtest|testnet]");
        return;
    }

    // Figure out which network we should connect to. Each one gets its own set of files.
    NetworkParameters params;
    String filePrefix;
    if (args.length > 1 && args[1].equals("testnet")) {
        params = TestNet3Params.get();
        filePrefix = "forwarding-service-testnet";
    } else if (args.length > 1 && args[1].equals("regtest")) {
        params = RegTestParams.get();
        filePrefix = "forwarding-service-regtest";
    } else {
        params = MainNetParams.get();
        filePrefix = "forwarding-service";
    }
    // Parse the address given as the first parameter.
    forwardingAddress = Address.fromBase58(params, args[0]);

    // Start up a basic app using a class that automates some boilerplate.
    kit = new WalletAppKit(params, new File("."), filePrefix);

    if (params == RegTestParams.get()) {
        // Regression test mode is designed for testing and development only, so there's no public network for it.
        // If you pick this mode, you're expected to be running a local "bitcoind -regtest" instance.
        kit.connectToLocalHost();
    }

    // Download the block chain and wait until it's done.
    kit.startAsync();
    kit.awaitRunning();

    // We want to know when we receive money.
    kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
        @Override
        public void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
            // Runs in the dedicated "user thread" (see bitcoinj docs for more info on this).
            //
            // The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast).
            Coin value = tx.getValueSentToMe(w);
            System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx);
            System.out.println("Transaction will be forwarded after it confirms.");
            // Wait until it's made it into the block chain (may run immediately if it's already there).
            //
            // For this dummy app of course, we could just forward the unconfirmed transaction. If it were
            // to be double spent, no harm done. Wallet.allowSpendingUnconfirmedTransactions() would have to
            // be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common
            // case of waiting for a block.
            Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
                @Override
                public void onSuccess(TransactionConfidence result) {
                    forwardCoins(tx);
                }

                @Override
                public void onFailure(Throwable t) {
                    // This kind of future can't fail, just rethrow in case something weird happens.
                    throw new RuntimeException(t);
                }
            });
        }
    });

    Address sendToAddress = kit.wallet().currentReceiveKey().toAddress(params);
    System.out.println("Send coins to: " + sendToAddress);
    System.out.println("Waiting for coins to arrive. Press Ctrl-C to quit.");

    try {
        Thread.sleep(Long.MAX_VALUE);
    } catch (InterruptedException ignored) {}
}
 
Example #19
Source File: Network.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public Network(final InputStream json) throws GAException {

        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        try {
            final Map<String,Object> map = objectMapper.readValue(json, Map.class);
            final JSONMap jsonMap = new JSONMap(map);
            mName = jsonMap.getString("name");
            mLiquid = jsonMap.getBool("liquid");

            if (!mLiquid) {
                final String network = jsonMap.getString("network");
                switch (network == null ? "mainnet" : network) {
                    case "mainnet":
                        mNetworkParameters = MainNetParams.get();
                        break;
                    case "testnet":
                        mNetworkParameters = TestNet3Params.get();
                        break;
                    case "regtest":
                        mNetworkParameters = RegTestParams.get();
                        break;
                    default:
                        throw new GAException("Invalid Network");
                }
            }
            else
                mNetworkParameters = ElementsRegTestParams.get();

            mWampUrl = jsonMap.getString("wamp_url");
            mWampCertPins = (List<String>) jsonMap.get("wamp_cert_pins");
            mOnion = jsonMap.getString("wamp_url_onion");
            mBlockExplorers = new ArrayList<>();
            for (final Map<String,Object> m : (List<Map<String,Object>>) jsonMap.get("blockexplorers"))
                mBlockExplorers.add(new BlockExplorer(m.get("address").toString(), m.get("tx").toString()));

            mDepositPubkey = jsonMap.getString("deposit_pubkey");
            mDepositChainCode = jsonMap.getString("deposit_chain_code");

            mDefaultPeers =  jsonMap.get("default_peers") == null ? new ArrayList<>() : (List<String>) jsonMap.mData.get("default_peers") ;
        } catch (final IOException e) {
            throw new GAException("Invalid Network");
        }
    }
 
Example #20
Source File: Verifier.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
static Coin verify(final GaService service,
                   final Map<TransactionOutPoint, Coin> countedUtxoValues, final PreparedTransaction ptx,
                   final Address recipient, final Coin amount, final List<Boolean> input) {
    final int changeIdx;
    if (input == null)
        changeIdx = -1;
    else if (input.get(0))
        changeIdx = 0;
    else if (input.get(1))
        changeIdx = 1;
    else
        throw new IllegalArgumentException("Verification: Change output missing.");

    if (input != null && input.get(0) && input.get(1)) {
        // Shouldn't happen really. In theory user can send money to a new change address
        // of themselves which they've generated manually, but it's unlikely, so for
        // simplicity we don't handle it.
        throw new IllegalArgumentException("Verification: Cannot send to a change address.");
    }
    final TransactionOutput output = ptx.mDecoded.getOutputs().get(1 - Math.abs(changeIdx));
    if (recipient != null) {
        final Address gotAddress = output.getScriptPubKey().getToAddress(service.getNetworkParameters());
        if (!gotAddress.equals(recipient))
            throw new IllegalArgumentException("Verification: Invalid recipient address.");
    }
    if (amount != null && !output.getValue().equals(amount))
        throw new IllegalArgumentException("Verification: Invalid output amount.");

    // 3. Verify fee value
    Coin fee = Coin.ZERO;
    for (final TransactionInput in : ptx.mDecoded.getInputs()) {
        if (countedUtxoValues.get(in.getOutpoint()) != null) {
            fee = fee.add(countedUtxoValues.get(in.getOutpoint()));
            continue;
        }

        final Transaction prevTx = ptx.mPrevoutRawTxs.get(in.getOutpoint().getHash().toString());
        if (!prevTx.getHash().equals(in.getOutpoint().getHash()))
            throw new IllegalArgumentException("Verification: Prev tx hash invalid");
        fee = fee.add(prevTx.getOutput((int) in.getOutpoint().getIndex()).getValue());
    }
    for (final TransactionOutput out : ptx.mDecoded.getOutputs())
        fee = fee.subtract(out.getValue());

    final double messageSize = ptx.mDecoded.getMessageSize();
    final double satoshiPerByte = fee.value / messageSize;
    final double satoshiPerKiloByte = satoshiPerByte * 1000.0;
    final Coin feeRate = Coin.valueOf((int) satoshiPerKiloByte);

    final Coin minFeeRate = service.getMinFeeRate();
    if (feeRate.isLessThan(minFeeRate) && service.getNetworkParameters() != RegTestParams.get())
        feeError("small", feeRate, minFeeRate);

    final Coin maxFeeRate = Coin.valueOf(15000 * 1000); // FIXME: Get max fee rate from server
    if (feeRate.isGreaterThan(maxFeeRate))
        feeError("large", feeRate, maxFeeRate);

    return amount == null ? output.getValue() : fee;
}
 
Example #21
Source File: WalletTool.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
private static void setup() throws BlockStoreException {
    if (store != null) return;  // Already done.
    // Will create a fresh chain if one doesn't exist or there is an issue with this one.
    boolean reset = !chainFileName.exists();
    if (reset) {
        // No chain, so reset the wallet as we will be downloading from scratch.
        System.out.println("Chain file is missing so resetting the wallet.");
        reset();
    }
    if (mode == ValidationMode.SPV) {
        store = new SPVBlockStore(params, chainFileName);
        chain = new BlockChain(params, wallet, store);
        if (reset) {
            try {
                CheckpointManager.checkpoint(params, CheckpointManager.openStream(params), store,
                        wallet.getEarliestKeyCreationTime());
                StoredBlock head = store.getChainHead();
                System.out.println("Skipped to checkpoint " + head.getHeight() + " at "
                        + Utils.dateTimeFormat(head.getHeader().getTimeSeconds() * 1000));
            } catch (IOException x) {
                System.out.println("Could not load checkpoints: " + x.getMessage());
            }
        }
    } else if (mode == ValidationMode.FULL) {
        FullPrunedBlockStore s = new H2FullPrunedBlockStore(params, chainFileName.getAbsolutePath(), 5000);
        store = s;
        chain = new FullPrunedBlockChain(params, wallet, s);
    }
    // This will ensure the wallet is saved when it changes.
    wallet.autosaveToFile(walletFile, 5, TimeUnit.SECONDS, null);
    if (peers == null) {
        peers = new PeerGroup(params, chain);
    }
    peers.setUserAgent("WalletTool", "1.0");
    if (params == RegTestParams.get())
        peers.setMinBroadcastConnections(1);
    peers.addWallet(wallet);
    if (options.has("peers")) {
        String peersFlag = (String) options.valueOf("peers");
        String[] peerAddrs = peersFlag.split(",");
        for (String peer : peerAddrs) {
            try {
                peers.addAddress(new PeerAddress(params, InetAddress.getByName(peer)));
            } catch (UnknownHostException e) {
                System.err.println("Could not understand peer domain name/IP address: " + peer + ": " + e.getMessage());
                System.exit(1);
            }
        }
    }
}
 
Example #22
Source File: ExamplePaymentChannelClient.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public void run(final String host, IPaymentChannelClient.ClientChannelProperties clientChannelProperties, final NetworkParameters params) throws Exception {
    // Bring up all the objects we need, create/load a wallet, sync the chain, etc. We override WalletAppKit so we
    // can customize it by adding the extension objects - we have to do this before the wallet file is loaded so
    // the plugin that knows how to parse all the additional data is present during the load.
    appKit = new WalletAppKit(params, new File("."), "payment_channel_example_client") {
        @Override
        protected List<WalletExtension> provideWalletExtensions() {
            // The StoredPaymentChannelClientStates object is responsible for, amongst other things, broadcasting
            // the refund transaction if its lock time has expired. It also persists channels so we can resume them
            // after a restart.
            // We should not send a PeerGroup in the StoredPaymentChannelClientStates constructor
            // since WalletAppKit will find it for us.
            return ImmutableList.<WalletExtension>of(new StoredPaymentChannelClientStates(null));
        }
    };
    // Broadcasting can take a bit of time so we up the timeout for "real" networks
    final int timeoutSeconds = params.getId().equals(NetworkParameters.ID_REGTEST) ? 15 : 150;
    if (params == RegTestParams.get()) {
        appKit.connectToLocalHost();
    }
    appKit.startAsync();
    appKit.awaitRunning();
    // We now have active network connections and a fully synced wallet.
    // Add a new key which will be used for the multisig contract.
    appKit.wallet().importKey(myKey);
    appKit.wallet().allowSpendingUnconfirmedTransactions();

    System.out.println(appKit.wallet());

    // Create the object which manages the payment channels protocol, client side. Tell it where the server to
    // connect to is, along with some reasonable network timeouts, the wallet and our temporary key. We also have
    // to pick an amount of value to lock up for the duration of the channel.
    //
    // Note that this may or may not actually construct a new channel. If an existing unclosed channel is found in
    // the wallet, then it'll re-use that one instead.
    final InetSocketAddress server = new InetSocketAddress(host, 4242);

    waitForSufficientBalance(channelSize);
    final String channelID = host;
    // Do this twice as each one sends 1/10th of a bitcent 5 times, so to send a bitcent, we do it twice. This
    // demonstrates resuming a channel that wasn't closed yet. It should close automatically once we run out
    // of money on the channel.
    log.info("Round one ...");
    openAndSend(timeoutSeconds, server, channelID, 5, clientChannelProperties);
    log.info("Round two ...");
    log.info(appKit.wallet().toString());
    openAndSend(timeoutSeconds, server, channelID, 4, clientChannelProperties);   // 4 times because the opening of the channel made a payment.
    log.info("Stopping ...");
    appKit.stopAsync();
    appKit.awaitTerminated();
}
 
Example #23
Source File: ExamplePaymentChannelClient.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public ExamplePaymentChannelClient() {
    channelSize = CENT;
    myKey = new ECKey();
    params = RegTestParams.get();
}
 
Example #24
Source File: ForwardingService.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    // This line makes the log output more compact and easily read, especially when using the JDK log adapter.
    BriefLogFormatter.init();
    if (args.length < 1) {
        System.err.println("Usage: address-to-send-back-to [regtest|testnet]");
        return;
    }

    // Figure out which network we should connect to. Each one gets its own set of files.
    NetworkParameters params;
    String filePrefix;
    if (args.length > 1 && args[1].equals("testnet")) {
        params = TestNet3Params.get();
        filePrefix = "forwarding-service-testnet";
    } else if (args.length > 1 && args[1].equals("regtest")) {
        params = RegTestParams.get();
        filePrefix = "forwarding-service-regtest";
    } else {
        params = MainNetParams.get();
        filePrefix = "forwarding-service";
    }
    // Parse the address given as the first parameter.
    forwardingAddress = Address.fromBase58(params, args[0]);

    // Start up a basic app using a class that automates some boilerplate.
    kit = new WalletAppKit(params, new File("."), filePrefix);

    if (params == RegTestParams.get()) {
        // Regression test mode is designed for testing and development only, so there's no public network for it.
        // If you pick this mode, you're expected to be running a local "bitcoind -regtest" instance.
        kit.connectToLocalHost();
    }

    // Download the block chain and wait until it's done.
    kit.startAsync();
    kit.awaitRunning();

    // We want to know when we receive money.
    kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
        @Override
        public void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
            // Runs in the dedicated "user thread" (see bitcoinj docs for more info on this).
            //
            // The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast).
            Coin value = tx.getValueSentToMe(w);
            System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx);
            System.out.println("Transaction will be forwarded after it confirms.");
            // Wait until it's made it into the block chain (may run immediately if it's already there).
            //
            // For this dummy app of course, we could just forward the unconfirmed transaction. If it were
            // to be double spent, no harm done. Wallet.allowSpendingUnconfirmedTransactions() would have to
            // be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common
            // case of waiting for a block.
            Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
                @Override
                public void onSuccess(TransactionConfidence result) {
                    forwardCoins(tx);
                }

                @Override
                public void onFailure(Throwable t) {
                    // This kind of future can't fail, just rethrow in case something weird happens.
                    throw new RuntimeException(t);
                }
            });
        }
    });

    Address sendToAddress = kit.wallet().currentReceiveKey().toAddress(params);
    System.out.println("Send coins to: " + sendToAddress);
    System.out.println("Waiting for coins to arrive. Press Ctrl-C to quit.");

    try {
        Thread.sleep(Long.MAX_VALUE);
    } catch (InterruptedException ignored) {}
}
 
Example #25
Source File: NetworkData.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@JsonIgnore
public boolean isRegtest() { return getNetworkParameters() == RegTestParams.get(); }
 
Example #26
Source File: Bitcoin.java    From bisq-assets with GNU Affero General Public License v3.0 4 votes vote down vote up
public Regtest() {
    super(Network.REGTEST, RegTestParams.get());
}
 
Example #27
Source File: BSQ.java    From bisq-assets with GNU Affero General Public License v3.0 4 votes vote down vote up
public Regtest() {
    super(Network.REGTEST, RegTestParams.get());
}
 
Example #28
Source File: BitcoinClient.java    From consensusj with Apache License 2.0 2 votes vote down vote up
/**
 * Construct a BitcoinClient from URI, user name, and password.
 * @param server URI of the Bitcoin RPC server
 * @param rpcuser Username (if required)
 * @param rpcpassword Password (if required)
 * @deprecated You need to specify NetworkParameters, this constructor defaults to RegTest
 * @see BitcoinClient#BitcoinClient(NetworkParameters, URI, String, String)
 */
@Deprecated
public BitcoinClient(URI server, String rpcuser, String rpcpassword) {
    this(RegTestParams.get(), server, rpcuser, rpcpassword);
}
 
Example #29
Source File: Network.java    From GreenBits with GNU General Public License v3.0 votes vote down vote up
public boolean isRegtest() { return mNetworkParameters == RegTestParams.get(); }