编写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绘制蛇年春节祝福艺术图

《使用Python绘制蛇年春节祝福艺术图》:本文主要介绍如何使用Python的Matplotlib库绘制一幅富有创意的“蛇年有福”艺术图,这幅图结合了数字,蛇形,花朵等装饰,需要的可以参考下... 目录1. 绘图的基本概念2. 准备工作3. 实现代码解析3.1 设置绘图画布3.2 绘制数字“2025”3.3

python使用watchdog实现文件资源监控

《python使用watchdog实现文件资源监控》watchdog支持跨平台文件资源监控,可以检测指定文件夹下文件及文件夹变动,下面我们来看看Python如何使用watchdog实现文件资源监控吧... python文件监控库watchdogs简介随着Python在各种应用领域中的广泛使用,其生态环境也

Python中构建终端应用界面利器Blessed模块的使用

《Python中构建终端应用界面利器Blessed模块的使用》Blessed库作为一个轻量级且功能强大的解决方案,开始在开发者中赢得口碑,今天,我们就一起来探索一下它是如何让终端UI开发变得轻松而高... 目录一、安装与配置:简单、快速、无障碍二、基本功能:从彩色文本到动态交互1. 显示基本内容2. 创建链

Java调用Python代码的几种方法小结

《Java调用Python代码的几种方法小结》Python语言有丰富的系统管理、数据处理、统计类软件包,因此从java应用中调用Python代码的需求很常见、实用,本文介绍几种方法从java调用Pyt... 目录引言Java core使用ProcessBuilder使用Java脚本引擎总结引言python

python 字典d[k]中key不存在的解决方案

《python字典d[k]中key不存在的解决方案》本文主要介绍了在Python中处理字典键不存在时获取默认值的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录defaultdict:处理找不到的键的一个选择特殊方法__missing__有时候为了方便起见,

使用Python绘制可爱的招财猫

《使用Python绘制可爱的招财猫》招财猫,也被称为“幸运猫”,是一种象征财富和好运的吉祥物,经常出现在亚洲文化的商店、餐厅和家庭中,今天,我将带你用Python和matplotlib库从零开始绘制一... 目录1. 为什么选择用 python 绘制?2. 绘图的基本概念3. 实现代码解析3.1 设置绘图画

Python pyinstaller实现图形化打包工具

《Pythonpyinstaller实现图形化打包工具》:本文主要介绍一个使用PythonPYQT5制作的关于pyinstaller打包工具,代替传统的cmd黑窗口模式打包页面,实现更快捷方便的... 目录1.简介2.运行效果3.相关源码1.简介一个使用python PYQT5制作的关于pyinstall

使用Python实现大文件切片上传及断点续传的方法

《使用Python实现大文件切片上传及断点续传的方法》本文介绍了使用Python实现大文件切片上传及断点续传的方法,包括功能模块划分(获取上传文件接口状态、临时文件夹状态信息、切片上传、切片合并)、整... 目录概要整体架构流程技术细节获取上传文件状态接口获取临时文件夹状态信息接口切片上传功能文件合并功能小

python实现自动登录12306自动抢票功能

《python实现自动登录12306自动抢票功能》随着互联网技术的发展,越来越多的人选择通过网络平台购票,特别是在中国,12306作为官方火车票预订平台,承担了巨大的访问量,对于热门线路或者节假日出行... 目录一、遇到的问题?二、改进三、进阶–展望总结一、遇到的问题?1.url-正确的表头:就是首先ur

Linux使用nohup命令在后台运行脚本

《Linux使用nohup命令在后台运行脚本》在Linux或类Unix系统中,后台运行脚本是一项非常实用的技能,尤其适用于需要长时间运行的任务或服务,本文我们来看看如何使用nohup命令在后台... 目录nohup 命令简介基本用法输出重定向& 符号的作用后台进程的特点注意事项实际应用场景长时间运行的任务服