本文主要是介绍编写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"}
测试结果:
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的接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!