bn

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2025 License: Apache-2.0 Imports: 14 Imported by: 1

README ¶

🚀 go-bn

The go-to Bitcoin Node (BN) Go library (Forked from libsv/go-bn)

CI / CD Quality & Security Docs & Meta Community
Latest Release
Build Status
CodeQL
SonarCloud
Go Report Card
Code Coverage
OpenSSF Scorecard
Security policy
Go version
Go docs
AGENTS.md rules
Makefile Supported
Dependabot
Contributors
Last commit
Sponsor

🗂️ Table of Contents


📦 Installation

go-bn requires a supported release of Go.

go get -u github.com/bsv-blockchain/go-bn

📚 Documentation

For more information around the technical aspects of Bitcoin, please see the updated Bitcoin Wiki


Repository Features
  • Continuous Integration on Autopilot with GitHub Actions – every push is built, tested, and reported in minutes.
  • Pull‑Request Flow That Merges Itself thanks to auto‑merge and hands‑free Dependabot auto‑merge.
  • One‑Command Builds powered by battle‑tested Make targets for linting, testing, releases, and more.
  • First‑Class Dependency Management using native Go Modules.
  • Uniform Code Style via gofumpt plus zero‑noise linting with golangci‑lint.
  • Confidence‑Boosting Tests with testify, the Go race detector, crystal‑clear HTML coverage snapshots, and automatic uploads to Codecov.
  • Hands‑Free Releases delivered by GoReleaser whenever you create a new Tag.
  • Relentless Dependency & Vulnerability Scans via Dependabot, Nancy, and govulncheck.
  • Security Posture by Default with CodeQL, OpenSSF Scorecard, and secret‑leak detection via gitleaks.
  • Automatic Syndication to pkg.go.dev on every release for instant godoc visibility.
  • Polished Community Experience using rich templates for Issues & PRs.
  • All the Right Meta Files (LICENSE, CONTRIBUTING.md, CODE_OF_CONDUCT.md, SUPPORT.md, SECURITY.md) pre‑filled and ready.
  • Code Ownership clarified through a CODEOWNERS file, keeping reviews fast and focused.
  • Zero‑Noise Dev Environments with tuned editor settings (.editorconfig) plus curated ignore files for VS Code, Docker, and Git.
  • Label Sync Magic: your repo labels stay in lock‑step with .github/labels.yml.
  • Friendly First PR Workflow – newcomers get a warm welcome thanks to a dedicated workflow.
  • Standards‑Compliant Docs adhering to the standard‑readme spec.
  • Instant Cloud Workspaces via Gitpod – spin up a fully configured dev environment with automatic linting and tests.
  • Out‑of‑the‑Box VS Code Happiness with a preconfigured Go workspace and .vscode folder with all the right settings.
  • Optional Release Broadcasts to your community via Slack, Discord, or Twitter – plug in your webhook.
  • AI Compliance Playbook – machine‑readable guidelines (AGENTS.md, CLAUDE.md, .cursorrules, sweep.yaml) keep ChatGPT, Claude, Cursor & Sweep aligned with your repo’s rules.
  • Pre-commit Hooks for Consistency powered by pre-commit and the .pre-commit-config.yaml file—run the same formatting, linting, and tests before every commit, just like CI.
  • Automated Hook Updates keep the .pre-commit-config.yaml current via a weekly workflow.
  • DevContainers for Instant Onboarding – Launch a ready-to-code environment in seconds with VS Code DevContainers and the included .devcontainer.json config.
Library Deployment

This project uses goreleaser for streamlined binary and library deployment to GitHub. To get started, install it via:

brew install goreleaser

The release process is defined in the .goreleaser.yml configuration file.

To generate a snapshot (non-versioned) release for testing purposes, run:

make release-snap

Then create and push a new Git tag using:

make tag version=x.y.z

This process ensures consistent, repeatable releases with properly versioned artifacts and citation metadata.

Makefile Commands

View all makefile commands

make help

List of all current commands:

bench                 ## Run all benchmarks in the Go application
build-go              ## Build the Go application (locally)
citation              ## Update version in CITATION.cff (use version=X.Y.Z)
clean-mods            ## Remove all the Go mod cache
coverage              ## Show test coverage
diff                  ## Show git diff and fail if uncommitted changes exist
fumpt                 ## Run fumpt to format Go code
generate              ## Run go generate in the base of the repo
godocs                ## Trigger GoDocs tag sync
govulncheck-install   ## Install govulncheck
help                  ## Display this help message
install-go            ## Install using go install with specific version
install-releaser      ## Install GoReleaser
install               ## Install the application binary
lint                  ## Run the golangci-lint application (install if not found)
release-snap          ## Build snapshot binaries
release-test          ## Run release dry-run (no publish)
release               ## Run production release (requires github_token)
run-fuzz-tests        ## Run fuzz tests for all packages
tag-remove            ## Remove local and remote tag (use version=X.Y.Z)
tag-update            ## Force-update tag to current commit (use version=X.Y.Z)
tag                   ## Create and push a new tag (use version=X.Y.Z)
test-ci-no-race       ## CI test suite without race detector
test-ci-short         ## CI unit-only short tests
test-ci               ## CI full test suite with coverage
test-no-lint          ## Run only tests (no lint)
test-short            ## Run tests excluding integration
test-unit             ## Runs tests and outputs coverage
test                  ## Run lint and all tests
uninstall             ## Uninstall the Go binary
update-linter         ## Upgrade golangci-lint (macOS only)
update-releaser       ## Reinstall GoReleaser
update                ## Update dependencies
vet                   ## Run go vet
GitHub Workflows
Workflow Name Description
auto-merge-on-approval.yml Automatically merges PRs after approval and all required checks, following strict rules.
clean-runner-cache.yml Removes GitHub Actions caches tied to closed pull requests.
codeql.yml Analyzes code for security vulnerabilities using GitHub CodeQL.
delete-merged-branches.yml Deletes feature branches after their pull requests are merged.
dependabot-auto-merge.yml Automatically merges Dependabot PRs that meet all requirements.
pull-request-management.yml Labels PRs by branch prefix, assigns a default user if none is assigned, and welcomes new contributors with a comment.
release.yml Builds and publishes releases via GoReleaser when a semver tag is pushed.
run-tests.yml Runs linter, Go tests and dependency checks on every push and pull request.
scorecard.yml Runs OpenSSF Scorecard to assess supply chain security.
stale.yml Warns about (and optionally closes) inactive issues and PRs on a schedule or manual trigger.
sync-labels.yml Keeps GitHub labels in sync with the declarative manifest at .github/labels.yml.
update-pre-commit-hooks.yml Automatically update versions for pre-commit hooks
update-pip-requirements.yml Updates Python requirements for pre-commit hooks to the latest versions.
Updating Dependencies

To update all dependencies (Go modules, linters, and related tools), run:

make update

This command ensures all dependencies are brought up to date in a single step, including Go modules and any tools managed by the Makefile. It is the recommended way to keep your development environment and CI in sync with the latest versions.

Pre-commit Hooks

Set up the optional pre-commit hooks to run the same formatting, linting, and tests defined in AGENTS.md before every commit:

pip install pre-commit
pre-commit install

The hooks are configured in .pre-commit-config.yaml and mirror the CI pipeline.


đź§Ş Examples & Tests

All unit tests and examples run via GitHub Actions and use Go version 1.24.x. View the configuration file.

Run all tests:

make test

⚡ Benchmarks

Run the Go benchmarks:

make bench

Benchmark Results
Benchmark Iterations ns/op B/op allocs/op
(TODO) 4,112,503 280.2 1024 1

These benchmarks reflect fast, allocation-free lookups for most retrieval functions, ensuring optimal performance in production environments. Performance benchmarks for the core functions in this library, executed on an Apple M1 Max (ARM64).


🛠️ Code Standards

Read more about this Go project's code standards.


🤖 AI Compliance

This project documents expectations for AI assistants using a few dedicated files:

  • AGENTS.md — canonical rules for coding style, workflows, and pull requests used by Codex.
  • CLAUDE.md — quick checklist for the Claude agent.
  • .cursorrules — machine-readable subset of the policies for Cursor and similar tools.
  • sweep.yaml — rules for Sweep, a tool for code review and pull request management.

Edit AGENTS.md first when adjusting these policies, and keep the other files in sync within the same pull request.


👥 Maintainers

Siggi
Siggi

🤝 Contributing

View the contributing guidelines and please follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏

Stars


📝 License

License

Documentation ¶

Index ¶

Constants ¶

View Source
const (
	NodeAddOneTry internal.NodeAddType = "onetry"
	NodeAddRemove internal.NodeAddType = "remove"
	NodeAddAdd    internal.NodeAddType = "add"
)

NodeAdd enums.

View Source
const (
	BanActionAdd    internal.BanAction = "add"
	BanActionRemove internal.BanAction = "remove"
)

BanAction enums.

Variables ¶

This section is empty.

Functions ¶

This section is empty.

Types ¶

type BitcoinClientOptFunc ¶

type BitcoinClientOptFunc func(c *clientOpts)

BitcoinClientOptFunc for setting bitcoin client options.

func WithCache ¶

func WithCache() BitcoinClientOptFunc

WithCache enable response caching.

func WithCreds ¶

func WithCreds(username, password string) BitcoinClientOptFunc

WithCreds set the bitcoin node credentials.

func WithCustomRPC ¶

func WithCustomRPC(rpc service.RPC) BitcoinClientOptFunc

WithCustomRPC set a custom RPC client.

func WithHost ¶

func WithHost(host string) BitcoinClientOptFunc

WithHost set the bitcoin node host.

func WithMainnet ¶

func WithMainnet() BitcoinClientOptFunc

WithMainnet set whether the node is a mainnet node.

func WithTimeout ¶

func WithTimeout(seconds time.Duration) BitcoinClientOptFunc

WithTimeout set the timeout for the http client.

type BlockChainClient ¶

type BlockChainClient interface {
	BestBlockHash(ctx context.Context) (string, error)
	BlockHex(ctx context.Context, hash string) (string, error)
	BlockHexByHeight(ctx context.Context, height int) (string, error)
	BlockDecodeHeader(ctx context.Context, hash string) (*models.BlockDecodeHeader, error)
	BlockDecodeHeaderByHeight(ctx context.Context, height int) (*models.BlockDecodeHeader, error)
	Block(ctx context.Context, hash string) (*models.Block, error)
	BlockByHeight(ctx context.Context, height int) (*models.Block, error)
	ChainInfo(ctx context.Context) (*models.ChainInfo, error)
	BlockCount(ctx context.Context) (uint32, error)
	BlockHash(ctx context.Context, height int) (string, error)
	BlockHeader(ctx context.Context, hash string) (*models.BlockHeader, error)
	BlockHeaderHex(ctx context.Context, hash string) (string, error)
	BlockStats(ctx context.Context, hash string, fields ...string) (*models.BlockStats, error)
	BlockStatsByHeight(ctx context.Context, height int, fields ...string) (*models.BlockStats, error)
	ChainTips(ctx context.Context) ([]*models.ChainTip, error)
	ChainTxStats(ctx context.Context, opts *models.OptsChainTxStats) (*models.ChainTxStats, error)
	Difficulty(ctx context.Context) (float64, error)
	InvalidateBlock(ctx context.Context, blockHash string) error
	MerkleProof(ctx context.Context, blockHash, txID string, opts *models.OptsMerkleProof) (*bc.MerkleProof, error)
	LegacyMerkleProof(ctx context.Context, txID string,
		opts *models.OptsLegacyMerkleProof) (*models.LegacyMerkleProof, error)
	RawMempool(ctx context.Context) (models.MempoolTxs, error)
	RawMempoolIDs(ctx context.Context) ([]string, error)
	RawNonFinalMempool(ctx context.Context) ([]string, error)
	MempoolEntry(ctx context.Context, txID string) (*models.MempoolEntry, error)
	MempoolAncestors(ctx context.Context, txID string) (models.MempoolTxs, error)
	MempoolAncestorIDs(ctx context.Context, txID string) ([]string, error)
	MempoolDescendants(ctx context.Context, txID string) (models.MempoolTxs, error)
	MempoolDescendantIDs(ctx context.Context, txID string) ([]string, error)
	Output(ctx context.Context, txID string, n int, opts *models.OptsOutput) (*models.Output, error)
	OutputSetInfo(ctx context.Context) (*models.OutputSetInfo, error)
	PreciousBlock(ctx context.Context, blockHash string) error
	PruneChain(ctx context.Context, height int) (uint32, error)
	CheckJournal(ctx context.Context) (*models.JournalStatus, error)
	RebuildJournal(ctx context.Context) error
	VerifyChain(ctx context.Context) (bool, error)
	Generate(ctx context.Context, n int, opts *models.OptsGenerate) ([]string, error)
	GenerateToAddress(ctx context.Context, n int, addr string, opts *models.OptsGenerate) ([]string, error)
}

BlockChainClient interfaces interaction with the blockchain sub commands on a bitcoin node.

func NewBlockChainClient ¶

func NewBlockChainClient(oo ...BitcoinClientOptFunc) BlockChainClient

NewBlockChainClient returns a client only capable of interfacing with the blockchain sub commands on a bitcoin node.

type ControlClient ¶

type ControlClient interface {
	ActiveZMQNotifications(ctx context.Context) ([]*models.ZMQNotification, error)
	DumpParams(ctx context.Context) ([]string, error)
	Info(ctx context.Context) (*models.Info, error)
	MemoryInfo(ctx context.Context) (*models.MemoryInfo, error)
	Settings(ctx context.Context) (*models.Settings, error)
	Stop(ctx context.Context) error
	Uptime(ctx context.Context) (time.Duration, error)
}

ControlClient interfaces interaction with the control sub commands on a bitcoin node.

func NewControlClient ¶

func NewControlClient(oo ...BitcoinClientOptFunc) ControlClient

NewControlClient returns a client only capable of interfacing with the control sub commands on a bitcoin node.

type MiningClient ¶

type MiningClient interface {
	BlockTemplate(ctx context.Context, opts *models.BlockTemplateRequest) (*models.BlockTemplate, error)
	MiningCandidate(ctx context.Context, opts *models.OptsMiningCandidate) (*models.MiningCandidate, error)
	MiningInfo(ctx context.Context) (*models.MiningInfo, error)
	NetworkHashPS(ctx context.Context, opts *models.OptsNetworkHashPS) (uint64, error)
	PrioritiseTx(ctx context.Context, txID string, feeDelta int64) (bool, error)
	SubmitBlock(ctx context.Context, block *bc.Block, params *models.OptsSubmitBlock) (string, error)
	SubmitMiningSolution(ctx context.Context, solution *models.MiningSolution) (string, error)
	VerifyBlockCandidate(ctx context.Context, block *bc.Block, params *models.OptsSubmitBlock) (string, error)
}

MiningClient interfaces interaction with the mining sub commands on a bitcoin node.

func NewMiningClient ¶

func NewMiningClient(oo ...BitcoinClientOptFunc) MiningClient

NewMiningClient returns a client only capable of interfacing with the mining sub commands on a bitcoin node.

type NetworkClient ¶

type NetworkClient interface {
	Ping(ctx context.Context) error
	AddNode(ctx context.Context, node string, command internal.NodeAddType) error
	ClearBanned(ctx context.Context) error
	DisconnectNode(ctx context.Context, params models.ParamsDisconnectNode) error
	NodeInfo(ctx context.Context, opts *models.OptsNodeInfo) ([]*models.NodeInfo, error)
	ConnectionCount(ctx context.Context) (uint64, error)
	ExcessiveBlock(ctx context.Context) (*models.ExcessiveBlock, error)
	NetworkTotals(ctx context.Context) (*models.NetworkTotals, error)
	NetworkInfo(ctx context.Context) (*models.NetworkInfo, error)
	PeerInfo(ctx context.Context) ([]*models.PeerInfo, error)
	ListBanned(ctx context.Context) ([]*models.BannedSubnet, error)
	SetBan(ctx context.Context, subnet string, action internal.BanAction, opts *models.OptsSetBan) error
	SetBlockMaxSize(ctx context.Context, size uint64) (string, error)
	SetExcessiveBlock(ctx context.Context, size uint64) (string, error)
	SetNetworkActive(ctx context.Context, enabled bool) error
	SetTxPropagationFrequency(ctx context.Context, frequency uint64) error
}

NetworkClient interfaces interaction with the network sub commands on a bitcoin node.

func NewNetworkClient ¶

func NewNetworkClient(oo ...BitcoinClientOptFunc) NetworkClient

NewNetworkClient returns a client only capable of interfacing with the network sub commands on a bitcoin node.

type NodeClient ¶

NodeClient interfaces interacting with all commands on a bitcoin node.

func NewNodeClient ¶

func NewNodeClient(oo ...BitcoinClientOptFunc) NodeClient

NewNodeClient returns a node client, built from the provided option funcs. This client is used for interfacing with the bitcoin node across all subcategories.

type TransactionClient ¶

type TransactionClient interface {
	AddToConfiscationTransactionWhitelist(ctx context.Context, funds []models.ConfiscationTransactionDetails) (*models.AddToConfiscationTransactionWhitelistResponse, error)
	AddToConsensusBlacklist(ctx context.Context, funds []models.Fund) (*models.AddToConsensusBlacklistResponse, error)
	CreateRawTransaction(ctx context.Context, utxos bt.UTXOs, params models.ParamsCreateRawTransaction) (*bt.Tx, error)
	FundRawTransaction(ctx context.Context, tx *bt.Tx,
		opts *models.OptsFundRawTransaction) (*models.FundRawTransaction, error)
	RawTransaction(ctx context.Context, txID string) (*bt.Tx, error)
	SignRawTransaction(ctx context.Context, tx *bt.Tx,
		opts *models.OptsSignRawTransaction) (*models.SignedRawTransaction, error)
	SendRawTransaction(ctx context.Context, tx *bt.Tx, opts *models.OptsSendRawTransaction) (string, error)
	SendRawTransactions(ctx context.Context,
		params ...models.ParamsSendRawTransactions) (*models.SendRawTransactionsResponse, error)
}

TransactionClient interfaces interaction with the transaction sub commands on a bitcoin node.

func NewTransactionClient ¶

func NewTransactionClient(oo ...BitcoinClientOptFunc) TransactionClient

NewTransactionClient returns a client only capable of interfacing with the transaction sub commands on a bitcoin node.

type UtilClient ¶

type UtilClient interface {
	ClearInvalidTransactions(ctx context.Context) (uint64, error)
	CreateMultiSig(ctx context.Context, n int, keys ...string) (*models.MultiSig, error)
	ValidateAddress(ctx context.Context, address string) (*models.ValidateAddress, error)
	SignMessageWithPrivKey(ctx context.Context, w *wif.WIF, msg string) (string, error)
	VerifySignedMessage(ctx context.Context, w *wif.WIF, signature, message string) (bool, error)
}

UtilClient interfaces interaction with the util sub commands on a bitcoin node.

func NewUtilClient ¶

func NewUtilClient(oo ...BitcoinClientOptFunc) UtilClient

NewUtilClient returns a client only capable of interfacing with the util sub commands on a bitcoin node.

type WalletClient ¶

type WalletClient interface {
	AbandonTransaction(ctx context.Context, txID string) error
	AddMultiSigAddress(ctx context.Context, n int, keys ...string) (string, error)
	BackupWallet(ctx context.Context, dest string) error
	DumpPrivateKey(ctx context.Context, address string) (*wif.WIF, error)
	DumpWallet(ctx context.Context, dest string) (*models.DumpWallet, error)
	Account(ctx context.Context, address string) (string, error)
	AccountAddress(ctx context.Context, account string) (string, error)
	AccountAddresses(ctx context.Context, account string) ([]string, error)
	Balance(ctx context.Context, opts *models.OptsBalance) (uint64, error)
	UnconfirmedBalance(ctx context.Context) (uint64, error)
	NewAddress(ctx context.Context, opts *models.OptsNewAddress) (string, error)
	RawChangeAddress(ctx context.Context) (string, error)
	ReceivedByAddress(ctx context.Context, address string) (uint64, error)
	Transaction(ctx context.Context, txID string) (*models.Transaction, error)
	ImportAddress(ctx context.Context, address string, opts *models.OptsImportAddress) error
	WalletInfo(ctx context.Context) (*models.WalletInfo, error)
	ImportMulti(ctx context.Context, reqs []models.ImportMultiRequest,
		opts *models.OptsImportMulti) ([]*models.ImportMulti, error)
	ImportPrivateKey(ctx context.Context, w *wif.WIF, opts *models.OptsImportPrivateKey) error
	ImportPrunedFunds(ctx context.Context, tx *bt.Tx, txOutProof string) error
	ImportPublicKey(ctx context.Context, publicKey string, opts *models.OptsImportPublicKey) error
	ImportWallet(ctx context.Context, filename string) error
	KeypoolRefill(ctx context.Context, opts *models.OptsKeypoolRefill) error
	ListAccounts(ctx context.Context, opts *models.OptsListAccounts) (map[string]uint64, error)
	ListLockUnspent(ctx context.Context) ([]*models.LockUnspent, error)
	ListReceivedByAccount(ctx context.Context, opts *models.OptsListReceivedBy) ([]*models.ReceivedByAccount, error)
	ListReceivedByAddress(ctx context.Context, opts *models.OptsListReceivedBy) ([]*models.ReceivedByAddress, error)
	ListSinceBlock(ctx context.Context, opts *models.OptsListSinceBlock) (*models.SinceBlock, error)
	ListTransactions(ctx context.Context, opts *models.OptsListTransactions) ([]*models.Transaction, error)
	ListUnspent(ctx context.Context, opts *models.OptsListUnspent) (bt.UTXOs, error)
	ListWallets(ctx context.Context) ([]string, error)
	LockUnspent(ctx context.Context, lock bool, opts *models.OptsLockUnspent) (bool, error)
	Move(ctx context.Context, from, to string, amount uint64, opts *models.OptsMove) (bool, error)
	RemovePrunedFunds(ctx context.Context, txID string) error
	SendFrom(ctx context.Context, from, to string, amount uint64, opts *models.OptsSendFrom) (string, error)
	SendMany(ctx context.Context, from string, amounts map[string]uint64, opts *models.OptsSendMany) (string, error)
	SendToAddress(ctx context.Context, address string, amount uint64, opts *models.OptsSendToAddress) (string, error)
	SetAccount(ctx context.Context, address, account string) error
	SetTxFee(ctx context.Context, amount uint64) (bool, error)
	SignMessage(ctx context.Context, address, message string) (string, error)
	EncryptWallet(ctx context.Context, passphrase string) error
	WalletPhassphrase(ctx context.Context, passphrase string, timeout int) error
	WalletPhassphraseChange(ctx context.Context, oldPassphrase, newPassphrase string) error
	WalletLock(ctx context.Context) error
}

WalletClient interfaces interaction with the wallet sub commands on a bitcoin node.

func NewWalletClient ¶

func NewWalletClient(oo ...BitcoinClientOptFunc) WalletClient

NewWalletClient returns a client only capable of interfacing with the wallet sub commands on a bitcoin node.

Jump to

Keyboard shortcuts

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