blockchain-python-cheat-sheet

田曜瑞
2023-12-01

地址正则表达式汇总

# BTC 正则
_pattern = r'^(([13][a-km-zA-HJ-NP-Z0-9]{26,33},*)|(bc(0([ac-hj-np-z02-9]{39}|[ac-hj-np-z02-9]{59})|1[ac-hj-np-z02-9]{8,87}),*))+$'
regex_btc = re.compile(pattern_btc)

# ETH 正则
pattern_eth = r'^0x[a-fA-F0-9]{40}$'
regex_eth = re.compile(pattern_eth)

# TRX 正则
pattern_trx = r'^T[0-9a-zA-Z]{33}$'
regex_trx = re.compile(pattern_trx)

# EOS 正则
pattern_eos = r'^[a-z1-5][a-z1-5\.]{0,10}[a-z1-5]?$'
regex_eos = re.compile(pattern_eos)

# XRP 正则
pattern_xrp = r'^r[0-9a-zA-Z]{24,34}$'
regex_xrp = re.compile(pattern_xrp)

bytes 转为 string

# pip 安装 web3
pip3 install web3
from web3 import Web3
string_content = Web3.toText(bytes_content)

BTC 交易数据解析 USDT 交易

# 判断是否为 USDT-Omni 交易
is_usdt_omni = False
vouts = transaction["vout"]
usdt_op_return = ""
for vout in vouts:
    address = vout["addresses"][0]
    if "#31" in address:
        is_usdt_omni = True
        usdt_op_return = address
        break

# 解析 USDT-Omni 的输入输出地址 sender recipient
vins = transaction["vin"]
vouts = transaction["vout"][::-1]
sender = vins[0]["addresses"][0]

had_changed = False
recipient = vouts[0]
for vout in vouts:
    is_address = vout["isAddress"]

    if is_address:
        maybe_output_address = vout['addresses'][0]
        if had_changed:
            recipient = maybe_output_address
            break

        if maybe_output_address != sender:
            recipient = maybe_output_address
            break
        else:
            had_changed = True

# 获取 value 值 amount
usdt_op_return_list = usdt_op_return.split(" ")
amount = round(float(usdt_op_return_list[3]), 3)

# 排除 sender recipient 都不是查询地址的情况
if (sender == address) or (recipient == address):
    pass

精度转换

def convert_decimal(value, token_decimal=18):
    """为无小数点位的转移数额值添加小数点位,结果保留 6 位小数

    :param value: 无小数点位的转移数额值
    :param token_decimal: 代币小数点位
    :return: 有小数点位的转移数额值(精确度:6 位小数)
    """

    convert_value = round(value * pow(0.1, token_decimal), 6)

    return convert_value
 类似资料: