编写python脚本调用ordinals以及BRC20的接口

2024-01-31 15:44

本文主要是介绍编写python脚本调用ordinals以及BRC20的接口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

初始版本

#!/usr/bin/python3from flask import Flask, request, jsonify
import subprocess
import json
import osapp = Flask(__name__)ord_cmd = ["/root/ord/target/release/ord", "--cookie-file=/data/btcregtest/data/regtest/.cookie", "--rpc-url=127.0.0.1:8540", "-r"]bitcoin_cli_cmd=["/data/btcregtest/bin/bitcoin-cli", "-regtest", "--conf=/data/btcregtest/conf/bitcoin-regtest.conf", "-rpcwallet=btcregtest"]@app.route('/walletreceive', methods=['POST'])
def wallet_receive():try:num = int(request.json['num'])return wallet_receive_impl(num)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/inscription', methods=['POST'])
def inscription():try:fee_rate = request.json['fee_rate']tick = request.json['tick']amount = request.json['amount']destination = request.json['destination']return inscription_impl(fee_rate, tick, amount, destination)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/send', methods=['POST'])
def send():try:fee_rate = request.json['fee_rate']address = request.json['address']inscription_id = request.json['inscription_id']return send_impl(fee_rate, address, inscription_id)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/sendtoaddress', methods=['POST'])
def sendtoaddress():try:address = request.json['address']count = request.json['count']return sendtoaddress_impl(address, count)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/generate', methods=['POST'])
def generate():try:count = request.json['count']return generate_impl(count)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/getrawtransaction', methods=['POST'])
def getrawtransaction():try:hash_id = request.json['hash_id']return getrawtransaction_impl(hash_id)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/wallet_balance', methods=['POST'])
def wallet_balance():try:return wallet_balance_impl()except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/wallet', methods=['POST'])
def wallet():try:wallet_method = request.json['wallet_method']return wallet_impl(wallet_method)except Exception as e:return jsonify({"error": str(e)}), 400def wallet_receive_impl(num):addresses = []for i in range(1, num + 1):command = ord_cmd + ["wallet", "receive"]output = subprocess.check_output(command)address = json.loads(output.decode().strip().replace("'", "\""))["address"]addresses.append(address)return addressesdef inscription_impl(fee_rate, tick, amount, destination):fee_rate_file = "/root/fee_rate_file.json"with open(fee_rate_file, "w") as json_file:json.dump({"p": "brc-20", "op": "transfer", "tick": tick, "amount": str(amount)}, json_file)command = ord_cmd + ["wallet", "inscribe", "--fee-rate", str(fee_rate), "--file", fee_rate_file, "--destination", destination]result = subprocess.check_output(command)return result.decode().strip()def send_impl(fee_rate, address, inscription_id):                command = ord_cmd + ["wallet", "send", "--fee-rate", str(fee_rate), address, inscription_id]result = subprocess.check_output(command)return result.decode().strip()def sendtoaddress_impl(address, count):               command = bitcoin_cli_cmd + ["sendtoaddress", address, str(count)]result = subprocess.check_output(command)return result.decode().strip()def generate_impl(count):    command = bitcoin_cli_cmd + ["-generate", count]result = subprocess.check_output(command)return result.decode().strip()def getrawtransaction_impl(hash_id):    command = bitcoincli_cmd + ["getrawtransaction", hash_id, "true"]result = subprocess.check_output(command)return result.decode().strip()def wallet_balance_impl():command = ord_cmd + ["wallet", "balance"]result = subprocess.check_output(command)return result.decode().strip()    def wallet_impl(wallet_method):command = ord_cmd + ["wallet", wallet_method]# 使用 subprocess.run 获取命令执行结果和错误输出result = subprocess.run(command, capture_output=True, text=True)return run_command(command)if __name__ == '__main__':app.run(debug=False, host='0.0.0.0', port=5000)

优化后,正常返回节点的错误信息

#!/usr/bin/python3from flask import Flask, request, jsonify,make_response
import subprocess
import json
import os
import re 
import logging app = Flask(__name__)ord_cmd = ["/data/ord/target/release/ord", "--cookie-file=/data/btc/btcdata/regtest/.cookie", "--rpc-url=127.0.0.1:8540", "-r"]bitcoin_cli_cmd=["/data/btc/bin/bin/bitcoin-cli", "-regtest", "--conf=/data/btc/conf/bitcoin.conf", "-rpcwallet=btcregtest"]
bitcoincli_cmd=["/data/btc/bin/bin/bitcoin-cli", "-regtest", "--conf=/data/btc/conf/bitcoin.conf"]def run_command(command):try:# 使用 subprocess.run 获取命令执行结果和错误输出result = subprocess.run(command, capture_output=True, text=True)# 如果命令返回非零退出码,表示发生错误if result.returncode != 0:# 从错误输出中提取包含 "error" 的部分match = re.search(r'error:.*', result.stderr, re.IGNORECASE)processed_error_message = match.group(0) if match else "Unknown error"# 记录错误到日志logging.error("Error in command execution: %s", result.stderr)# 手动创建 JSON 响应并设置状态码response = jsonify({"error": processed_error_message, "normal_output": result.stdout.strip()})response.status_code = 500return response# 记录正常输出到日志logging.info("Normal output in command execution: %s", result.stdout)# 返回正常输出到客户端return result.stdout.strip()except Exception as e:# 记录异常到日志logging.error("Error in command execution: %s", str(e))return str(e), 500@app.route('/walletreceive', methods=['POST'])
def wallet_receive():try:num = int(request.json['num'])return wallet_receive_impl(num)except Exception as e:return str(e), 400@app.route('/inscription', methods=['POST'])
def inscription():try:fee_rate = request.json['fee_rate']tick = request.json['tick']amount = request.json['amount']destination = request.json['destination']return inscription_impl(fee_rate, tick, amount, destination)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/send', methods=['POST'])
def send():try:fee_rate = request.json['fee_rate']address = request.json['address']inscription_id = request.json['inscription_id']return send_impl(fee_rate, address, inscription_id)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/sendtoaddress', methods=['POST'])
def sendtoaddress():try:address = request.json['address']count = request.json['count']return sendtoaddress_impl(address, count)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/generate', methods=['POST'])
def generate():try:count = request.json['count']return generate_impl(count)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/getrawtransaction', methods=['POST'])
def getrawtransaction():try:hash_id = request.json['hash_id']return getrawtransaction_impl(hash_id)except Exception as e:return jsonify({"error": str(e)}), 400@app.route('/wallet', methods=['POST'])
def wallet():try:wallet_method = request.json['wallet_method']return wallet_impl(wallet_method)except Exception as e:return jsonify({"error": str(e)}), 400def wallet_receive_impl(num):addresses = []for i in range(1, num + 1):command = ord_cmd + ["wallet", "receive"]output = subprocess.check_output(command)address = json.loads(output.decode().strip().replace("'", "\""))["address"]addresses.append(address)return addressesdef inscription_impl(fee_rate, tick, amount, destination):fee_rate_file = "/root/fee_rate_file.json"with open(fee_rate_file, "w") as json_file:json.dump({"p": "brc-20", "op": "transfer", "tick": tick, "amount": str(amount)}, json_file)command = ord_cmd + ["wallet", "inscribe", "--fee-rate", str(fee_rate), "--file", fee_rate_file, "--destination", destination]return run_command(command)def send_impl(fee_rate, address, inscription_id):command = ord_cmd + ["wallet", "send", "--fee-rate", str(fee_rate), address, inscription_id]# 使用 subprocess.run 获取命令执行结果和错误输出result = subprocess.run(command, capture_output=True, text=True)return run_command(command)def sendtoaddress_impl(address, count):command = bitcoin_cli_cmd + ["sendtoaddress", address, str(count)]return run_command(command)def generate_impl(count):command = bitcoin_cli_cmd + ["-generate", count]# 使用 subprocess.run 获取命令执行结果和错误输出result = subprocess.run(command, capture_output=True, text=True)return run_command(command)def getrawtransaction_impl(hash_id):command = bitcoincli_cmd + ["getrawtransaction", hash_id, "true"]# 使用 subprocess.run 获取命令执行结果和错误输出result = subprocess.run(command, capture_output=True, text=True)return run_command(command)def wallet_impl(wallet_method):command = ord_cmd + ["wallet", wallet_method]# 使用 subprocess.run 获取命令执行结果和错误输出result = subprocess.run(command, capture_output=True, text=True)return run_command(command)if __name__ == '__main__':app.run(debug=False, host='0.0.0.0', port=5000)

测试验证
所有接口都是post请求,采用postman进行测试
1、钱包地址生成walletreceive,对应ord命令:ord wallet receive
测试地址:http://192.168.25.128:5000/walletreceive
测试参数:
其中数值代表要新生成的地址数

{"num": "1"}

测试结果示例
在这里插入图片描述
2、钱包币种铭刻inscription,
对应ord命令

ord --cookie-file btcdata/.cookie -r wallet inscribe --fee-rate 50 --file fee.json

fee.json文本模板

{"p":"brc-20","op":"transfer","tick":"ordi","amt":"10"}

测试结果
测试地址:http://192.168.25.128:5000/inscription
测试参数

{"fee_rate": "37", 
"tick": "ordi", 
"amount": "0.25564588", 
"destination": "bcrt1pp76laj6axjryppcfw2vjuyhpq75ndulkcmm3dq59le52qlfmdpws26zrpd"
}

在这里插入图片描述
3、铭文转账send
对应ord命令

ord --cookie-file btcdata/.cookie -r wallet send --fee-rate 50 钱包地址 铭文id

测试地址:http://192.168.25.128:5000/send
测试参数:

{
"fee_rate": "40", 
"address": "bcrt1pp76laj6axjryppcfw2vjuyhpq75ndulkcmm3dq59le52qlfmdpws26zrpd", "inscription_id": "1757702fcffbea626de0f524b76f048f87e43351640b92d6eddbcc93e68c44e9i0"
}

测试结果:
在这里插入图片描述
4、测试bitcoin转币sendtoaddress
对应bitcoin-cli命令

./btcoin-cli -rpcwallet=btcregtest(钱包名称)  sendtoaddress bcrt1pprdrceqpc2sy8fr60jqaaatkw5wne2j3g0xljtn0wskajwafgc8qxac384(目的钱包地址) 10(币种数量)

测试地址:http://192.168.25.128:5000/sendtoaddress
测试参数:

{"address": "bcrt1pp76laj6axjryppcfw2vjuyhpq75ndulkcmm3dq59le52qlfmdpws26zrpd", 
"count": "10"}

测试结果
在这里插入图片描述

5、测试通过hash查询交易getrawtransaction
对应bitcoin-cli命令

./btcoin-cli getrawtransaction hash_id true

测试地址:http://192.168.25.128:5000/getrawtransaction
测试参数:

{"hash_id": "731237ec34e833713d349daf30f1e66d69a31ca261af84ea787368d017ef9f75"}

测试结果:
在这里插入图片描述](https://img-blog.csdnimg.cn/direct/aa29c0a074574b4b9f87047382126075.png)
6、测试手动出块generate,这个只在regtest链节点用得上
对应bitcoin-cli命令

./btcoin-cli -generate num(手动出块数,也就是挖矿)

测试地址:http://192.168.25.128:5000/generate
测试参数:

{"count": "10"}

测试结果:
在这里插入图片描述
7、测试其他的wallet方法wallet
距离测试三个方法
对应ord命令:

ord -r wallet wallet_method(钱包方法)

测试参数

{"wallet_method": "inscriptions"}
或者
{"wallet_method": "cardinals"}
或者
{"wallet_method": "outputs"}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
还可以加很多根据需要加减

这篇关于编写python脚本调用ordinals以及BRC20的接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/664275

相关文章

Python结合PyWebView库打造跨平台桌面应用

《Python结合PyWebView库打造跨平台桌面应用》随着Web技术的发展,将HTML/CSS/JavaScript与Python结合构建桌面应用成为可能,本文将系统讲解如何使用PyWebView... 目录一、技术原理与优势分析1.1 架构原理1.2 核心优势二、开发环境搭建2.1 安装依赖2.2 验

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm

一文详解如何在Python中从字符串中提取部分内容

《一文详解如何在Python中从字符串中提取部分内容》:本文主要介绍如何在Python中从字符串中提取部分内容的相关资料,包括使用正则表达式、Pyparsing库、AST(抽象语法树)、字符串操作... 目录前言解决方案方法一:使用正则表达式方法二:使用 Pyparsing方法三:使用 AST方法四:使用字

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

Python运行中频繁出现Restart提示的解决办法

《Python运行中频繁出现Restart提示的解决办法》在编程的世界里,遇到各种奇怪的问题是家常便饭,但是,当你的Python程序在运行过程中频繁出现“Restart”提示时,这可能不仅仅是令人头疼... 目录问题描述代码示例无限循环递归调用内存泄漏解决方案1. 检查代码逻辑无限循环递归调用内存泄漏2.

Python中判断对象是否为空的方法

《Python中判断对象是否为空的方法》在Python开发中,判断对象是否为“空”是高频操作,但看似简单的需求却暗藏玄机,从None到空容器,从零值到自定义对象的“假值”状态,不同场景下的“空”需要精... 目录一、python中的“空”值体系二、精准判定方法对比三、常见误区解析四、进阶处理技巧五、性能优化

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

python logging模块详解及其日志定时清理方式

《pythonlogging模块详解及其日志定时清理方式》:本文主要介绍pythonlogging模块详解及其日志定时清理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录python logging模块及日志定时清理1.创建logger对象2.logging.basicCo

Python如何自动生成环境依赖包requirements

《Python如何自动生成环境依赖包requirements》:本文主要介绍Python如何自动生成环境依赖包requirements问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录生成当前 python 环境 安装的所有依赖包1、命令2、常见问题只生成当前 项目 的所有依赖包1、

如何将Python彻底卸载的三种方法

《如何将Python彻底卸载的三种方法》通常我们在一些软件的使用上有碰壁,第一反应就是卸载重装,所以有小伙伴就问我Python怎么卸载才能彻底卸载干净,今天这篇文章,小编就来教大家如何彻底卸载Pyth... 目录软件卸载①方法:②方法:③方法:清理相关文件夹软件卸载①方法:首先,在安装python时,下