比特离线交易

离线交易生成 hex交易值、手动广播出去即可。
广播交易

// 1、私钥
        ECKey privKey = ECKey.fromPrivate(Utils.HEX.decode(unspentBean.getPrivKey()));

        // 2、计算金额
        long amount = (long) (unspentBean.getAmout() * LongMath.pow(10, netParams.getUnitExponent()));// 输入金额
        long fee = (long) (unspentBean.getFeeD() * LongMath.pow(10, netParams.getUnitExponent())); // 旷工费
        long inputSum = 0L; // 总输入金额
        long needed = amount + fee; // 最终转账金额:输入金额+旷工费
        long change; // 找零  总输入-总消费

        // 3、符合的utxo列表
        List<UnspentBean.UtxoBean> utxoList = unspentBean.getUtxos();
        for (UnspentBean.UtxoBean utxo : utxoList) {
            inputSum += utxo.getValue();
            if (inputSum >= needed) {
                break;
            }
        }

        // 4、计算找零
        change = inputSum - needed;

        // 5、构建交易
        Transaction tx = new Transaction(netParams);
        tx.addOutput(Coin.valueOf(amount), Address.fromBase58(netParams, unspentBean.getToA())); // 转出
        tx.addOutput(Coin.valueOf(change), Address.fromBase58(netParams, unspentBean.getFromA()));// 找零

        // 6、签名输出脚本
        for (UnspentBean.UtxoBean utxosBean : utxoList) {
            UTXO sUtxo = new UTXO(Sha256Hash.wrap(utxosBean.getTx_hash()),
                    utxosBean.getTx_pos(),
                    Coin.valueOf(utxosBean.getValue()),
                    utxosBean.getHeight(),
                    false,
                    new Script(Utils.HEX.decode(utxosBean.getScriptPubKey())));
            TransactionOutPoint outPoint = new TransactionOutPoint(netParams, sUtxo.getIndex(), sUtxo.getHash());
            tx.addSignedInput(outPoint, sUtxo.getScript(), privKey, Transaction.SigHash.ALL, true);
        }
        // 7、构建交易签名
        tx.getConfidence().setSource(TransactionConfidence.Source.SELF);
        tx.setPurpose(Transaction.Purpose.USER_PAYMENT);
        String transCode = Utils.HEX.encode(tx.bitcoinSerialize());
        Logger.e("交易签名:"+transCode);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。