编程技术类比特钱包

4、交易签名实现

2018-05-24  本文已影响304人  谷歌派

比特币系列交易签名

查询UTXO交易信息网站
https://blockchain.info/tx/7957a35fe64f80d234d76d83a2a8f1a0d8149a41d81de548f0a65a8a999f6f18?show_adv=true
校验签名信息网站
https://live.blockcypher.com/btc-testnet/decodetx/
下面干点正事👇
private void test5(){
        // 币种类型 根据BIP44生产的对应币种 比如BTC/ETH/DOGE ...
        CoinType netParams = CoinConfigUtils.getInstance().getCoinType("0Y");
        // 1、UTXO 列表
        List<UTXO> utxoList = new ArrayList<>();
        // 私钥
        ECKey privKey = ECKey.fromPrivate(StringUtils.parseHexString("自己的私钥"));
        // 接收地址
        Address receiveAddress = Address.fromBase58(netParams, "DQZuuK8tHCj573qLGLiANRKJcukENboG4X");
        // 交易
        Transaction tx = new Transaction(netParams);
        // 添加要发送金额、输出的地址
        tx.addOutput(Coin.valueOf(1000000),receiveAddress);
        // 如果需要找零
        // tx.addOutput(Coin.valueOf(找零数量),自己的地址);
        // 一次UTXO
        // (1) hashID
        Sha256Hash hashId = Sha256Hash.wrap("9c560ce5b128830b7a09bdf6c584b723eb688da0b31028ee739d92461e22d681");
        // (2) 下标
        int index = 0;
        // (3) 交易金额
        Coin coin = Coin.valueOf(399990000);
        // (4) 区块高度
        int height = 2226079;
        // (5) 是否是创世区块
        boolean isCoinBase = false;
        // (6) 待签名脚本
        Script script = new Script(StringUtils.parseHexString("76a914e195b52651163c5d6d7dca2cc3388bce4d700d8288ac"));
        UTXO utxo = new UTXO(hashId,index,coin,height,isCoinBase,script);
        utxoList.add(utxo);
        // 用私钥签名每个输出 utxo
        for (UTXO sUtxo : utxoList) {
            TransactionOutPoint outPoint = new TransactionOutPoint(netParams, sUtxo.getIndex(), sUtxo.getHash());
            tx.addSignedInput(outPoint, sUtxo.getScript(), privKey, Transaction.SigHash.ALL, true);
        }

        tx.getConfidence().setSource(TransactionConfidence.Source.SELF);
        tx.setPurpose(Transaction.Purpose.USER_PAYMENT);
        // 5、生成交易签名
        String hexString = StringUtils.toHexString(tx.bitcoinSerialize());

    }
上一篇下一篇

猜你喜欢

热点阅读