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


Java WalletAppKit.connectToLocalHost方法代码示例

本文整理汇总了Java中org.bitcoinj.kits.WalletAppKit.connectToLocalHost方法的典型用法代码示例。如果您正苦于以下问题:Java WalletAppKit.connectToLocalHost方法的具体用法?Java WalletAppKit.connectToLocalHost怎么用?Java WalletAppKit.connectToLocalHost使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.bitcoinj.kits.WalletAppKit的用法示例。


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

示例1: setupWalletKit

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void setupWalletKit(@Nullable DeterministicSeed seed) {
    // If seed is non-null it means we are restoring from backup.
    bitcoin = new WalletAppKit(params, new File("."), WALLET_FILE_NAME) {
        @Override
        protected void onSetupCompleted() {
            // Don't make the user wait for confirmations for now, as the intention is they're sending it
            // their own money!
            bitcoin.wallet().allowSpendingUnconfirmedTransactions();
            Platform.runLater(controller::onBitcoinSetup);
        }
    };
    // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
    // or progress widget to keep the user engaged whilst we initialise, but we don't.
    if (params == RegTestParams.get()) {
        bitcoin.connectToLocalHost();   // You should run a regtest mode bitcoind locally.
    } else if (params == TestNet3Params.get()) {
        // As an example!
        bitcoin.useTor();
        // bitcoin.setDiscovery(new HttpDiscovery(params, URI.create("http://localhost:8080/peers"), ECKey.fromPublicOnly(BaseEncoding.base16().decode("02cba68cfd0679d10b186288b75a59f9132b1b3e222f6332717cb8c4eb2040f940".toUpperCase()))));
    }
    bitcoin.setDownloadListener(controller.progressBarUpdater())
           .setBlockingStartup(false)
           .setUserAgent(APP_NAME, "1.0");
    if (seed != null)
        bitcoin.restoreWalletFromSeed(seed);
}
 
开发者ID:Grant-Redmond,项目名称:cryptwallet,代码行数:27,代码来源:Main.java

示例2: run

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void run() throws Exception {
    NetworkParameters params = RegTestParams.get();

    // 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));
        }
    };
    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(), 15, Coin.valueOf(100000), this).bindAndStart(4242);
}
 
开发者ID:HashEngineering,项目名称:namecoinj,代码行数:26,代码来源:ExamplePaymentChannelServer.java

示例3: setupWalletKit

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void setupWalletKit(@Nullable DeterministicSeed seed) {
    // If seed is non-null it means we are restoring from backup.
    bitcoin = new WalletAppKit(params, new File("."), WALLET_FILE_NAME) {
        @Override
        protected void onSetupCompleted() {
            // Don't make the user wait for confirmations for now, as the intention is they're sending it
            // their own money!
            bitcoin.wallet().allowSpendingUnconfirmedTransactions();
            Platform.runLater(controller::onBitcoinSetup);
        }
    };
    // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
    // or progress widget to keep the user engaged whilst we initialise, but we don't.
    if (params == RegTestParams.get()) {
        bitcoin.connectToLocalHost();   // You should run a regtest mode bitcoind locally.
    }
    bitcoin.setDownloadListener(controller.progressBarUpdater())
           .setBlockingStartup(false)
           .setUserAgent(APP_NAME, "1.0");
    if (seed != null)
        bitcoin.restoreWalletFromSeed(seed);
}
 
开发者ID:bitcoinj,项目名称:bitcoinj,代码行数:23,代码来源:Main.java

示例4: setupWalletKit

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void setupWalletKit(@Nullable DeterministicSeed seed) {
    // If seed is non-null it means we are restoring from backup.
    bitcoin = new WalletAppKit(params, new File("."), APP_NAME + "-" + params.getPaymentProtocolId()) {
        @Override
        protected void onSetupCompleted() {
            // Don't make the user wait for confirmations for now, as the intention is they're sending it
            // their own money!
            bitcoin.wallet().allowSpendingUnconfirmedTransactions();
            Platform.runLater(controller::onBitcoinSetup);
        }
    };
    // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
    // or progress widget to keep the user engaged whilst we initialise, but we don't.
    if (params == RegTestParams.get()) {
        bitcoin.connectToLocalHost();   // You should run a regtest mode bitcoind locally.
    } else if (params == TestNet3Params.get()) {
        // As an example!
        bitcoin.useTor();
        // bitcoin.setDiscovery(new HttpDiscovery(params, URI.create("http://localhost:8080/peers"), ECKey.fromPublicOnly(BaseEncoding.base16().decode("02cba68cfd0679d10b186288b75a59f9132b1b3e222f6332717cb8c4eb2040f940".toUpperCase()))));
    } else {
        bitcoin.useTor();
    }
    bitcoin.setDownloadListener(controller.progressBarUpdater())
           .setBlockingStartup(false)
           .setUserAgent(APP_NAME, "1.0");
    if (seed != null)
        bitcoin.restoreWalletFromSeed(seed);
}
 
开发者ID:Techsoul192,项目名称:legendary-guide,代码行数:29,代码来源:Main.java

示例5: setupWalletKit

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void setupWalletKit(@Nullable DeterministicSeed seed) {
    // If seed is non-null it means we are restoring from backup.
    bitcoin = new WalletAppKit(params, new File("."), APP_NAME) {
        @Override
        protected void onSetupCompleted() {
            // Don't make the user wait for confirmations for now, as the intention is they're sending it
            // their own money!
            bitcoin.wallet().allowSpendingUnconfirmedTransactions();
            if (params != RegTestParams.get())
                bitcoin.peerGroup().setMaxConnections(11);
            bitcoin.peerGroup().setBloomFilterFalsePositiveRate(0.00001);
            Platform.runLater(controller::onBitcoinSetup);
        }
    };
    // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
    // or progress widget to keep the user engaged whilst we initialise, but we don't.
    if (params == RegTestParams.get()) {
        bitcoin.connectToLocalHost();   // You should run a regtest mode bitcoind locally.
    } else if (params == MainNetParams.get()) {
        // Checkpoints are block headers that ship inside our app: for a new user, we pick the last header
        // in the checkpoints file and then download the rest from the network. It makes things much faster.
        // Checkpoint files are made using the BuildCheckpoints tool and usually we have to download the
        // last months worth or more (takes a few seconds).
        bitcoin.setCheckpoints(getClass().getResourceAsStream("checkpoints"));
    } else if (params == TestNet3Params.get()) {
        bitcoin.setCheckpoints(getClass().getResourceAsStream("checkpoints.testnet"));
        // As an example!
        bitcoin.useTor();
    }
    bitcoin.setDownloadListener(controller.progressBarUpdater())
           .setBlockingStartup(false)
           .setUserAgent(APP_NAME, "1.0");
    if (seed != null)
        bitcoin.restoreWalletFromSeed(seed);
}
 
开发者ID:HashEngineering,项目名称:namecoinj,代码行数:36,代码来源:Main.java

示例6: setupWalletKit

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void setupWalletKit(@Nullable DeterministicSeed seed) {
    // If seed is non-null it means we are restoring from backup.
    bitcoin = new WalletAppKit(params, new File("."), APP_NAME) {
        @Override
        protected void onSetupCompleted() {
            // Don't make the user wait for confirmations for now, as the intention is they're sending it
            // their own money!
            bitcoin.wallet().allowSpendingUnconfirmedTransactions();
            if (params != RegTestParams.get())
                bitcoin.peerGroup().setMaxConnections(11);
            bitcoin.peerGroup().setBloomFilterFalsePositiveRate(0.00001);
            Platform.runLater(controller::onBitcoinSetup);
        }
    };
    // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
    // or progress widget to keep the user engaged whilst we initialise, but we don't.
    if (params == RegTestParams.get()) {
        bitcoin.connectToLocalHost();   // You should run a regtest mode bitcoind locally.
    } else if (params == TestNet3Params.get()) {
        // As an example!
        //bitcoin.useTor();
        // bitcoin.setDiscovery(new HttpDiscovery(params, URI.create("http://localhost:8080/peers"), ECKey.fromPublicOnly(BaseEncoding.base16().decode("02cba68cfd0679d10b186288b75a59f9132b1b3e222f6332717cb8c4eb2040f940".toUpperCase()))));
    }
    bitcoin.setDownloadListener(controller.progressBarUpdater())
           .setBlockingStartup(false)
           .setUserAgent(APP_NAME, "1.0");
    if (seed != null)
        bitcoin.restoreWalletFromSeed(seed);
}
 
开发者ID:egordon,项目名称:CoinJoin,代码行数:30,代码来源:Main.java

示例7: setupWalletKit

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void setupWalletKit(@Nullable DeterministicSeed seed) {
    // If seed is non-null it means we are restoring from backup.
    bitcoin = new WalletAppKit(params, new File("."), APP_NAME) {
        @Override
        protected void onSetupCompleted() {
            // Don't make the user wait for confirmations for now, as the intention is they're sending it
            // their own money!
            bitcoin.wallet().allowSpendingUnconfirmedTransactions();
            if (params != RegTestParams.get())
                bitcoin.peerGroup().setMaxConnections(11);
            bitcoin.peerGroup().setBloomFilterFalsePositiveRate(0.00001);
            Platform.runLater(controller::onBitcoinSetup);
        }
    };
    // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
    // or progress widget to keep the user engaged whilst we initialise, but we don't.
    if (params == RegTestParams.get()) {
        bitcoin.connectToLocalHost();   // You should run a regtest mode bitcoind locally.
    } else if (params == TestNet3Params.get()) {
        // As an example!
        bitcoin.useTor();
    }
    bitcoin.setDownloadListener(controller.progressBarUpdater())
           .setBlockingStartup(false)
           .setUserAgent(APP_NAME, "1.0");
    if (seed != null)
        bitcoin.restoreWalletFromSeed(seed);
}
 
开发者ID:DigiByte-Team,项目名称:digibytej-alice,代码行数:29,代码来源:Main.java

示例8: run

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
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);
    }
 
开发者ID:HashEngineering,项目名称:dashj,代码行数:29,代码来源:ExamplePaymentChannelServer.java

示例9: main

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
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 = new Address(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().addEventListener(new AbstractWalletEventListener() {
        @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<Transaction>() {
                @Override
                public void onSuccess(Transaction result) {
                    // "result" here is the same as "tx" above, but we use it anyway for clarity.
                    forwardCoins(result);
                }

                @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) {}
}
 
开发者ID:HashEngineering,项目名称:namecoinj,代码行数:78,代码来源:ForwardingService.java

示例10: run

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void run(final String host) 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.
            return ImmutableList.<WalletExtension>of(new StoredPaymentChannelClientStates(null, peerGroup()));
        }
    };
    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 int timeoutSecs = 15;
    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(timeoutSecs, server, channelID, 5);
    log.info("Round two ...");
    log.info(appKit.wallet().toString());
    openAndSend(timeoutSecs, server, channelID, 4);   // 4 times because the opening of the channel made a payment.
    log.info("Stopping ...");
    appKit.stopAsync();
    appKit.awaitTerminated();
}
 
开发者ID:HashEngineering,项目名称:namecoinj,代码行数:47,代码来源:ExamplePaymentChannelClient.java

示例11: run

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void run(final String host) 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));
        }
    };
    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 int timeoutSecs = 15;
    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(timeoutSecs, server, channelID, 5);
    log.info("Round two ...");
    log.info(appKit.wallet().toString());
    openAndSend(timeoutSecs, server, channelID, 4);   // 4 times because the opening of the channel made a payment.
    log.info("Stopping ...");
    appKit.stopAsync();
    appKit.awaitTerminated();
}
 
开发者ID:DigiByte-Team,项目名称:digibytej-alice,代码行数:49,代码来源:ExamplePaymentChannelClient.java

示例12: run

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void run(final String host, PaymentChannelClient.VersionSelector versionSelector, 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, versionSelector);
    log.info("Round two ...");
    log.info(appKit.wallet().toString());
    openAndSend(timeoutSeconds, server, channelID, 4, versionSelector);   // 4 times because the opening of the channel made a payment.
    log.info("Stopping ...");
    appKit.stopAsync();
    appKit.awaitTerminated();
}
 
开发者ID:HashEngineering,项目名称:dashj,代码行数:52,代码来源:ExamplePaymentChannelClient.java

示例13: main

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
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) {}
}
 
开发者ID:bitcoinj,项目名称:bitcoinj,代码行数:77,代码来源:ForwardingService.java

示例14: run

import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
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();
}
 
开发者ID:bitcoinj,项目名称:bitcoinj,代码行数:52,代码来源:ExamplePaymentChannelClient.java


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