区块链中,如何调用Bit RPC接口来对节点Node操作,包括创建交易,验证交易,发送交易等

testmempoolaccept API

  1. 首先去接口文档找到这个testmempoolaccept

  2. 看参数和返回值

    a.首先要看需要哪些参数:

这里第一个参数rawTxs是必须的,要求是一个字符串的数组,每个字符串代表要test的交易,该交易要被签过名并且已经十六进制编码了

            b.再看返回结果:

是一个jason的数组

  1. 调用接口

      如果你本地运行着Bit Core全节点,则可以直接使用命令:

    1. 命令行调用

bitcoin-cli testmempoolaccept '["signedhex"]'

                2. HTTP + JSON-RPC调用

curl --user myusername --data-binary '{"jsonrpc": "1.0", "id": "curltest", "method": "testmempoolaccept", "params": [["signedhex"]]}' -H 'content-type: text/plain;' http://127.0.0.1:8332/

上面是在命令行调用,也可以在Java中用HttpURLConnection来构建:

public String callRPCOne(BitcoinNodeDto bitcoinNode, JsonRpcDto params) throws IOException {
    String url = "http://" + bitcoinNode.getIp() + ":" + bitcoinNode.getPort() + "/";//这里分别获取到远程运行bit core全节点的服务器IP和端口,这个自己配置
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    // 设置请求方法
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "text/plain");
    con.setDoOutput(true);//允许通过 getOutputStream() 方法获取输出流
    // 设置基本认证
    String encoded = Base64.getEncoder().encodeToString((bitcoinNode.getUser() + ":" + bitcoinNode.getPasswd()).getBytes("UTF-8"));//请求头(Header)字段仅允许 ASCII 字符,若直接发送原始凭证(如包含中文或特殊符号),可能导致解析错误或截断
    con.setRequestProperty("Authorization", "Basic " + encoded);
    // 发送请求
    String jsonInputString = JSON.toJSONString(params);//这里提前将{"jsonrpc": "1.0", "id": "curltest", "method": "sendrawtransaction", "params": ["signedhex"]}'封装成了一个DTO类
    try (OutputStream os = con.getOutputStream()) {
        os.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
    }//建立连接
    
    //接收响应
    StringBuilder rpcResponse = new StringBuilder();
    if (con.getResponseCode() > 299) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                rpcResponse.append(inputLine);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    } else {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                rpcResponse.append(inputLine);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
    return rpcResponse.toString();
}

上面介绍了如何测试一笔交易是否会被内存池接收,那么如何获取到一笔交易呢?

创建一笔交易rawTransaction

  1. 利用createrawtransactionsignrawtransactionwithwallet两个API就可以得到一笔交易了,注意交易的输入输出,以及outputs-inputs = fee ,即给旷工的手续费,不能过大,不然会有错。

  2. 或者去mempool这个区块链浏览器上看已经在内存池的交易

获取rawTransaction的相关信息

当我们拿到一个rawTransaction时,我们该如何获取到它的信息呢?比如它的vsize,它的fee

这里我们用到java提供的 org.bitcoinj.core.Transaction 类:

protected Transaction getTransaction(String rawTx) {
    byte[] txBytes = null;
    try {
        txBytes = Hex.decodeHex(rawTx);
    } catch (DecoderException e) {
        log.error("Get transaction error: {}", e.getMessage());
        throw new RuntimeException(e);
    }
    ByteBuffer txBuffer = ByteBuffer.allocate(txBytes.length);
    txBuffer.put(txBytes);
    txBuffer.flip();
    return Transaction.read(txBuffer);
}

将原十六进制的rawTx解码成字节数组,再放到byteBuffer中被读取

而Transaction类提供便捷的方法直接获取到vsize和fee,transaction.getVsize()transaction.getFee().getValue()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值