编写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: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

如何在页面调用utility bar并传递参数至lwc组件

1.在app的utility item中添加lwc组件: 2.调用utility bar api的方式有两种: 方法一,通过lwc调用: import {LightningElement,api ,wire } from 'lwc';import { publish, MessageContext } from 'lightning/messageService';import Ca

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

nudepy,一个有趣的 Python 库!

更多资料获取 📚 个人网站:ipengtao.com 大家好,今天为大家分享一个有趣的 Python 库 - nudepy。 Github地址:https://github.com/hhatto/nude.py 在图像处理和计算机视觉应用中,检测图像中的不适当内容(例如裸露图像)是一个重要的任务。nudepy 是一个基于 Python 的库,专门用于检测图像中的不适当内容。该

Linux服务器Java启动脚本

Linux服务器Java启动脚本 1、初版2、优化版本3、常用脚本仓库 本文章介绍了如何在Linux服务器上执行Java并启动jar包, 通常我们会使用nohup直接启动,但是还是需要手动停止然后再次启动, 那如何更优雅的在服务器上启动jar包呢,让我们一起探讨一下吧。 1、初版 第一个版本是常用的做法,直接使用nohup后台启动jar包, 并将日志输出到当前文件夹n

pip-tools:打造可重复、可控的 Python 开发环境,解决依赖关系,让代码更稳定

在 Python 开发中,管理依赖关系是一项繁琐且容易出错的任务。手动更新依赖版本、处理冲突、确保一致性等等,都可能让开发者感到头疼。而 pip-tools 为开发者提供了一套稳定可靠的解决方案。 什么是 pip-tools? pip-tools 是一组命令行工具,旨在简化 Python 依赖关系的管理,确保项目环境的稳定性和可重复性。它主要包含两个核心工具:pip-compile 和 pip

如何编写Linux PCIe设备驱动器 之二

如何编写Linux PCIe设备驱动器 之二 功能(capability)集功能(capability)APIs通过pci_bus_read_config完成功能存取功能APIs参数pos常量值PCI功能结构 PCI功能IDMSI功能电源功率管理功能 功能(capability)集 功能(capability)APIs int pcie_capability_read_wo

HTML提交表单给python

python 代码 from flask import Flask, request, render_template, redirect, url_forapp = Flask(__name__)@app.route('/')def form():# 渲染表单页面return render_template('./index.html')@app.route('/submit_form',