bitcoindrpc

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package bitcoindrpc 提供Bitcoin Core JSON-RPC客户端

地址相关接口

链相关接口

这是bitcoin core节点的内存池, 要和mempool.space区分开!

查询 bitcoind core 节点状态

交易相关接口

钱包相关操作 封装只能对本地钱包操作的rpc接口

rpc原生数据结构定义

构建tx结构 涉及到动态key值, 需要进行转换处理.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AddressInfoDTO

type AddressInfoDTO struct {
	Address        string   `json:"address"`         // 地址
	ScriptPubKey   string   `json:"scriptPubKey"`    // 脚本公钥
	IsMine         bool     `json:"ismine"`          // 是否属于钱包
	Solvable       bool     `json:"solvable"`        // 是否可解
	Desc           string   `json:"desc"`            // 描述
	ParentDesc     string   `json:"parent_desc"`     // 父描述
	IsWatchOnly    bool     `json:"iswatchonly"`     // 是否只读
	IsScript       bool     `json:"isscript"`        // 是否脚本
	IsWitness      bool     `json:"iswitness"`       // 是否见证
	WitnessVersion int      `json:"witness_version"` // 见证版本
	WitnessProgram string   `json:"witness_program"` // 见证程序
	IsChange       bool     `json:"ischange"`        // 是否改变
	Labels         []string `json:"labels"`          // 标签
}

地址信息数据结构

type BlockDTO

type BlockDTO 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 BlockHeaderDTO

type BlockHeaderDTO 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"`     // 下一个区块哈希
}

区块头数据结构

type BlockStatsDTO

type BlockStatsDTO struct {
	Avgfee             int    `json:"avgfee"`               // 平均交易费
	Avgfeerate         int    `json:"avgfeerate"`           // 平均交易费率
	Avgtxsize          int    `json:"avgtxsize"`            // 平均交易大小
	Blockhash          string `json:"blockhash"`            // 区块哈希
	Feeratepercentiles []int  `json:"feerate_percentiles"`  // 交易费率百分比
	Height             int    `json:"height"`               // 区块高度
	Ins                int    `json:"ins"`                  // 输入数
	Maxfee             int    `json:"maxfee"`               // 最大交易费
	Maxfeerate         int    `json:"maxfeerate"`           // 最大交易费率
	Maxtxsize          int    `json:"maxtxsize"`            // 最大交易大小
	Medianfee          int    `json:"medianfee"`            // 中位交易费
	Mediantime         int    `json:"mediantime"`           // 中位时间
	Mediantxsize       int    `json:"mediantxsize"`         // 中位交易大小
	Minfee             int    `json:"minfee"`               // 最小交易费
	Minfeerate         int    `json:"minfeerate"`           // 最小交易费率
	Mintxsize          int    `json:"mintxsize"`            // 最小交易大小
	Outs               int    `json:"outs"`                 // 输出数
	Subsidy            int    `json:"subsidy"`              // 挖矿奖励
	SwtotalSize        int    `json:"swtotal_size"`         // 简化交易大小
	SwtotalWeight      int    `json:"swtotal_weight"`       // 简化交易权重
	Swtxs              int    `json:"swtxs"`                // 简化交易数
	Time               int    `json:"time"`                 // 时间
	TotalOut           int    `json:"total_out"`            // 总输出
	TotalSize          int    `json:"total_size"`           // 总大小
	TotalWeight        int    `json:"total_weight"`         // 总权重
	Totalfee           int    `json:"totalfee"`             // 总交易费
	Txs                int    `json:"txs"`                  // 交易数
	UtxoIncrease       int    `json:"utxo_increase"`        // 未花费输出增加
	UtxoSizeInc        int    `json:"utxo_size_inc"`        // 未花费输出大小增加
	UtxoIncreaseActual int    `json:"utxo_increase_actual"` // 实际未花费输出增加
	UtxoSizeIncActual  int    `json:"utxo_size_inc_actual"` // 实际未花费输出大小增加
}

区块统计信息数据结构

type ChainInfoDTO

type ChainInfoDTO struct {
	Chain                string  `json:"chain"`                // 链
	Blocks               int     `json:"blocks"`               // 区块数
	Headers              int     `json:"headers"`              // 头数
	Bestblockhash        string  `json:"bestblockhash"`        // 最佳区块哈希
	Difficulty           float64 `json:"difficulty"`           // 难度
	Time                 int     `json:"time"`                 // 时间
	MedianTime           int     `json:"mediantime"`           // 中位时间
	Verificationprogress float64 `json:"verificationprogress"` // 验证进度
	Initialblockdownload bool    `json:"initialblockdownload"` // 初始区块下载
	Chainwork            string  `json:"chainwork"`            // 链工作量
	Sizeondisk           int     `json:"size_on_disk"`         // 磁盘大小
	Pruned               bool    `json:"pruned"`               // 是否修剪
	Warnings             string  `json:"warnings"`             // 警告列表
}

链信息数据结构

type ChainTipDTO

type ChainTipDTO struct {
	Height    int64  `json:"height"`    // 高度
	Hash      string `json:"hash"`      // 哈希
	BranchLen int    `json:"branchlen"` // 分支
	Status    string `json:"status"`    // 状态
}

链顶信息数据结构

type Client

type Client struct {
	// contains filtered or unexported fields
}

func New

func New(url, user, pass string, timeout int) *Client

func (*Client) AddressGetInfo

func (c *Client) AddressGetInfo(ctx context.Context, addr string) (*AddressInfoDTO, error)

查询钱包详细信息: 根据是否导入到本地节点, 返回数据不同

func (*Client) AddressGetUTXOs

func (c *Client) AddressGetUTXOs(ctx context.Context, addr string) ([]UTXODTO, error)

查询钱包UTXO集(基于描述符/地址扫描全链 UTXO) - 会导致节点进行全量查询, 慎用, 等待时间很长

func (*Client) AddressValidate

func (c *Client) AddressValidate(ctx context.Context, addr string) (*ValidateAddressDTO, error)

校验钱包

func (*Client) ChainEstimateSmartFeeRate

func (c *Client) ChainEstimateSmartFeeRate(ctx context.Context, targetBlocks int) (*FeeRateSmartDTO, error)

估算交易费率 Confirmation target in blocks (1 - 1008)

func (*Client) ChainGetBestBlockHash

func (c *Client) ChainGetBestBlockHash(ctx context.Context) (string, error)

获取最新区块的hash

func (*Client) ChainGetBlock

func (c *Client) ChainGetBlock(ctx context.Context, hash string) (*BlockDTO, error)

使用区块block hash 查询区块

func (*Client) ChainGetBlockCount

func (c *Client) ChainGetBlockCount(ctx context.Context) (int, error)

获取节点区块数量

func (*Client) ChainGetBlockHash

func (c *Client) ChainGetBlockHash(ctx context.Context, height int64) (string, error)

使用区块高度 查询区块哈希

func (*Client) ChainGetBlockHeader

func (c *Client) ChainGetBlockHeader(ctx context.Context, hash string) (*BlockDTO, error)

使用区块block hash 查询区块头

func (*Client) ChainGetUTXO

func (c *Client) ChainGetUTXO(ctx context.Context, hash [32]byte, index uint32) ([]byte, int64, error)

查询 UTXO

func (*Client) GetBlockChainInfo added in v0.1.0

func (c *Client) GetBlockChainInfo(ctx context.Context) (*ChainInfoDTO, error)

获取链信息

func (*Client) GetBlockCount added in v0.1.1

func (c *Client) GetBlockCount(ctx context.Context) (int64, error)

GetBlockCount

func (*Client) GetBlockStats

func (c *Client) GetBlockStats(ctx context.Context, height int64) (*BlockStatsDTO, error)

获取区块统计信息

func (*Client) GetChainTips added in v0.1.0

func (c *Client) GetChainTips(ctx context.Context) ([]ChainTipDTO, error)

获取链顶信息

func (*Client) GetNetworkInfo

func (c *Client) GetNetworkInfo(ctx context.Context) (*NetworkInfoDTO, error)

获取节点网络信息

func (*Client) MempoolGetInfo

func (c *Client) MempoolGetInfo(ctx context.Context) (*MempoolInfoDTO, error)

获取内存池信息

func (*Client) MempoolGetTx

func (c *Client) MempoolGetTx(ctx context.Context, txid string) (*MempoolTxDTO, error)

获取内存池交易信息

func (*Client) MempoolGetTxs

func (c *Client) MempoolGetTxs(ctx context.Context) ([]string, error)

获取内存池交易信息

func (*Client) TxBroadcast

func (c *Client) TxBroadcast(ctx context.Context, rawtx []byte) (string, error)

广播交易

func (*Client) TxCreateRaw

func (c *Client) TxCreateRaw(ctx context.Context, dto *TxCreateRawDTO) ([]byte, error)

构建交易(taproot需要使用psbt)

func (*Client) TxFinalizePsbt

func (c *Client) TxFinalizePsbt(ctx context.Context, psbt string) (string, error)

完成psbt交易

func (*Client) TxFundRaw

func (c *Client) TxFundRaw(ctx context.Context, rawtx string, options *TxFundOptionsDTO) (*TxFundRawResultDTO, error)

填充交易费用(taproot需要使用psbt)

func (*Client) TxGetRaw

func (c *Client) TxGetRaw(ctx context.Context, txid string, decodeFlag bool) ([]byte, error)

获取交易元数据 [可以修改decodeFlag获取json格式数据, 也可以使用decoderawtransaction(hex)解析raw数据] 目前使用btcd库统一解析交易数据的hex. decodeFlag: false-返回hex字符串; true-返回json;

func (*Client) TxSignRawWithKey

func (c *Client) TxSignRawWithKey(ctx context.Context, rawtx string) (string, error)

签名交易(taproot需要使用psbt)

func (*Client) TxTestMempoolAccept

func (c *Client) TxTestMempoolAccept(ctx context.Context, rawtx []byte) (string, error)

预检查交易 testmempoolaccept: 需要组装交易数据后生成hex字符串再测试

func (*Client) TxValidateUnsignedPsbt added in v0.1.1

func (c *Client) TxValidateUnsignedPsbt(ctx context.Context, psbt string) error

检查psbt合法性

type FeeRateSmartDTO

type FeeRateSmartDTO struct {
	Feerate float64 `json:"feerate"` // 交易费率(BTC/KB)
	Blocks  int     `json:"blocks"`  // 目标区块数
}

估算交易费率数据结构

type MempoolInfoDTO

type MempoolInfoDTO struct {
	Loaded              bool    `json:"loaded"`              // 是否加载
	Size                int     `json:"size"`                // 大小
	Bytes               int     `json:"bytes"`               // 字节
	Usage               int     `json:"usage"`               // 使用
	TotalFee            float64 `json:"total_fee"`           // 总费用
	MaxMempool          int     `json:"maxmempool"`          // 最大内存池
	MempoolMinFee       float64 `json:"mempoolminfee"`       // 最小内存池费用
	MinRelayTxFee       float64 `json:"minrelaytxfee"`       // 最小中继交易费用
	IncrementalRelayFee float64 `json:"incrementalrelayfee"` // 增量中继交易费用
	UnbroadcastCount    int     `json:"unbroadcastcount"`    // 未广播数量
	FullRBF             bool    `json:"fullrbf"`             // 全RBF
}

type MempoolTxDTO

type MempoolTxDTO struct {
	Vsize           int    `json:"vsize"`           // 剥离大小
	Weight          int    `json:"weight"`          // 权重
	Time            int    `json:"time"`            // 时间
	Height          int    `json:"height"`          // 高度
	DescendantCount int    `json:"descendantcount"` // 后代数量
	DescendantSize  int    `json:"descendantsize"`  // 后代大小
	AncestorCount   int    `json:"ancestorcount"`   // 祖先数量
	AncestorSize    int    `json:"ancestorsize"`    // 祖先大小
	Wtxid           string `json:"wtxid"`           // 交易ID
	Fees            struct {
		Base       float64 `json:"base"`       // 基础费用
		Modified   float64 `json:"modified"`   // 修改后的费用
		Ancestor   float64 `json:"ancestor"`   // 祖先费用
		Descendant float64 `json:"descendant"` // 后代费用
	} `json:"fees"` // 费用
	Depends           []string `json:"depends"`            // 依赖
	Spentby           []string `json:"spentby"`            // 花费
	Bip125Replaceable bool     `json:"bip125-replaceable"` // 可替换
	Unbroadcast       bool     `json:"unbroadcast"`        // 未广播
}

内存池交易信息数据结构

type NetworkInfoDTO

type NetworkInfoDTO struct {
	Version            int      `json:"version"`            // 版本
	Subversion         string   `json:"subversion"`         // 子版本
	ProtocolVersion    int      `json:"protocolversion"`    // 协议版本
	LocalServices      string   `json:"localservices"`      // 本地服务
	LocalServicesNames []string `json:"localservicesnames"` // 本地服务名称
	LocalRelay         bool     `json:"localrelay"`         // 本地中继
	TimeOffset         int      `json:"timeoffset"`         // 时间偏移
	NetworkActive      bool     `json:"networkactive"`      // 网络活跃
	Connections        int      `json:"connections"`        // 连接数
	Connectionsin      int      `json:"connections_in"`     // 入站连接数
	Connectionsout     int      `json:"connections_out"`    // 出站连接数
	Networks           []struct {
		Name                      string `json:"name"`                        // 网络名称
		Limited                   bool   `json:"limited"`                     // 是否有限
		Reachable                 bool   `json:"reachable"`                   // 是否可达
		Proxy                     string `json:"proxy"`                       // 代理
		ProxyRandomizeCredentials bool   `json:"proxy_randomize_credentials"` // 代理随机化凭证
	} `json:"networks"` // 网络列表
	Relayfee       float64 `json:"relayfee"`       // 中继费
	Incrementalfee float64 `json:"incrementalfee"` // 增量费
	Localaddresses []struct {
		Address string `json:"address"` // 地址
		Port    int    `json:"port"`    // 端口
		Score   int    `json:"score"`   // 分数
	} `json:"localaddresses"` // 本地地址列表
	Warnings string `json:"warnings"` // 警告
}

网络信息数据结构

type SignedTxDTO added in v0.1.0

type SignedTxDTO struct {
	Hex      string `json:"hex"`      // 交易十六进制
	Complete bool   `json:"complete"` // 是否完成
}

经过bitcoin core的finalizepsbt处理后的交易数据结构

type TxCreateRawDTO

type TxCreateRawDTO struct {
	Inputs      []TxInputCreateRawDTO  `json:"inputs"`      // 交易输入
	Outputs     []TxOutputCreateRawDTO `json:"outputs"`     // 交易输出
	Locktime    *int64                 `json:"locktime"`    // 可选, 默认 0; 非0值时, 交易锁定时间生效
	Replaceable *bool                  `json:"replaceable"` // 可选, 默认 true; 是否可替换
}

构建交易

func (TxCreateRawDTO) MarshalJSON

func (p TxCreateRawDTO) MarshalJSON() ([]byte, error)

MarshalJSON 按 Core 期望的“位置参数数组”编码: [vin, vout, locktime, replaceable]

type TxFundOptionsDTO

type TxFundOptionsDTO struct {
	AddInputs      bool   `json:"add_inputs"`     // 可选, 默认 true; 是否自动添加更多输入
	IncludeUnsafe  bool   `json:"include_unsafe"` // 可选, 默认 false; 是否包含未确认的交易
	MinConf        int    `json:"minconf"`        // 可选, 默认 0; 如果 add_inputs 为 true, 则需要输入至少这么多确认
	MaxConf        int    `json:"maxconf"`        // 可选, 默认 0; 如果 add_inputs 为 true, 则需要输入最多这么多确认
	ChangeAddress  string `json:"changeAddress"`  // 可选, 默认 自动; 接收找零的地址
	ChangePosition int    `json:"changePosition"` // 可选, 默认 随机; 找零输出的索引
	// ChangeType             string     `json:"change_type"`            // 可选, 默认 由 -changetype 设置; 找零输出的类型
	IncludeWatching bool    `json:"includeWatching"` // 可选, 默认 true; 是否包含 watch-only 的输入
	LockUnspents    bool    `json:"lockUnspents"`    // 可选, 默认 false; 锁定选定的未花费输出
	FeeRateSats     float64 `json:"fee_rate"`        // 可选, 默认 0; 指定费用率, 单位 sat/vB
	// FeeRateBtc             float64    `json:"feeRate"`                // 可选, 默认 0; 指定费用率, 单位 BTC/kvB
	// SubtractFeeFromOutputs []int      `json:"subtractFeeFromOutputs"` // 可选, 默认 []; 从指定输出的金额中扣除费用
	// InputWeights           []struct { // 可选, 默认 []; 输入和对应的权重
	// 	TxID   string `json:"txid"`   // 交易ID
	// 	Vout   int    `json:"vout"`   // 输出索引
	// 	Weight int    `json:"weight"` // 权重
	// } `json:"input_weights"`
	// MaxTxWeight int `json:"max_tx_weight"` // 可选, 默认 400000; 最大可接受的交易权重
	// ConfTarget   int      `json:"conf_target"`   // 可选, 默认 由 -txconfirmtarget 设置; 确认目标区块数
	// EstimateMode string   `json:"estimate_mode"` // 可选, 默认 "unset"; 费用估计模式, 可选值: "unset", "economical", "conservative"
	Replaceable bool `json:"replaceable"` // 可选, 默认 false; 是否可替换

}

填充交易费用

type TxFundRawResultDTO

type TxFundRawResultDTO struct {
	Hex       string  `json:"hex"`       // 交易数据
	Fee       float64 `json:"fee"`       // 交易费用
	ChangePos int     `json:"changepos"` // 找零输出索引
	Change    string  `json:"change"`    // 找零地址
}

填充交易费用结果

type TxInputCreateRawDTO

type TxInputCreateRawDTO struct {
	TxID     string `json:"txid"`     // 交易ID
	Vout     uint32 `json:"vout"`     // 输出索引
	Sequence uint32 `json:"sequence"` // 可选, 默认 0xffffffff
}

构建交易输入

func NewTxInput

func NewTxInput(txid string, vout uint32) TxInputCreateRawDTO

便捷构造器

type TxOutputCreateRawDTO

type TxOutputCreateRawDTO struct {
	Address string                            `json:"address,omitempty"` // 地址
	Script  *TxOutputScriptPubKeyCreateRawDTO `json:"script,omitempty"`  // 脚本公钥
	Amount  float64                           `json:"amount,omitempty"`  // 金额(单位:BTC)
	DataHex string                            `json:"datahex,omitempty"` // OP_RETURN 不带金额
}

构建交易输出

func NewOpReturn

func NewOpReturn(hexData string) TxOutputCreateRawDTO

func NewPayToAddress

func NewPayToAddress(addr string, amountBtc float64) TxOutputCreateRawDTO

func NewPayToScriptHex

func NewPayToScriptHex(scriptHex string, amountBtc float64) TxOutputCreateRawDTO

func (TxOutputCreateRawDTO) MarshalJSON

func (o TxOutputCreateRawDTO) MarshalJSON() ([]byte, error)

单个输出对象的 JSON 编码(与 Core 接口格式对齐)

type TxOutputScriptPubKeyCreateRawDTO

type TxOutputScriptPubKeyCreateRawDTO struct {
	// 二选一:常用为 Hex。也允许携带 address(Core 会验证/转换)。
	Address string `json:"address,omitempty"`
	Hex     string `json:"hex,omitempty"`
}

type UTXODTO

type UTXODTO struct {
	TxID         string  `json:"txid"`         // 交易ID
	Vout         uint32  `json:"vout"`         // 输出索引
	ScriptPubKey string  `json:"scriptPubKey"` // 脚本公钥
	Desc         string  `json:"desc"`         // 描述
	AmountBTC    float64 `json:"amount"`       // 金额
	Height       int64   `json:"height"`       // 高度
}

UTXO数据结构

type ValidateAddressDTO

type ValidateAddressDTO struct {
	IsValid        bool   `json:"isvalid"`         // 是否有效
	Address        string `json:"address"`         // 地址
	ScriptPubKey   string `json:"scriptPubKey"`    // 脚本公钥
	IsScript       bool   `json:"isscript"`        // 是否脚本
	IsWitness      bool   `json:"iswitness"`       // 是否见证
	WitnessVersion int    `json:"witness_version"` // 见证版本
	WitnessProgram string `json:"witness_program"` // 见证程序
}

Jump to

Keyboard shortcuts

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