编写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 FastAPI入门安装使用

《PythonFastAPI入门安装使用》FastAPI是一个现代、快速的PythonWeb框架,用于构建API,它基于Python3.6+的类型提示特性,使得代码更加简洁且易于绶护,这篇文章主要介... 目录第一节:FastAPI入门一、FastAPI框架介绍什么是ASGI服务(WSGI)二、FastAP

Python中Windows和macOS文件路径格式不一致的解决方法

《Python中Windows和macOS文件路径格式不一致的解决方法》在Python中,Windows和macOS的文件路径字符串格式不一致主要体现在路径分隔符上,这种差异可能导致跨平台代码在处理文... 目录方法 1:使用 os.path 模块方法 2:使用 pathlib 模块(推荐)方法 3:统一使

一文教你解决Python不支持中文路径的问题

《一文教你解决Python不支持中文路径的问题》Python是一种广泛使用的高级编程语言,然而在处理包含中文字符的文件路径时,Python有时会表现出一些不友好的行为,下面小编就来为大家介绍一下具体的... 目录问题背景解决方案1. 设置正确的文件编码2. 使用pathlib模块3. 转换路径为Unicod

Python结合Flask框架构建一个简易的远程控制系统

《Python结合Flask框架构建一个简易的远程控制系统》这篇文章主要为大家详细介绍了如何使用Python与Flask框架构建一个简易的远程控制系统,能够远程执行操作命令(如关机、重启、锁屏等),还... 目录1.概述2.功能使用系统命令执行实时屏幕监控3. BUG修复过程1. Authorization

Python使用DeepSeek进行联网搜索功能详解

《Python使用DeepSeek进行联网搜索功能详解》Python作为一种非常流行的编程语言,结合DeepSeek这一高性能的深度学习工具包,可以方便地处理各种深度学习任务,本文将介绍一下如何使用P... 目录一、环境准备与依赖安装二、DeepSeek简介三、联网搜索与数据集准备四、实践示例:图像分类1.

Python中__new__()方法适应及注意事项详解

《Python中__new__()方法适应及注意事项详解》:本文主要介绍Python中__new__()方法适应及注意事项的相关资料,new()方法是Python中的一个特殊构造方法,用于在创建对... 目录前言基本用法返回值单例模式自定义对象创建注意事项总结前言new() 方法在 python 中是一个

Python批量调整Word文档中的字体、段落间距及格式

《Python批量调整Word文档中的字体、段落间距及格式》这篇文章主要为大家详细介绍了如何使用Python的docx库来批量处理Word文档,包括设置首行缩进、字体、字号、行间距、段落对齐方式等,需... 目录关键代码一级标题设置  正文设置完整代码运行结果最近关于批处理格式的问题我查了很多资料,但是都没

Python依赖库的几种离线安装方法总结

《Python依赖库的几种离线安装方法总结》:本文主要介绍如何在Python中使用pip工具进行依赖库的安装和管理,包括如何导出和导入依赖包列表、如何下载和安装单个或多个库包及其依赖,以及如何指定... 目录前言一、如何copy一个python环境二、如何下载一个包及其依赖并安装三、如何导出requirem

python中列表list切分的实现

《python中列表list切分的实现》列表是Python中最常用的数据结构之一,经常需要对列表进行切分操作,本文主要介绍了python中列表list切分的实现,文中通过示例代码介绍的非常详细,对大家... 目录一、列表切片的基本用法1.1 基本切片操作1.2 切片的负索引1.3 切片的省略二、列表切分的高

基于Python实现一个PDF特殊字体提取工具

《基于Python实现一个PDF特殊字体提取工具》在PDF文档处理场景中,我们常常需要针对特定格式的文本内容进行提取分析,本文介绍的PDF特殊字体提取器是一款基于Python开发的桌面应用程序感兴趣的... 目录一、应用背景与功能概述二、技术架构与核心组件2.1 技术选型2.2 系统架构三、核心功能实现解析