types

package
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

示例代码备用参考: 锁定脚本/解锁脚本/自定义逻辑脚等

Package types 网络相关类型定义 包含比特币网络节点信息、连接状态、网络统计等网络层相关的数据结构

Index

Constants

This section is empty.

Variables

View Source
var CurrentNetworkParams *chaincfg.Params = &chaincfg.MainNetParams // 当前网络参数

Functions

func GetInSize added in v0.1.0

func GetInSize(addrType AddressType) int

根据地址类型速查交易输入的虚拟字节大小(vsize) 返回值:估算值上限.

func GetOpReturnSize added in v0.1.0

func GetOpReturnSize(dataLen int) int

GetOpReturnSize 估算 OP_RETURN 输出大小 返回值:输出大小vsize.

func GetOutSize added in v0.1.0

func GetOutSize(addrType AddressType) (int, int)

根据地址类型速查交易输出的字节大小 返回值:1-scriptPubKey 长度, 2-输出大小vsize.

func OpcodeName

func OpcodeName(op byte) string

将 opcode 映射为可读名称

func SetCurrentNetwork

func SetCurrentNetwork(net string)

SetCurrentNetwork 设置当前网络

Types

type AddressBalanceInfo added in v0.2.1

type AddressBalanceInfo struct {
	Address     string // 地址
	Confirmed   int64  // 已确认余额(聪)
	Unconfirmed int64  // 未确认余额(聪)
	Total       int64  // 总余额(聪)
	Error       error  // 查询错误(如果有)
}

AddressBalanceInfo 地址余额信息

type AddressInfo

type AddressInfo struct {
	PKScript  []byte               // 原始脚本
	Typ       AddressType          // 地址类型
	Cls       txscript.ScriptClass // 脚本类型
	ReqSigs   int                  // 需要签名数(多签时有意义)
	Addresses []string             // 可能为 0/1/N
}

AddressInfo 结构体:存储地址解析后的信息

type AddressScriptInfo

type AddressScriptInfo struct {
	Address         string               // 地址
	Typ             AddressType          // 地址类型
	Cls             txscript.ScriptClass // 脚本类型
	ScriptPubKeyHex []byte               // 脚本哈希 => PKScript
	ScriptAsm       string               // 脚本汇编

	// “哈希/程序”层面(地址能直接给出的)
	PubKeyHashHex       []byte // P2PKH: 20 bytes
	RedeemScriptHashHex []byte // P2SH:  20 bytes

	// SegWit
	IsWitness         bool   // 是否为见证地址
	WitnessVersion    int    // 见证版本:0(SegWit v0)、1(Taproot)、-1(非SegWit)
	WitnessProgramHex []byte // v0: 20/32 bytes; v1+: 32 bytes
	WitnessProgramLen int    // 见证数据长度:20字节或32字节
	BechEncoding      string // bech32 / bech32m

	// Taproot
	TaprootOutputKeyHex []byte // 等同于 witness program (v=1, 32B x-only pubkey)
}

AddressScriptInfo 结构体:存储地址解析后的脚本信息 包含脚本类型、各种哈希值、见证版本等关键信息

type AddressType

type AddressType string

AddressType 标注常见地址/脚本族群。

const (
	AddrP2PK    AddressType = "p2pk"
	AddrP2PKH   AddressType = "p2pkh"
	AddrP2SH    AddressType = "p2sh"
	AddrP2WPKH  AddressType = "p2wpkh"
	AddrP2WSH   AddressType = "p2wsh"
	AddrP2TR    AddressType = "p2tr"
	AddrUnknown AddressType = "unknown"
)

type ChainBlock added in v0.1.0

type ChainBlock struct {
	Hash              string  `json:"hash"`              // 区块哈希
	Confirmations     int     `json:"confirmations"`     // 确认数
	Height            int     `json:"height"`            // 高度
	Version           int     `json:"version"`           // 版本
	VersionHex        string  `json:"versionHex"`        // 版本十六进制
	MerkleRoot        string  `json:"merkleroot"`        // 默克尔根
	Time              int     `json:"time"`              // 时间
	MedianTime        int     `json:"mediantime"`        // 中位时间
	Nonce             int     `json:"nonce"`             // 随机数
	Bits              string  `json:"bits"`              // 难度位
	Difficulty        float64 `json:"difficulty"`        // 难度
	Chainwork         string  `json:"chainwork"`         // 工作量
	NTx               int     `json:"nTx"`               // 交易数
	PreviousBlockHash string  `json:"previousblockhash"` // 上一个区块哈希
	NextBlockHash     string  `json:"nextblockhash"`     // 下一个区块哈希

	// 区块链头数据不包含以下字段
	StrippedSize int      `json:"strippedsize"` // 剥离大小
	Size         int      `json:"size"`         // 大小
	Weight       int      `json:"weight"`       // 权重
	Tx           []string `json:"tx"`           // 交易
}

区块数据结构

type Hash32

type Hash32 [32]byte

Hash32 是 32 字节哈希(双 SHA256 结果)。 约定:内部按“比特币内部顺序”存(通常等同于小端存放), JSON 显示时按“大端十六进制字符串”(常见 txid 书写)输出。

func (Hash32) BytesBE

func (h Hash32) BytesBE() []byte

func (Hash32) BytesLE

func (h Hash32) BytesLE() []byte

内部:LE 存储

func (*Hash32) FromBEHex

func (h *Hash32) FromBEHex(s string) error

解析来自外部(BE 字符串)

func (Hash32) MarshalJSON

func (h Hash32) MarshalJSON() ([]byte, error)

JSON 始终输出 BE;输入接受 BE

func (Hash32) String

func (h Hash32) String() string

人类可读(与 mempool.space / bitcoin-cli 对齐):BE hex

func (*Hash32) UnmarshalJSON

func (h *Hash32) UnmarshalJSON(b []byte) error

type Network

type Network string

Network 网络类型

const (
	Mainnet Network = "mainnet" // 主网
	Testnet Network = "testnet" // 测试网
	Signet  Network = "signet"  // 签名网
	Regtest Network = "regtest" // 回归测试网
)
var CurrentNetwork Network = Mainnet // 当前网络

func (Network) ToParams

func (n Network) ToParams() *chaincfg.Params

ToParams 将网络转换为网络参数

type Runes added in v0.2.0

type Runes struct {
	ID               string          `db:"id"`                 // Rune 的唯一 ID(通常是 `block_height-tx_index` 或内部编码)。可作为主键。
	Number           int64           `db:"number"`             // (postgre: int8)Rune 序号(按诞生顺序的编号)。
	Name             string          `db:"name"`               // 原始名称(不含空格/分隔符)。
	SpacedName       string          `db:"spaced_name"`        // 带 spacer 的展示名(协议允许在 name 中插入分隔符以增强可读性)。
	BlockHash        string          `db:"block_hash"`         // 铸造/诞生所在区块哈希。
	BlockHeight      int             `db:"block_height"`       // 诞生区块高度。用于范围/时间查询。
	TxIndex          int64           `db:"tx_index"`           // (postgre: int8)该区块内的交易索引(定位同高内顺序)。
	TxID             string          `db:"tx_id"`              // 诞生交易哈希。
	Divisibility     int16           `db:"divisibility"`       // (postgres: int2)小数位精度(等价 ERC-20 decimals)。
	Premine          decimal.Decimal `db:"premine"`            // (postgres: numberic)预挖/预留发行量(在 terms 之外直接进入供给)。
	Symbol           string          `db:"symbol"`             // 代币符号(截图中默认值显示为 `'r'::text`,不同实现可能为空)。
	TermsAmount      decimal.Decimal `db:"terms_amount"`       // (postgres: numberic)**每次 mint 的单位数量**(按规则铸造时的一次配额)。
	TermsCap         decimal.Decimal `db:"terms_cap"`          // (postgres: numberic)**总的可 mint 次数上限**(“能铸几次”)。达到后不可再 mint。
	TermsHeightStart int             `db:"terms_height_start"` // 允许 mint 的起始高度(闭区间起点)。
	TermsHeightEnd   int             `db:"terms_height_end"`   // 允许 mint 的结束高度(闭区间终点)。
	TermsOffsetStart int             `db:"terms_offset_start"` // 允许 mint 的相对高度起点(相对“诞生高度”的偏移)。实现上常用于 height + offset 的双窗限制。
	TermsOffsetEnd   int             `db:"terms_offset_end"`   // 允许 mint 的相对高度终点。
	Turbo            bool            `db:"turbo"`              // 是否为“turbo”模式(部分实现里代表宽松/快速铸造规则或 gas/费用优化标记,阅读你用的 indexer 定义为准)。
	Cenotaph         bool            `db:"cenotaph"`           // 失效/空墓标记:表示该 Rune 在诞生 tx 上因规则错误被判定为无效(常见于 ordinals 语境中的“Cenotaph”概念)。通常不应被统计进有效供给。
	Timestamp        int64           `db:"timestamp"`          // (postgre: int8)诞生区块时间(Unix 秒)。
}

runes: 用途:每个 Rune 的“元数据/发行规则”,一条记录=一个 Rune。 索引建议:

PK(id),UNIQUE(tx_id);
BTREE(block_height), BTREE(name), BTREE(number);
需要以“是否可 mint”检索时,再建复合索引:(terms_height_start,terms_height_end)。

type RunesBalanceChanges added in v0.2.0

type RunesBalanceChanges struct {
	RuneID          string          `db:"rune_id"`          // 关联的 Rune。
	BlockHeight     int             `db:"block_height"`     // 统计到的区块高度(该高度时点的余额口径)。
	Address         string          `db:"address"`          // 地址。
	Balance         decimal.Decimal `db:"balance"`          // (postgre: numeric)该地址在该高度的**余额**(注意是累计量,而非当区块的 delta)。
	TotalOperations int64           `db:"total_operations"` // (postgre: int8)该地址到此高度累计发生的相关事件数(便于做增量/校验)。默认 0。
}

balance_changes 用途:地址维度的累计余额快照/变动汇总(比逐事件更适合余额/排行榜查询)。 常见用法:

取地址最新余额:ORDER BY block_height DESC LIMIT 1;
做时间序列:按高度排序取 balance。

索引建议:

PK/UNIQUE(rune_id,address,block_height);
BTREE(address), BTREE(block_height DESC)。

type RunesLedger added in v0.2.0

type RunesLedger struct {
	RuneID          string          `db:"rune_id"`          // 关联的 Rune。
	BlockHash       string          `db:"block_hash"`       // 所在区块哈希。
	BlockHeight     int             `db:"block_height"`     // 区块高度。
	TxIndex         int64           `db:"tx_index"`         // (postgre: int8)区块内交易索引。
	EventIndex      int64           `db:"event_index"`      // (postgre: int8)**同一交易内的事件序号**(确保事件稳定排序,便于回放)。
	TxID            string          `db:"tx_id"`            // 交易哈希。
	Output          int             `db:"output"`           // (postgre: int8)事件关联的 `vout`(收款/分发通常能落到具体输出;`mint` 可能无明确地址时该列可空)。
	Address         string          `db:"address"`          // 地址字段(实现里常作**发送方**或通用地址;搭配 `receiver_address` 使用,见下)。
	ReceiverAddress string          `db:"receiver_address"` // **接收方地址**(`receive` 事件一定有值;`send` 常为空;`mint` 视实现是否能归集到具体 vout)。
	Amount          decimal.Decimal `db:"amount"`           // (postgre: numeric)本事件的数量(正值)。
	Operation       string          `db:"operation"`        // (postgre: public.ledger_operation)**枚举**:常见有 `mint` / `send` / `receive` / `burn`。不同实现也可能仅用三类。
	Timestamp       int64           `db:"timestamp"`        // (postgre: int8)区块时间(Unix 秒)。
}

ledger 用途:事件流水表(事实表)。一笔 tx 可能产生多行:mint / send / receive(及可选 burn)。 查询口径:

“该地址本笔交易净变化” → 对同一 tx_id、address 聚合 receive - send (+ 可选 mint 归属)。
“同一 tx 概览” → 按 operation 汇总 mint/receive/send/burn。

索引建议:

BTREE(tx_id), BTREE(rune_id), BTREE(block_height), BTREE(operation), BTREE(receiver_address), BTREE(address);
事件回放:复合索引 (block_height,tx_index,event_index)。

type RunesSupplyChanges added in v0.2.0

type RunesSupplyChanges struct {
	RuneID          string          `db:"rune_id"`          // 关联的 Rune。
	BlockHeight     int             `db:"block_height"`     // 统计到的区块高度。
	Minted          decimal.Decimal `db:"minted"`           // (postgre: numeric)**该高度内新增**的铸造量(delta)。
	TotalMints      decimal.Decimal `db:"total_mints"`      // (postgre: numeric)截至该高度的**累计铸造总量**。
	Burned          decimal.Decimal `db:"burned"`           // (postgre: numeric)**该高度内销毁**量(delta,若协议/实现支持)。
	TotalBurns      decimal.Decimal `db:"total_burns"`      // (postgre: numeric)截至该高度的**累计销毁总量**。
	TotalOperations int64           `db:"total_operations"` // (postgre: int8)截至该高度与该 Rune 有关的累计事件数(便于做增量/校验)。默认 0。
}

supply_changes 用途:全局供给维度的累计快照/变动统计(每个高度一行或仅在有事件的高度一行)。 查询口径:

当前总供给 ≈ total_mints - total_burns(或 premine + 累计mint - 累计burn,看实现是否将 premine 计入 total_mints)。
供给时间序列:按高度取 total_mints/total_burns。

索引建议:

PK/UNIQUE(rune_id,block_height);
BTREE(block_height), BTREE(rune_id)。

type Runestone

type Runestone struct {
	BodyHex string `json:"body_hex"` // 十六进制编码的 payload
}

Runestone 结构体:存储 Runestone 数据

type ScriptOp

type ScriptOp struct {
	Op      string `json:"op"`                 // 操作码
	DataHex string `json:"data_hex,omitempty"` // 数据十六进制
	DataLen int    `json:"data_len,omitempty"` // 数据长度,单位:字节
}

ScriptOp 表示一条脚本指令;若为数据推送,DataHex/DataLen 会被填充。

type TapControlBlock

type TapControlBlock struct {
	Header       byte     `json:"header"`        // 原始头字节
	LeafVersion  byte     `json:"leaf_version"`  // header & 0xfe
	Parity       int      `json:"parity"`        // (header >> 7) & 1
	InternalKey  string   `json:"internal_key"`  // 32B x-only pubkey (hex)
	MerkleHashes []string `json:"merkle_hashes"` // 0或多段32B(hex)
}

TapControlBlock 解析后的控制块信息(P2TR 脚本路径花费使用)

type Tx

type Tx struct {
	Version  int32   // 交易版本
	LockTime uint32  // 交易锁定时间
	TxIn     []TxIn  // 交易输入
	TxOut    []TxOut // 交易输出

}

Tx:完整的交易对象(不显式包含 marker/flag 字段;是否为 segwit 由 TxIn[].Witness 是否存在决定) 序列化顺序(无见证):Version | vinCount | vin[...] | voutCount | vout[...] | LockTime 序列化顺序(有见证):Version | 0x00 | 0x01 | vinCount | vin[...] | voutCount | vout[...] | witnesses(for each vin) | LockTime

type TxIn

type TxIn struct {
	PreviousOutPoint TxOutPoint // 上一笔交易的输出点
	Sequence         uint32     // 交易序列号
	ScriptSig        []byte     // scriptSig
	Witness          TxWitness  // 若任一输入 Witness 非空,序列化需写入 marker/flag,并在所有 TxOut 之后写入全部 Witness
}

TxIn:交易输入 - PreviousOutPoint:被花费的 UTXO 引用 - ScriptSig:非隔离见证路径下的解锁脚本(如 P2PKH 的 <sig><pubkey> 等) - Sequence:nSequence;影响 RBF(<0xffffffff-1)与 CSV;默认 0xffffffff - Witness:隔离见证路径下的见证栈(P2WPKH/P2WSH/P2TR 等)

func (TxIn) MarshalJSON

func (in TxIn) MarshalJSON() ([]byte, error)

type TxInputParams

type TxInputParams struct {
	FromAddress   []string  `json:"from_address"`   // 来源地址数组-可以是多个, 但是目前版本只支持1个地址
	ToAddress     []string  `json:"to_address"`     // 目标地址数组-可以是多个, 但是要和Amount一一对应
	AmountBTC     []float64 `json:"amount"`         // 金额-单位BTC
	FeeRate       float64   `json:"fee_rate"`       // 费用率(sat/vB)
	Locktime      int64     `json:"locktime"`       // 锁定时间(秒)
	Replaceable   bool      `json:"replaceable"`    // 是否可替换RBF
	Data          string    `json:"data"`           // 可选 交付附加数据
	PublicKey     string    `json:"public_key"`     // 公钥 => 从OKX获取, 后续要删除, 改用其他方式录入钱包
	ChangeAddress string    `json:"change_address"` // 找零地址
}

通用的转账交易输入参数

type TxOut

type TxOut struct {
	Value      int64  // satoshi
	PkScript   []byte // scriptPubKey
	ScriptType string // 可选, 用于显示 解析出的脚本类别
	Address    string // 可选, 用于显示 解析得到的人类可读地址
}

TxOut:交易输出 - Value:satoshi 数(int64,允许负数编码但务必在业务层校验非负) - PkScript:锁定脚本(scriptPubKey),如 P2PKH 的 OP_DUP OP_HASH160 <20b> OP_EQUALVERIFY OP_CHECKSIG

func (TxOut) MarshalJSON

func (out TxOut) MarshalJSON() ([]byte, error)

type TxOutPoint

type TxOutPoint struct {
	Hash  Hash32 // 上一笔交易的 txid(逻辑上大端显示;写入时小端序)
	Index uint32 // vout 索引,从 0 开始
}

OutPoint 唯一标识一个已存在的交易输出:<txid, vout>

type TxUTXO

type TxUTXO struct {
	OutPoint TxOutPoint // 定位该 UTXO
	Value    int64      // satoshi
	PkScript []byte     // 原始 scriptPubKey
	Height   uint32     // 产出该 UTXO 的区块高度;mempool 可置 0 或特约定值
	Coinbase bool       // 该 UTXO 是否来自 coinbase 交易
	Address  string     // 解析得到的人类可读地址(可选)

}

UTXO:钱包/索引层常用的未花费输出结构(**链上共识并不定义该结构**,这是应用层抽象)

type TxUnsignedPSBT added in v0.1.0

type TxUnsignedPSBT struct {
	PSBTBase64 string `json:"psbt_base64"`     // 导出签名用的PSBT数据
	UnsignedTx string `json:"unsigned_tx_hex"` // 调试/核对
}

type TxWitness

type TxWitness [][]byte

TxWitness 是 SegWit 的 per-input 见证栈;外层是项数量,内层每项为原始字节。

type VarInt

type VarInt = uint64

VarInt 序列化时采用比特币可变长度整型编码;此处仅作标注,实际可直接用 uint64 并在编解码层处理。

type WalletInfo added in v0.2.0

type WalletInfo struct {
	P2PKH      string `json:"p2pkh"`
	P2PSH      string `json:"p2psh"`
	P2WPKH     string `json:"p2wpkh"`
	P2TR       string `json:"p2tr"`
	Mnemonic   string `json:"mnemonic"`
	XPRV       string `json:"xprv"`
	BTCBalance int64  `json:"btc_balance,omitempty"`
}

WalletInfo 钱包信息结构

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL