BitCoinJ之Hello World示例程序
简介
比特币(BitCoin)是一种基于区块链(BlockChain)技术的数字化货币. 本文介绍了使用基于Java语言的BitCoinJ API实现一个简单的收取和支付比特币的示例程序.
开发环境
本示例使用BitCoinJ(https://bitcoinj.github.io/) API, 目前的发布版本是0.14.3, 其JAR包可以从官网下载, 也可以通过如下的Maven定义在项目POM中引用.
<dependencies>
<dependency>
<groupId>org.bitcoinj</groupId>
<artifactId>bitcoinj-core</artifactId>
<version>0.14.3</version>
<scope>compile</scope>
</dependency>
</dependencies>
收取比特币
收取比特币的示例代码如下
public class BitCoinHelloWorld implements WalletCoinsReceivedEventListener {
public static void main(String[] args) {
BitCoinHelloWorld demo = new BitCoinHelloWorld();
demo.run();
}
public void run() {
try {
init();
System.out.println("Waiting for coins...");
while (true) {
Thread.sleep(20);
}
} catch (BlockStoreException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void init() throws BlockStoreException {
NetworkParameters params = TestNet3Params.get();
ECKey key = new ECKey();
System.out.println("We created a new key:\n" + key);
Address addressFromKey = key.toAddress(params);
System.out.println("Public Address generated: " + addressFromKey);
System.out.println("Private key is: " + key.getPrivateKeyEncoded(params).toString());
Wallet wallet = new Wallet(params);
wallet.importKey(key);
File blockFile = new File("/tmp/bitcoin-blocks");
SPVBlockStore blockStore = new SPVBlockStore(params, blockFile);
BlockChain blockChain = new BlockChain(params, wallet, blockStore);
PeerGroup peerGroup = new PeerGroup(params, blockChain);
peerGroup.addPeerDiscovery(new DnsDiscovery(params));
peerGroup.addWallet(wallet);
System.out.println("Start peer group");
peerGroup.start();
System.out.println("Downloading block chain");
peerGroup.downloadBlockChain();
System.out.println("Block chain downloaded");
wallet.addCoinsReceivedEventListener(this);
}
@Override
public void onCoinsReceived(final Wallet wallet, final Transaction transaction, Coin prevBalance, Coin newBalance) {
final Coin value = transaction.getValueSentToMe(wallet);
System.out.println("Received tx for " + value.toFriendlyString() + ": " + transaction);
System.out.println("Previous balance is " + prevBalance.toFriendlyString());
System.out.println("New estimated balance is " + newBalance.toFriendlyString());
System.out.println("Coin received, wallet balance is :" + wallet.getBalance());
Futures.addCallback(transaction.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
public void onSuccess(TransactionConfidence result) {
System.out.println("Transaction confirmed, wallet balance is :" + wallet.getBalance());
}
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
}
}
该示例程序首先调用init方法进行初始化, 然后进入一个等待循环, 当有比特币到来时, onCoinsReceived方法就被触发.
各个步骤的具体分析如下
选择运行环境
比特币应用可以在三种不同的环境中运行: 正式流通网络, 测试流通网络以及本地开发环境. 初始化的第一步是通过设置一个NetworkParameters变量来选择运行环境, 以下代码使用测试流通网络
NetworkParameters params = TestNet3Params.get();
获取地址和设置钱包对象
以下代码首先创建一个可用于接受比特币的地址, 并将其导入相应的钱包对象中.
ECKey key = new ECKey();
System.out.println("We created a new key:\n" + key);
Address addressFromKey = key.toAddress(params);
System.out.println("Public Address generated: " + addressFromKey);
System.out.println("Private key is: " + key.getPrivateKeyEncoded(params).toString());
Wallet wallet = new Wallet(params);
wallet.importKey(key);
接入流通网络并下载比特币区块
以下代码接入流通网络并下载比特币区块
File blockFile = new File("/tmp/bitcoin-blocks");
SPVBlockStore blockStore = new SPVBlockStore(params, blockFile);
BlockChain blockChain = new BlockChain(params, wallet, blockStore);
PeerGroup peerGroup = new PeerGroup(params, blockChain);
peerGroup.addPeerDiscovery(new DnsDiscovery(params));
peerGroup.addWallet(wallet);
System.out.println("Start peer group");
peerGroup.start();
System.out.println("Downloading block chain");
peerGroup.downloadBlockChain();
System.out.println("Block chain downloaded");
需要注意的是peerGroup.downloadBlockChain();这一步可能会运行很长时间.
设置事件响应
以下代码设置当比特币到来时的事件响应
wallet.addCoinsReceivedEventListener(this);
比特币到来事件响应
当比特币到来时onCoinsReceived方法就会触发, 注意该方法的newBalance参数提供的是钱包中金额的估计值,其实际金额要等到交易被网络确认后才会提现在wallet.getBalance()的返回值中, 如以下代码所示
Futures.addCallback(transaction.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
public void onSuccess(TransactionConfidence result) {
System.out.println("Transaction confirmed, wallet balance is :" + wallet.getBalance());
}
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
支付比特币
支付比特币的过程相对简单, 首选设置要支付的金额.
final Coin amountToSend = Coin.valueOf(10, 0);
其次设置接收方的地址
Address toAddress = Address.fromBase58(params, "n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi");
然后发送该支付交易
final Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, toAddress, amountToSend);
并设置交易完成后的事件响应
sendResult.broadcastComplete.addListener(new Runnable() {
@Override
public void run() {
System.out.println("Coins Sent! Transaction hash is " + sendResult.tx.getHashAsString());
}
}, MoreExecutors.sameThreadExecutor());
总结
本文给出了一个基于BitCoinJ的比特币收发示例程序, 并对BitCoinJ的编程模式以及其事件响应机制做了初步介绍.
BitCoinJ之Hello World示例程序的更多相关文章
- 通过Jexus 部署 dotnetcore版本MusicStore 示例程序
ASPNET Music Store application 是一个展示最新的.NET 平台(包括.NET Core/Mono等)上使用MVC 和Entity Framework的示例程序,本文将展示 ...
- .NET跨平台:在Ubuntu上用自己编译的dnx运行ASP.NET 5示例程序
在 Linux Ubuntu 上成功编译 dnx 之后,会在 artifacts/build/ 文件夹中生成 dnx-coreclr-linux-x64/ 与 dnx-mono/ 这2个文件夹,前者是 ...
- .NET跨平台:在CentOS上编译dnx并运行ASP.NET 5示例程序
在之前的博文中我们在 Ubuntu 上成功编译出了 dnx ,并且用它成功运行了 ASP.NET 5 示例程序.在这篇博文中我们将 Ubuntu 换成 CentOS. 目前 dnx 的编译需要用到 m ...
- Salesforce Apex 使用JSON数据的示例程序
本文介绍了一个在Salesforce Apex中使用JSON数据的示例程序, 该示例程序由以下几部分组成: 1) Album.cls, 定了了封装相关字段的数据Model类 2) RestClient ...
- osg 示例程序解析之osgdelaunay
osg 示例程序解析之osgdelaunay 转自:http://lzchenheng.blog.163.com/blog/static/838335362010821103038928/ 本示例程序 ...
- DotNetBar for Windows Forms 12.7.0.10_冰河之刃重打包版原创发布-带官方示例程序版
关于 DotNetBar for Windows Forms 12.7.0.10_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版------------- ...
- DotNetBar for Windows Forms 12.5.0.2_冰河之刃重打包版原创发布-带官方示例程序版
关于 DotNetBar for Windows Forms 12.5.0.2_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版-------------- ...
- DotNetBar for Windows Forms 12.2.0.7_冰河之刃重打包版原创发布-带官方示例程序版
关于 DotNetBar for Windows Forms 12.2.0.7_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版-------------- ...
- ACEXML解析XML文件——简单示例程序
掌握了ACMXML库解析XML文件的方法后,下面来实现一个比较完整的程序. 定义基本结构 xml文件格式如下 <?xml version="1.0"?> <roo ...
随机推荐
- HTML5学习生涯1--touchmove中遇到的问题
在使用html5做在手机上显示轮播图片的效果时突然遇到touchmove事件在touchstart事件之后只触发了一次touchmove之后和touchend一起触发了一次,咦,这是怎么回事?怎么不和 ...
- 桌面 透明 三角形 分层窗口 DX
//桌面 透明 三角形 分层窗口 DX //IDirect3DSurface9 GetDC UpdateLayeredWindow #include <Windows.h> #includ ...
- android知识杂记(二)
记录项目中的android零碎知识点,用以备忘. AsyncQueryHandler 继承与handler,可以用于处理增删改(ContentProvider提供的数据) 例如:query = new ...
- objective-c(继承)
objective-c的继承给出基础例子及注意点: 定义并实现基类ClassA #import <Foundation/Foundation.h> @interface ClassA : ...
- 由一篇文章引发的思考——多线程处理大数组
今天领导给我们发了一篇文章文章,让我们学习一下. 文章链接:TAM - Threaded Array Manipulator 这是codeproject上的一篇文章,花了一番时间阅读了一下.文章主要是 ...
- 来看看Windows9到底是什么
今天有新闻一直在说windows 8.2 windows9,还给出了一张很有趣的图 我们就假设这张图是真的. 这张图透漏出两个信息 其一:开始菜单真的回来了. 不过还是不死心,绝不放弃开始屏,确实,开 ...
- Visual Studio 2015速递(3)——ASP.NET 新特性
系列文章 Visual Studio 2015速递(1)——C#6.0新特性怎么用 Visual Studio 2015速递(2)——提升效率和质量(VS2015核心竞争力) Visual Studi ...
- Hibernate中对象的三个状态解析
Hibernate 将操作的对象分为三种状态: 1. 瞬时 (Transient )/临时状态/自由状态 持久 (Persistent) 脱管 (Detached) 瞬时对象特征: 第一.不处于 Se ...
- DDD~领域层
回到目录 再论Domain与Infrastructure 在面向领域的设计中,领域层(Domain)实现上是位于最底层的,其它层有对它的引用,包括基础设施层(Infrastructure)也是去引用领 ...
- Atitit rgb yuv hsv HSL 模式和 HSV(HSB) 图像色彩空间的区别
Atitit rgb yuv hsv HSL 模式和 HSV(HSB) 图像色彩空间的区别 1.1. 色彩的三要素 -- 色相.明度.纯度1 1.2. YUV三个字母中,其中"Y&quo ...