赞
踩
布隆过滤器(Bloom Filter):过滤掉那些不包含有目标地址的交易信息,这一步能避免掉大量不相关的数据下载。
//创建区块链文件
File blockChainFile = new File(getDir(“blockstore”, Context.MODE_PRIVATE), “blockchain”);
//创建SPVBlockStore,管理区块数据
blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
//加载检查点
final InputStream checkpointsInputStream = getAssets().open(“checkpoints-testnet.txt”);
CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream,
blockStore, earliestKeyCreationTime);
//创建区块链对象
blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
//添加网络权限:
private void startup() {
Log.d(TAG, "startup: ");
peerGroup = new PeerGroup(Constants.NETWORK_PARAMETERS, blockChain);
peerGroup.setDownloadTxDependencies(0); // recursive implementation causes StackOverflowError
peerGroup.addWallet(wallet);//设置钱包,重要
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES);
peerGroup.setUserAgent(USER_AGENT, packageInfo.versionName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
peerGroup.setMaxConnections(8);
int connectTimeout = (int) (15 * DateUtils.SECOND_IN_MILLIS);
peerGroup.setConnectTimeoutMillis(connectTimeout);
int discoveryTimeout = (int) (10 * DateUtils.SECOND_IN_MILLIS);
peerGroup.addConnectedEventListener(mPeerConnectedEventListener);
peerGroup.addDisconnectedEventListener(mPeerDisconnectedEventListener);
peerGroup.addDiscoveredEventListener(mPeerDiscoveredEventListener);
peerGroup.setPeerDiscoveryTimeoutMillis(discoveryTimeout);
//添加节点探索器,重要
peerGroup.addPeerDiscovery(new PeerDiscovery() {
private final PeerDiscovery normalPeerDiscovery = MultiplexingDiscovery
.forServices(Constants.NETWORK_PARAMETERS, 0);
@Override
public InetSocketAddress[] getPeers(final long services, final long timeoutValue,
final TimeUnit timeoutUnit) throws PeerDiscoveryException {
return normalPeerDiscovery.getPeers(services, timeoutValue, timeoutUnit);
}
@Override
public void shutdown() {
normalPeerDiscovery.shutdown();
}
});
peerGroup.startAsync();
peerGroup.startBlockChainDownload(null);
}
获取测试用比特币:testnet.manu.backend.hamburg/faucet 刚收到的币可能需要几分钟后才能使用
//监听比特币接受事件
wallet.addCoinsReceivedEventListener(mWalletListener);
//刷新余额
Coin balance = wallet.getBalance(Wallet.BalanceType.ESTIMATED);
比特币测试链转账查询 创建一个Tx,对Tx进行签名,对Tx进行P2P网络广播
Address address = Address.fromBase58(Constants.NETWORK_PARAMETERS, to);
//转账金额,以mBTC为单位
Coin coin = MonetaryFormat.MBTC.parse(amount);
//创建请求
SendRequest sendRequest = SendRequest.to(address, coin);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。