什么都不必说--bitcionj

Gradle

    //bitcionj依赖
    implementation 'org.bitcoinj:bitcoinj-core:0.14.7'
复制代码

创建钱包

    WalletAppKit kit = new WalletAppKit(TestNet3Params.get(), ".","walletName" );
    //自动保存
    kit.setAutoSave(true);
    //后台区块下载
    kit.setBlockingStartup(false);
    //开始运行
    kit.startAsync();
    kit.awaitRunning();
    //添加监听事件
    kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
        @Override
        public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
            final Coin value = tx.getValueSentToMe(wallet);
            System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx);
            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(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
                @Override
                public void onSuccess(TransactionConfidence result) {
                    // "result" here is the same as "tx" above, but we use it anyway for clarity.
                    System.out.println("call back is success:"+result.toString());
                }
                @Override
                public void onFailure(Throwable t) {}
            });
        }
    });
        
复制代码

查看钱包信息

    System.out.println("===========钱包信息==========");
    System.out.println(kit.getWallet().toString());
    System.out.println("历史接受地址 : " +  kit.getWallet().getIssuedReceiveAddresses());
    System.out.println("区块更新时间 : " + (kit.getWallet().getLastBlockSeenTime() != null ? TimeUtils.date2String(kit.getWallet().getLastBlockSeenTime()) : null));
    System.out.println("区块更新长度 : " +  kit.getWallet().getLastBlockSeenHeight());
    System.out.println("区块更新hash : " + kit.getWallet().getLastBlockSeenHash());
    
    System.out.println("===========收入信息==========" );
    System.out.println("收入总笔数 : " + kit.getWallet().getTransactionPool(WalletTransaction.Pool.UNSPENT).size() + "笔");
    for(Object obj : kit.getWallet().getTransactionPool(WalletTransaction.Pool.UNSPENT).entrySet()){
        Map.Entry entry = (Map.Entry) obj;
        Transaction value = (Transaction) entry.getValue();
        System.out.println(value);
    }
    
    System.out.println("===========花费信息==========" );
    System.out.println("花费总笔数 : " + kit.getWallet().getTransactionPool(WalletTransaction.Pool.SPENT).size() + "笔");
    for(Object obj : kit.getWallet().getTransactionPool(WalletTransaction.Pool.SPENT).entrySet()){
        Map.Entry entry = (Map.Entry) obj;
        Transaction value = (Transaction) entry.getValue();
        System.out.println(value);
    }
    
    System.out.println("===========待处理信息========");
    System.out.println("待处理总笔数 : " + kit.getWallet().getTransactionPool(WalletTransaction.Pool.PENDING).size() + "笔");
    for(Object obj : kit.getWallet().getTransactionPool(WalletTransaction.Pool.PENDING).entrySet()){
        Map.Entry entry = (Map.Entry) obj;
        Transaction value = (Transaction) entry.getValue();
        System.out.println(value);
    }
    
    System.out.println("===========卡死信息========" );
    System.out.println("卡死总笔数 : " + kit.getWallet().getTransactionPool(WalletTransaction.Pool.DEAD).size() + "笔");
    for(Object obj : kit.getWallet().getTransactionPool(WalletTransaction.Pool.DEAD).entrySet()){
        Map.Entry entry = (Map.Entry) obj;
        Transaction value = (Transaction) entry.getValue();
        System.out.println(value);
    }
复制代码

钱包历史订单流水

    for(Transaction transaction :kit.getWallet().getTransactionsByTime()){
        System.out.println("===========交易信息==========");
        System.out.println("交易订单 : " + transaction.getHashAsString());
        System.out.println("Pending : " + transaction.isPending());
        System.out.println("订单时间 : " + transaction.getUpdateTime());
        System.out.println("订单金额 : " + transaction.getValue(kit.getWallet()).toFriendlyString());
        System.out.println("接受地址 : " + transaction.getOutput(0).getAddressFromP2PKHScript(Constants.NETWORK_PARAMETERS));
        System.out.println("订单备注 : " + transaction.getMemo());
    }
复制代码

发送硬币

    // Get the address in object form.
    final Address targetAddress = Address.fromBase58(TestNet3Params.get(), address);
    // Do the send of value BTC in the background. This could throw InsufficientMoneyException.
    final Coin coin =  Coin.parseCoin(value);
    Wallet.SendResult result = kit.getWallet().sendCoins(kit.getPeerGroup(), targetAddress, coin);
    System.out.println("开始发送 : " + result.toString());

    new Thread(){
        @Override
        public void run() {

            // Wait for the transaction to propagate across the P2P network, indicating acceptance.
            try {
                Transaction transaction = result.broadcastComplete.get();
                System.out.println("发送完成 : " + transaction);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }.start();
复制代码

关闭钱包

    kit.stopAsync();
    kit.awaitTerminated();
复制代码

其他

    //获取助记词
    kit.getWallet().getKeyChainSeed().getMnemonicCode();
    //获取金额
    kit.getWallet().getBalance().toFriendlyString()
复制代码

转载于:https://juejin.im/post/5af5a8676fb9a07ab9798ae9

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
bitcoinj项目富含完整demo 此项目使用maven构建,不会使用maven的同学,查看项目pom.xml文件,并在http://mvnrepository.com/下载相应的依赖jar包. demo:bitcoinj签名交易 /** * @param unSpentBTCList 未花费utxo集合 * @param from 发送者地址 * @param to 接收者地址 * @param privateKey 私钥 * @param value 发送金额.单位:聪 * @param fee 旷工费.单位:聪 * @return 签名之后未广播的原生交易字符串 * @throws Exception */ public static String signBTCTransactionData(List unSpentBTCList, String from, String to, String privateKey, long value, long fee) throws Exception { NetworkParameters networkParameters = null; // networkParameters = MainNetParams.get(); //测试网络 networkParameters = TestNet3Params.get(); Transaction transaction = new Transaction(networkParameters); DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(networkParameters, privateKey); ECKey ecKey = dumpedPrivateKey.getKey(); long totalMoney = 0; List utxos = new ArrayList(); //遍历未花费列表,组装合适的item for (UnSpentBTC us : unSpentBTCList) { if (totalMoney >= (value + fee)) break; UTXO utxo = new UTXO(Sha256Hash.wrap(us.getTxid()), us.getVout(), Coin.valueOf(us.getSatoshis()), us.getHeight(), false, new Script(Hex.decode(us.getScriptPubKey()))); utxos.add(utxo); totalMoney += us.getSatoshis(); } transaction.addOutput(Coin.valueOf(value), Address.fromBase58(networkParameters, to)); // transaction. //消费列表总金额 - 已经转账的金额 - 手续费 就等于需要返回给自己的金额了 long balance = totalMoney - value - fee; //输出-转给自己 if (balance > 0) { transaction.addOutput(Coin.valueOf(balance), Address.fromBase58(networkParameters, from)); } //输入未消费列表项 for (UTXO utxo : utxos) { TransactionOutPoint outPoint = new TransactionOutPoint(networkParameters, utxo.getIndex(), utxo.getHash());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值