whatsonchain

package module
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2023 License: MIT Imports: 15 Imported by: 8

README

go-whatsonchain

The unofficial golang implementation for the whatsonchain.com API

Release Build Status Report codecov Go Sponsor Donate
Mergify Status Gitpod Ready-to-Code


Table of Contents


Installation

go-whatsonchain requires a supported release of Go.

go get -u github.com/mrz1836/go-whatsonchain

Documentation

View the generated documentation

GoDoc

Features
  • Client is completely configurable
  • Customize the network per request (main, test or stn)
  • Using default heimdall http client with exponential backoff & more
  • Use your own custom HTTP client and API Key
  • Current coverage for the whatsonchain.com API
    • Health
      • Get API Status
    • Chain Info
      • Get Blockchain Info
      • Get Circulating Supply
    • Block
      • Get by Hash
      • Get by Height
      • Get Block Pages
      • Get Header by Hash
      • Get Headers
    • Transaction
      • Get by TX Hash
      • Broadcast Transaction
      • Bulk Broadcast
      • Bulk Transaction Details
      • Decode Transaction
      • Download Receipt
      • Get Raw Transaction Data
      • Get Raw Transaction Output
      • Get Merkle Proof
      • Get Merkle Proof (TSC)
      • Get Bulk Transaction Details (Custom)
    • Mempool
      • Get Mempool Info
      • Get Mempool Transactions
    • Address
      • Get Address Info
      • Get Balance
      • Get History
      • Get Unspent Transactions
      • Get Unspent Transaction Details (Custom)
      • Bulk Balance
      • Bulk UTXOs
      • Download Statement
    • Script
      • Get Script History
      • Get Script Unspent Transactions
      • Bulk UTXOs
    • Exchange Rate
      • Get Exchange Rate
    • Search
      • Get Explorer Links
    • Web Sockets
      • New block header event
      • Block headers history
      • Block transactions
      • Mempool transactions
      • Confirmed transactions
      • Chain Stats
      • Customized events
Library Deployment

goreleaser for easy binary or library deployment to Github and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

make help

List of all current commands:

all                   Runs lint, test-short and vet
clean                 Remove previous builds and any test cache data
clean-mods            Remove all the Go mod cache
coverage              Shows the test coverage
diff                  Show the git diff
generate              Runs the go generate command in the base of the repo
godocs                Sync the latest tag with GoDocs
help                  Show this help message
install               Install the application
install-go            Install the application (Using Native Go)
install-releaser      Install the GoReleaser application
lint                  Run the golangci-lint application (install if not found)
release               Full production release (creates release in Github)
release               Runs common.release then runs godocs
release-snap          Test the full release (build binaries)
release-test          Full production test release (everything except deploy)
replace-version       Replaces the version in HTML/JS (pre-deploy)
tag                   Generate a new tag and push (tag version=0.0.0)
tag-remove            Remove a tag if found (tag-remove version=0.0.0)
tag-update            Update an existing tag to current commit (tag-update version=0.0.0)
test                  Runs lint and ALL tests
test-ci               Runs all tests via CI (exports coverage)
test-ci-no-race       Runs all tests via CI (no race) (exports coverage)
test-ci-short         Runs unit tests via CI (exports coverage)
test-no-lint          Runs just tests
test-short            Runs vet, lint and tests (excludes integration tests)
test-unit             Runs tests and outputs coverage
uninstall             Uninstall the application (and remove files)
update-linter         Update the golangci-lint package (macOS only)
vet                   Run the Go vet application

Examples & Tests

All unit tests and examples run via Github Actions and uses Go version 1.18.x. View the configuration file.

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.


Usage

View the whatsonchain examples

Basic implementation:

package main

import (
    "context"
    "fmt"
    
    "github.com/mrz1836/go-whatsonchain"
)

func main() {

    // Create a client
    client := whatsonchain.NewClient(whatsonchain.NetworkMain, nil, nil)

    // Get a balance for an address
    balance, _ := client.AddressBalance(context.Background(),"16ZqP5Tb22KJuvSAbjNkoiZs13mmRmexZA")
    fmt.Println("confirmed balance", balance.Confirmed)
}

Maintainers

MrZ
MrZ

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 👏 or by making a bitcoin donation to ensure this journey continues indefinitely! 🚀

Stars

Credits

WhatsOnChain for their hard work on the Whatsonchain API

AustEcon's Python Version


License

License

Documentation

Overview

Package whatsonchain is the unofficial golang implementation for the whatsonchain.com API

Example:

``` // Create a new client: client := whatsonchain.NewClient(whatsonchain.NetworkMain, nil, nil)

// Get a balance for an address: balance, _ := client.AddressBalance("16ZqP5Tb22KJuvSAbjNkoiZs13mmRmexZA") fmt.Println("confirmed balance", balance.Confirmed) ```

Index

Examples

Constants

View Source
const (

	// NetworkMain is for main-net
	NetworkMain NetworkType = "main"

	// NetworkTest is for test-net
	NetworkTest NetworkType = "test"

	// NetworkStn is for the stn-net
	NetworkStn NetworkType = "stn"

	// MaxTransactionsUTXO is the max allowed in the request
	MaxTransactionsUTXO int = 20

	// MaxTransactionsRaw is the max allowed in the request
	MaxTransactionsRaw int = 20

	// MaxBroadcastTransactions is the max transactions for Bulk Broadcast
	MaxBroadcastTransactions = 100

	// MaxSingleTransactionSize is the max single TX size for Bulk Broadcast
	MaxSingleTransactionSize = 102400

	// MaxCombinedTransactionSize is the max of all transactions combined
	MaxCombinedTransactionSize = 1e+7

	// MaxAddressesForLookup is the max allowed in the request for Bulk requests
	MaxAddressesForLookup int = 20

	// MaxScriptsForLookup is the max allowed in the request for Bulk requests
	MaxScriptsForLookup int = 20
)

Variables

View Source
var ErrAddressNotFound = errors.New("address not found")

ErrAddressNotFound is when an address is not found

View Source
var ErrBlockNotFound = errors.New("block not found")

ErrBlockNotFound is when a block is not found

View Source
var ErrChainInfoNotFound = errors.New("chain info not found")

ErrChainInfoNotFound is when the chain info is not found

View Source
var ErrExchangeRateNotFound = errors.New("exchange rate not found")

ErrExchangeRateNotFound is when the exchange rate is not found

View Source
var ErrHeadersNotFound = errors.New("headers not found")

ErrHeadersNotFound is when the headers are not found

View Source
var ErrMempoolInfoNotFound = errors.New("mempool info not found")

ErrMempoolInfoNotFound is when the mempool info is not found

View Source
var ErrScriptNotFound = errors.New("script not found")

ErrScriptNotFound is when a script is not found

View Source
var ErrTransactionNotFound = errors.New("transaction not found")

ErrTransactionNotFound is when a transaction is not found

Functions

This section is empty.

Types

type AddressBalance

type AddressBalance struct {
	Confirmed   int64 `json:"confirmed"`
	Unconfirmed int64 `json:"unconfirmed"`
}

AddressBalance is the address balance (unconfirmed and confirmed)

type AddressBalanceRecord added in v0.6.3

type AddressBalanceRecord struct {
	Address string          `json:"address"`
	Error   string          `json:"error"`
	Balance *AddressBalance `json:"balance"`
}

AddressBalanceRecord is the result from Bulk Balance request

type AddressBalances added in v0.6.3

type AddressBalances []*AddressBalanceRecord

AddressBalances is the response from Bulk Balance request

type AddressHistory

type AddressHistory []*HistoryRecord

AddressHistory is the history of transactions for an address

type AddressInfo

type AddressInfo struct {
	Address      string `json:"address"`
	IsMine       bool   `json:"ismine"`
	IsScript     bool   `json:"isscript"`
	IsValid      bool   `json:"isvalid"`
	IsWatchOnly  bool   `json:"iswatchonly"`
	ScriptPubKey string `json:"scriptPubKey"`
}

AddressInfo is the address info for a returned address request

type AddressList added in v0.6.3

type AddressList struct {
	Addresses []string `json:"addresses"`
}

AddressList is used to create a Bulk Balance request

type AddressService added in v0.9.1

type AddressService interface {
	AddressBalance(ctx context.Context, address string) (balance *AddressBalance, err error)
	AddressHistory(ctx context.Context, address string) (history AddressHistory, err error)
	AddressInfo(ctx context.Context, address string) (addressInfo *AddressInfo, err error)
	AddressUnspentTransactionDetails(ctx context.Context, address string, maxTransactions int) (history AddressHistory, err error)
	AddressUnspentTransactions(ctx context.Context, address string) (history AddressHistory, err error)
	BulkBalance(ctx context.Context, list *AddressList) (balances AddressBalances, err error)
}

AddressService is the WhatsOnChain address related requests

type BlockInfo

type BlockInfo struct {
	Bits              string         `json:"bits"`
	ChainWork         string         `json:"chainwork"`
	CoinbaseTx        CoinbaseTxInfo `json:"coinbaseTx"`
	Confirmations     int64          `json:"confirmations"`
	Difficulty        float64        `json:"difficulty"`
	Hash              string         `json:"hash"`
	Height            int64          `json:"height"`
	MedianTime        int64          `json:"mediantime"`
	MerkleRoot        string         `json:"merkleroot"`
	Miner             string         `json:"Bmgpool"`
	NextBlockHash     string         `json:"nextblockhash"`
	Nonce             int64          `json:"nonce"`
	Pages             Page           `json:"pages"`
	PreviousBlockHash string         `json:"previousblockhash"`
	Size              int64          `json:"size"`
	Time              int64          `json:"time"`
	TotalFees         float64        `json:"totalFees"`
	Tx                []string       `json:"tx"`
	TxCount           int64          `json:"txcount"`
	Version           int64          `json:"version"`
	VersionHex        string         `json:"versionHex"`
}

BlockInfo is the response info about a returned block

type BlockPagesInfo

type BlockPagesInfo []string

BlockPagesInfo is the response from the page request

type BlockService added in v0.9.1

type BlockService interface {
	GetBlockByHash(ctx context.Context, hash string) (blockInfo *BlockInfo, err error)
	GetBlockByHeight(ctx context.Context, height int64) (blockInfo *BlockInfo, err error)
	GetBlockPages(ctx context.Context, hash string, page int) (txList BlockPagesInfo, err error)
	GetHeaderByHash(ctx context.Context, hash string) (headerInfo *BlockInfo, err error)
	GetHeaders(ctx context.Context) (blockHeaders []*BlockInfo, err error)
}

BlockService is the WhatsOnChain block related requests

type BulkBroadcastResponse added in v0.0.5

type BulkBroadcastResponse struct {
	Feedback  bool   `json:"feedback"`
	StatusURL string `json:"statusUrl"`
}

BulkBroadcastResponse is the response from a bulk broadcast request

type BulkResponseRecord added in v0.6.3

type BulkResponseRecord struct {
	Address string           `json:"address"`
	Error   string           `json:"error"`
	Utxos   []*HistoryRecord `json:"unspent"`
}

BulkResponseRecord is the record in the results for Bulk Unspent transactions

type BulkScriptResponseRecord added in v0.6.3

type BulkScriptResponseRecord struct {
	Script string           `json:"script"`
	Error  string           `json:"error"`
	Utxos  []*HistoryRecord `json:"unspent"`
}

BulkScriptResponseRecord is the record in the results for Bulk Unspent transactions

type BulkScriptUnspentResponse added in v0.6.3

type BulkScriptUnspentResponse []*BulkScriptResponseRecord

BulkScriptUnspentResponse is the response from Bulk Unspent transactions

type BulkUnspentResponse added in v0.6.3

type BulkUnspentResponse []*BulkResponseRecord

BulkUnspentResponse is the response from Bulk Unspent transactions

type ChainInfo

type ChainInfo struct {
	BestBlockHash        string  `json:"bestblockhash"`
	Blocks               int64   `json:"blocks"`
	Chain                string  `json:"chain"`
	ChainWork            string  `json:"chainwork"`
	Difficulty           float64 `json:"difficulty"`
	Headers              int64   `json:"headers"`
	MedianTime           int64   `json:"mediantime"`
	Pruned               bool    `json:"pruned"`
	VerificationProgress float64 `json:"verificationprogress"`
}

ChainInfo is the structure response from getting info about the chain

type ChainService added in v0.9.1

type ChainService interface {
	GetChainInfo(ctx context.Context) (chainInfo *ChainInfo, err error)
	GetCirculatingSupply(ctx context.Context) (supply float64, err error)
	GetExchangeRate(ctx context.Context) (rate *ExchangeRate, err error)
}

ChainService is the WhatsOnChain chain info requests

type CirculatingSupply added in v0.2.4

type CirculatingSupply float64

CirculatingSupply is the structure response

type Client

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

Client is the parent struct that wraps the heimdall client

func (*Client) AddressBalance

func (c *Client) AddressBalance(ctx context.Context, address string) (balance *AddressBalance, err error)

AddressBalance this endpoint retrieves confirmed and unconfirmed address balance.

For more information: https://developers.whatsonchain.com/#get-balance

func (*Client) AddressHistory

func (c *Client) AddressHistory(ctx context.Context, address string) (history AddressHistory, err error)

AddressHistory this endpoint retrieves confirmed and unconfirmed address transactions.

For more information: https://developers.whatsonchain.com/#get-history

func (*Client) AddressInfo

func (c *Client) AddressInfo(ctx context.Context, address string) (addressInfo *AddressInfo, err error)

AddressInfo this endpoint retrieves various address info.

For more information: https://developers.whatsonchain.com/#address

func (*Client) AddressUnspentTransactionDetails added in v0.2.3

func (c *Client) AddressUnspentTransactionDetails(ctx context.Context, address string, maxTransactions int) (history AddressHistory, err error)

AddressUnspentTransactionDetails this endpoint retrieves transaction details for a given address Use max transactions to filter if there are more UTXOs returned than needed by the user

For more information: (custom request for this go package)

func (*Client) AddressUnspentTransactions

func (c *Client) AddressUnspentTransactions(ctx context.Context, address string) (history AddressHistory, err error)

AddressUnspentTransactions this endpoint retrieves ordered list of UTXOs.

For more information: https://developers.whatsonchain.com/#get-unspent-transactions

func (*Client) BroadcastTx

func (c *Client) BroadcastTx(ctx context.Context, txHex string) (txID string, err error)

BroadcastTx will broadcast transaction using this endpoint. Get tx_id in response or error msg from node.

For more information: https://developers.whatsonchain.com/#broadcast-transaction

func (*Client) BulkBalance added in v0.6.3

func (c *Client) BulkBalance(ctx context.Context, list *AddressList) (balances AddressBalances, err error)

BulkBalance this endpoint retrieves confirmed and unconfirmed address balances Max of 20 addresses at a time

For more information: https://developers.whatsonchain.com/#bulk-balance

func (*Client) BulkBroadcastTx added in v0.0.5

func (c *Client) BulkBroadcastTx(ctx context.Context, rawTxs []string,
	feedback bool) (response *BulkBroadcastResponse, err error)

BulkBroadcastTx will broadcast many transactions at once You can bulk broadcast transactions using this endpoint.

Size per transaction should be less than 100KB
Overall payload per request should be less than 10MB
Max 100 transactions per request
Only available for mainnet

Tip: First transaction in the list should have an output to WOC tip address '16ZqP5Tb22KJuvSAbjNkoiZs13mmRmexZA'

Feedback: true/false: true if response from the node is required for each transaction, otherwise, set it to false. (For stress testing set it to false). When set to true a unique url is provided to check the progress of the submitted transactions, eg 'QUEUED' or 'PROCESSED', with response data from node. You can poll the provided unique url until all transactions are marked as 'PROCESSED'. Progress of the transactions are tracked on this unique url for up to 5 hours.

For more information: https://developers.whatsonchain.com/#bulk-broadcast

func (*Client) BulkRawTransactionData added in v0.9.4

func (c *Client) BulkRawTransactionData(ctx context.Context, hashes *TxHashes) (txList TxList, err error)

BulkRawTransactionData this fetches raw hex data for multiple transactions in single request Max 20 transactions per request

For more information: https://developers.whatsonchain.com/#bulk-raw-transaction-data

func (*Client) BulkRawTransactionDataProcessor added in v0.9.4

func (c *Client) BulkRawTransactionDataProcessor(ctx context.Context, hashes *TxHashes) (txList TxList, err error)

BulkRawTransactionDataProcessor this fetches raw hex data for multiple transactions in single request and handles chunking Max 20 transactions per request

For more information: https://developers.whatsonchain.com/#bulk-raw-transaction-data

func (*Client) BulkScriptUnspentTransactions added in v0.6.3

func (c *Client) BulkScriptUnspentTransactions(ctx context.Context,
	list *ScriptsList) (response BulkScriptUnspentResponse, err error)

BulkScriptUnspentTransactions will fetch UTXOs for multiple scripts in a single request Max of 20 scripts at a time

For more information: https://developers.whatsonchain.com/#bulk-script-unspent-transactions

func (*Client) BulkTransactionDetails added in v0.4.0

func (c *Client) BulkTransactionDetails(ctx context.Context, hashes *TxHashes) (txList TxList, err error)

BulkTransactionDetails this fetches details for multiple transactions in single request Max 20 transactions per request

For more information: https://developers.whatsonchain.com/#bulk-transaction-details

func (*Client) BulkTransactionDetailsProcessor added in v0.6.4

func (c *Client) BulkTransactionDetailsProcessor(ctx context.Context, hashes *TxHashes) (txList TxList, err error)

BulkTransactionDetailsProcessor will get the details for ALL transactions in batches Processes 20 transactions per request See: BulkTransactionDetails()

func (*Client) BulkUnspentTransactions added in v0.6.3

func (c *Client) BulkUnspentTransactions(ctx context.Context, list *AddressList) (response BulkUnspentResponse, err error)

BulkUnspentTransactions will fetch UTXOs for multiple addresses in a single request Max of 20 addresses at a time

For more information: https://developers.whatsonchain.com/#bulk-unspent-transactions

func (*Client) BulkUnspentTransactionsProcessor added in v0.9.4

func (c *Client) BulkUnspentTransactionsProcessor(ctx context.Context, list *AddressList) (responseList BulkUnspentResponse, err error)

BulkUnspentTransactionsProcessor will fetch UTXOs for multiple addresses in a single request while automatically batching Max of 20 addresses at a time

For more information: https://developers.whatsonchain.com/#bulk-unspent-transactions

func (*Client) DecodeTransaction added in v0.4.0

func (c *Client) DecodeTransaction(ctx context.Context, txHex string) (txInfo *TxInfo, err error)

DecodeTransaction this endpoint decodes raw transaction

For more information: https://developers.whatsonchain.com/#decode-transaction

func (*Client) DownloadReceipt added in v0.4.0

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

DownloadReceipt this endpoint downloads a transaction receipt (PDF) The contents will be returned in plain-text and need to be converted to a file.pdf

For more information: https://developers.whatsonchain.com/#download-receipt

func (*Client) DownloadStatement added in v0.4.0

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

DownloadStatement this endpoint downloads an address statement (PDF) The contents will be returned in plain-text and need to be converted to a file.pdf

For more information: https://developers.whatsonchain.com/#download-statement

func (*Client) GetBlockByHash

func (c *Client) GetBlockByHash(ctx context.Context, hash string) (blockInfo *BlockInfo, err error)

GetBlockByHash this endpoint retrieves block details with given hash.

For more information: https://developers.whatsonchain.com/#get-by-hash

func (*Client) GetBlockByHeight

func (c *Client) GetBlockByHeight(ctx context.Context, height int64) (blockInfo *BlockInfo, err error)

GetBlockByHeight this endpoint retrieves block details with given block height.

For more information: https://developers.whatsonchain.com/#get-by-height

func (*Client) GetBlockPages

func (c *Client) GetBlockPages(ctx context.Context, hash string, page int) (txList BlockPagesInfo, err error)

GetBlockPages if the block has more than 1000 transactions the page URIs will be provided in the "pages element" when getting a block by hash or height.

For more information: https://developers.whatsonchain.com/#get-block-pages

func (*Client) GetChainInfo

func (c *Client) GetChainInfo(ctx context.Context) (chainInfo *ChainInfo, err error)

GetChainInfo this endpoint retrieves various state info of the chain for the selected network.

For more information: https://developers.whatsonchain.com/#chain-info

func (*Client) GetCirculatingSupply added in v0.2.4

func (c *Client) GetCirculatingSupply(ctx context.Context) (supply float64, err error)

GetCirculatingSupply this endpoint retrieves the current circulating supply

For more information: https://developers.whatsonchain.com/#get-circulating-supply

func (*Client) GetExchangeRate added in v0.4.0

func (c *Client) GetExchangeRate(ctx context.Context) (rate *ExchangeRate, err error)

GetExchangeRate this endpoint provides exchange rate for BSV

For more information: https://developers.whatsonchain.com/#get-exchange-rate

func (c *Client) GetExplorerLinks(ctx context.Context, query string) (results SearchResults, err error)

GetExplorerLinks this endpoint identifies whether the posted query text is a block hash, txid or address and responds with WoC links. Ideal for extending customized search in apps.

For more information: https://developers.whatsonchain.com/#get-history

func (*Client) GetHeaderByHash added in v0.6.1

func (c *Client) GetHeaderByHash(ctx context.Context, hash string) (headerInfo *BlockInfo, err error)

GetHeaderByHash this endpoint retrieves block header details with given hash.

For more information: https://developers.whatsonchain.com/#get-header-by-hash

func (*Client) GetHeaders added in v0.6.1

func (c *Client) GetHeaders(ctx context.Context) (blockHeaders []*BlockInfo, err error)

GetHeaders this endpoint retrieves last 10 block headers.

For more information: https://developers.whatsonchain.com/#get-headers

func (*Client) GetHealth

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

GetHealth simple endpoint to show API server is up and running

For more information: https://developers.whatsonchain.com/#health

func (*Client) GetMempoolInfo added in v0.4.0

func (c *Client) GetMempoolInfo(ctx context.Context) (info *MempoolInfo, err error)

GetMempoolInfo this endpoint retrieves various info about the node's mempool for the selected network

For more information: https://developers.whatsonchain.com/#get-mempool-info

func (*Client) GetMempoolTransactions added in v0.4.0

func (c *Client) GetMempoolTransactions(ctx context.Context) (transactions []string, err error)

GetMempoolTransactions this endpoint will retrieve a list of transaction ids from the node's mempool for the selected network

For more information: https://developers.whatsonchain.com/#get-mempool-transactions

func (*Client) GetMerkleProof added in v0.0.4

func (c *Client) GetMerkleProof(ctx context.Context, hash string) (merkleResults MerkleResults, err error)

GetMerkleProof this endpoint returns merkle branch to a confirmed transaction

For more information: https://developers.whatsonchain.com/#get-merkle-proof

func (*Client) GetMerkleProofTSC added in v0.9.3

func (c *Client) GetMerkleProofTSC(ctx context.Context, hash string) (merkleResults MerkleTSCResults, err error)

GetMerkleProofTSC this endpoint returns TSC compliant proof to a confirmed transaction

For more information: TODO! No link today

func (*Client) GetRawTransactionData added in v0.3.0

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

GetRawTransactionData this endpoint returns raw hex for the transaction with given hash

For more information: https://developers.whatsonchain.com/#get-raw-transaction-data

func (*Client) GetRawTransactionOutputData added in v0.3.0

func (c *Client) GetRawTransactionOutputData(ctx context.Context, hash string, vOutIndex int) (string, error)

GetRawTransactionOutputData this endpoint returns raw hex for the transaction output with given hash and index

For more information: https://developers.whatsonchain.com/#get-raw-transaction-output-data

func (*Client) GetScriptHistory added in v0.4.0

func (c *Client) GetScriptHistory(ctx context.Context, scriptHash string) (history ScriptList, err error)

GetScriptHistory this endpoint retrieves confirmed and unconfirmed script transactions

For more information: https://developers.whatsonchain.com/#get-script-history

func (*Client) GetScriptUnspentTransactions added in v0.4.0

func (c *Client) GetScriptUnspentTransactions(ctx context.Context,
	scriptHash string) (scriptList ScriptList, err error)

GetScriptUnspentTransactions this endpoint retrieves ordered list of UTXOs

For more information: https://developers.whatsonchain.com/#get-script-unspent-transactions

func (*Client) GetTxByHash

func (c *Client) GetTxByHash(ctx context.Context, hash string) (txInfo *TxInfo, err error)

GetTxByHash this endpoint retrieves transaction details with given transaction hash

For more information: https://developers.whatsonchain.com/#get-by-tx-hash

func (*Client) HTTPClient

func (c *Client) HTTPClient() HTTPInterface

HTTPClient will return the current HTTP client

func (*Client) LastRequest

func (c *Client) LastRequest() *LastRequest

LastRequest will return the last request information

func (*Client) Network added in v0.5.0

func (c *Client) Network() NetworkType

Network will return the network

func (*Client) NewBlockHeadersWebsocket added in v0.10.4

func (c *Client) NewBlockHeadersWebsocket(handler SocketHandler) *centrifuge.Client

NewBlockHeadersWebsocket instantiates a new websocket client to stream block headers

func (*Client) NewMempoolWebsocket added in v0.10.0

func (c *Client) NewMempoolWebsocket(handler SocketHandler) *centrifuge.Client

NewMempoolWebsocket instantiates a new websocket client to stream mempool transactions

func (*Client) RateLimit added in v0.9.4

func (c *Client) RateLimit() int

RateLimit will return the current configured rate limit

func (*Client) UserAgent added in v0.5.0

func (c *Client) UserAgent() string

UserAgent will return the current user agent

type ClientInterface added in v0.9.0

ClientInterface is the WhatsOnChain client interface

func NewClient

func NewClient(network NetworkType, clientOptions *Options, customHTTPClient HTTPInterface) ClientInterface

NewClient creates a new client for WOC requests

Example

ExampleNewClient example using NewClient()

client := NewClient(NetworkTest, nil, nil)
fmt.Println(client.UserAgent())
Output:

go-whatsonchain: v0.13.0

type CoinbaseTxInfo

type CoinbaseTxInfo struct {
	BlockHash     string     `json:"blockhash"`
	BlockTime     int64      `json:"blocktime"`
	Confirmations int64      `json:"confirmations"`
	Hash          string     `json:"hash"`
	Hex           string     `json:"hex"`
	LockTime      int64      `json:"locktime"`
	Size          int64      `json:"size"`
	Time          int64      `json:"time"`
	TxID          string     `json:"txid"`
	Version       int64      `json:"version"`
	Vin           []VinInfo  `json:"vin"`
	Vout          []VoutInfo `json:"vout"`
}

CoinbaseTxInfo is the coinbase tx info inside the BlockInfo

type DownloadService added in v0.9.1

type DownloadService interface {
	DownloadReceipt(ctx context.Context, hash string) (string, error)
	DownloadStatement(ctx context.Context, address string) (string, error)
}

DownloadService is the WhatsOnChain receipt and download related requests

type ExchangeRate added in v0.4.0

type ExchangeRate struct {
	Currency string  `json:"currency"`
	Rate     float64 `json:"rate"`
	Time     int64   `json:"time"`
}

ExchangeRate is the response from getting the current exchange rate

type Fee added in v0.5.0

type Fee struct {
	Bytes    int `json:"bytes"`
	Satoshis int `json:"satoshis"`
}

Fee is the actual fee (satoshis per byte)

type FeeQuote added in v0.5.0

type FeeQuote struct {
	FeeType   string `json:"feeType"`
	MiningFee *Fee   `json:"miningFee"`
	RelayFee  *Fee   `json:"relayFee"`
}

FeeQuote is the structure response for a fee in a quote

type FeeQuotes added in v0.5.0

type FeeQuotes struct {
	Quotes []*QuoteProvider `json:"quotes"`
}

FeeQuotes is the structure response from getting quotes from Merchant API

type GeneralService added in v0.9.1

type GeneralService interface {
	GetExplorerLinks(ctx context.Context, query string) (results SearchResults, err error)
	GetHealth(ctx context.Context) (string, error)
}

GeneralService is the WhatsOnChain general service requests

type HTTPInterface added in v0.8.0

type HTTPInterface interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPInterface is used for the http client (mocking heimdall)

type HistoryRecord

type HistoryRecord struct {
	Height int64   `json:"height"`
	Info   *TxInfo `json:"info,omitempty"` // Custom for our wrapper
	TxHash string  `json:"tx_hash"`
	TxPos  int64   `json:"tx_pos"`
	Value  int64   `json:"value"`
}

HistoryRecord is an internal record of AddressHistory

type LastRequest

type LastRequest struct {
	Method     string `json:"method"`      // method is the HTTP method used
	PostData   string `json:"post_data"`   // postData is the post data submitted if POST/PUT request
	StatusCode int    `json:"status_code"` // statusCode is the last code from the request
	URL        string `json:"url"`         // url is the url used for the request
}

LastRequest is used to track what was submitted via the request()

type MempoolInfo added in v0.4.0

type MempoolInfo struct {
	Bytes         int64 `json:"bytes"`
	MaxMempool    int64 `json:"maxmempool"`
	MempoolMinFee int64 `json:"mempoolminfee"`
	Size          int64 `json:"size"`
	Usage         int64 `json:"usage"`
}

MempoolInfo is the response for the get mempool info request

type MempoolService added in v0.9.1

type MempoolService interface {
	GetMempoolInfo(ctx context.Context) (info *MempoolInfo, err error)
	GetMempoolTransactions(ctx context.Context) (transactions []string, err error)
}

MempoolService is the WhatsOnChain mempool requests

type MerchantError added in v0.5.0

type MerchantError struct {
	Code   int    `json:"code"`
	Error  string `json:"error"`
	Status int    `json:"status"`
}

MerchantError is the error response from a bad tx submission

type MerchantResponse added in v0.5.0

type MerchantResponse struct {
	APIVersion                string `json:"apiVersion"`
	CurrentHighestBlockHash   string `json:"currentHighestBlockHash"`
	CurrentHighestBlockHeight int64  `json:"currentHighestBlockHeight"`
	MinerID                   string `json:"minerId"`
	ResultDescription         string `json:"resultDescription"`
	ReturnResult              string `json:"returnResult"`
	Timestamp                 string `json:"timestamp"`
	TxID                      string `json:"txid"`
	TxSecondMempoolExpiry     int    `json:"txSecondMempoolExpiry"`
}

MerchantResponse is the response from a tx submission

type MerchantStatus added in v0.5.0

type MerchantStatus struct {
	APIVersion            string `json:"apiVersion"`
	BlockHash             string `json:"blockHash"`
	BlockHeight           int64  `json:"blockHeight"`
	Confirmations         int64  `json:"confirmations"`
	MinerID               string `json:"minerId"`
	ResultDescription     string `json:"resultDescription"`
	ReturnResult          string `json:"returnResult"`
	Timestamp             string `json:"timestamp"`
	TxSecondMempoolExpiry int    `json:"txSecondMempoolExpiry"`
}

MerchantStatus is the response from a status request

type MerkleBranch added in v0.3.0

type MerkleBranch struct {
	Hash string `json:"hash"`
	Pos  string `json:"pos"`
}

MerkleBranch is a merkle branch

type MerkleInfo added in v0.0.4

type MerkleInfo struct {
	BlockHash  string          `json:"blockHash"`
	Branches   []*MerkleBranch `json:"branches"`
	Hash       string          `json:"hash"`
	MerkleRoot string          `json:"merkleRoot"`
}

MerkleInfo is the response for the get merkle request

type MerkleResults added in v0.3.0

type MerkleResults []*MerkleInfo

MerkleResults is the results from the proof request

type MerkleTSCInfo added in v0.9.3

type MerkleTSCInfo struct {
	Index  int      `json:"index"`
	Nodes  []string `json:"nodes"`
	Target string   `json:"target"`
	TxOrID string   `json:"txOrId"`
}

MerkleTSCInfo is the response for the get TSC merkle request

type MerkleTSCResults added in v0.9.3

type MerkleTSCResults []*MerkleTSCInfo

MerkleTSCResults is the results from the tsc proof request

type NetworkType

type NetworkType string

NetworkType is used internally to represent the possible values for network in queries to be submitted: {"main", "test", "stn"}

type Options added in v0.2.0

type Options struct {
	APIKey                         string        `json:"api_key"`
	BackOffExponentFactor          float64       `json:"back_off_exponent_factor"`
	BackOffInitialTimeout          time.Duration `json:"back_off_initial_timeout"`
	BackOffMaximumJitterInterval   time.Duration `json:"back_off_maximum_jitter_interval"`
	BackOffMaxTimeout              time.Duration `json:"back_off_max_timeout"`
	DialerKeepAlive                time.Duration `json:"dialer_keep_alive"`
	DialerTimeout                  time.Duration `json:"dialer_timeout"`
	RateLimit                      int           `json:"rate_limit"`
	RequestRetryCount              int           `json:"request_retry_count"`
	RequestTimeout                 time.Duration `json:"request_timeout"`
	TransportExpectContinueTimeout time.Duration `json:"transport_expect_continue_timeout"`
	TransportIdleTimeout           time.Duration `json:"transport_idle_timeout"`
	TransportMaxIdleConnections    int           `json:"transport_max_idle_connections"`
	TransportTLSHandshakeTimeout   time.Duration `json:"transport_tls_handshake_timeout"`
	UserAgent                      string        `json:"user_agent"`
}

Options holds all the configuration for connection, dialer and transport

func ClientDefaultOptions added in v0.2.0

func ClientDefaultOptions() (clientOptions *Options)

ClientDefaultOptions will return an "Options" struct with the default settings Useful for starting with the default and then modifying as needed

type Page

type Page struct {
	Size int64    `json:"size"`
	URI  []string `json:"uri"`
}

Page is used as a subtype for BlockInfo

type Quote added in v0.5.0

type Quote struct {
	APIVersion                string      `json:"apiVersion"`
	CurrentHighestBlockHash   string      `json:"currentHighestBlockHash"`
	CurrentHighestBlockHeight int64       `json:"currentHighestBlockHeight"`
	ExpiryTime                string      `json:"expiryTime"`
	Fees                      []*FeeQuote `json:"fees"`
	MinerID                   string      `json:"minerId"`
	MinerReputation           interface{} `json:"minerReputation"`
	Timestamp                 string      `json:"timestamp"`
}

Quote is the structure response for a quote

type QuoteProvider added in v0.5.0

type QuoteProvider struct {
	Payload         string `json:"payload"`
	ProviderID      string `json:"providerId"`
	ProviderName    string `json:"providerName"`
	PublicKey       string `json:"publicKey"`
	Quote           *Quote `json:"quote"`
	Signature       string `json:"signature"`
	TxStatusURL     string `json:"txStatusUrl"`
	TxSubmissionURL string `json:"txSubmissionUrl"`
}

QuoteProvider is the structure response for a quote provider (which has quotes)

type ScriptList added in v0.4.0

type ScriptList []*ScriptRecord

ScriptList is the list of script history records

type ScriptPubKeyInfo

type ScriptPubKeyInfo struct {
	Addresses   []string `json:"addresses"`
	Asm         string   `json:"asm"`
	Hex         string   `json:"hex"`
	IsTruncated bool     `json:"isTruncated"`
	OpReturn    string   `json:"-"` // todo: support this (can be an object of key/vals based on the op return data)
	ReqSigs     int64    `json:"reqSigs"`
	Type        string   `json:"type"`
}

ScriptPubKeyInfo is the scriptPubKey info inside the VoutInfo

type ScriptRecord added in v0.4.0

type ScriptRecord struct {
	Height int64  `json:"height"`
	TxHash string `json:"tx_hash"`
	TxPos  int64  `json:"tx_pos"`
	Value  int64  `json:"value"`
}

ScriptRecord is the script history record

type ScriptService added in v0.9.1

type ScriptService interface {
	BulkScriptUnspentTransactions(ctx context.Context, list *ScriptsList) (response BulkScriptUnspentResponse, err error)
	GetScriptHistory(ctx context.Context, scriptHash string) (history ScriptList, err error)
	GetScriptUnspentTransactions(ctx context.Context, scriptHash string) (scriptList ScriptList, err error)
}

ScriptService is the WhatsOnChain script requests

type ScriptSigInfo

type ScriptSigInfo struct {
	Asm string `json:"asm"`
	Hex string `json:"hex"`
}

ScriptSigInfo is the scriptSig info inside the VinInfo

type ScriptsList added in v0.6.3

type ScriptsList struct {
	Scripts []string `json:"scripts"`
}

ScriptsList is used to create a Bulk UTXO request

type SearchResult added in v0.4.0

type SearchResult struct {
	Type string `json:"type"`
	URL  string `json:"url"`
}

SearchResult is the actual result for the search (included in SearchResults)

type SearchResults added in v0.4.0

type SearchResults struct {
	Results []*SearchResult `json:"results"`
}

SearchResults is the response from searching for explorer links

type SocketHandler added in v0.10.1

type SocketHandler interface {
	OnConnect(*centrifuge.Client, centrifuge.ConnectEvent)
	OnDisconnect(*centrifuge.Client, centrifuge.DisconnectEvent)
	OnError(*centrifuge.Client, centrifuge.ErrorEvent)
	OnJoin(*centrifuge.Subscription, centrifuge.JoinEvent)
	OnLeave(*centrifuge.Subscription, centrifuge.LeaveEvent)
	OnMessage(*centrifuge.Client, centrifuge.MessageEvent)
	OnPublish(*centrifuge.Subscription, centrifuge.PublishEvent)
	OnServerJoin(*centrifuge.Client, centrifuge.ServerJoinEvent)
	OnServerLeave(*centrifuge.Client, centrifuge.ServerLeaveEvent)
	OnServerPublish(*centrifuge.Client, centrifuge.ServerPublishEvent)
	OnServerSubscribe(*centrifuge.Client, centrifuge.ServerSubscribeEvent)
	OnServerUnsubscribe(*centrifuge.Client, centrifuge.ServerUnsubscribeEvent)
	OnSubscribeError(*centrifuge.Subscription, centrifuge.SubscribeErrorEvent)
	OnSubscribeSuccess(*centrifuge.Subscription, centrifuge.SubscribeSuccessEvent)
	OnUnsubscribe(*centrifuge.Subscription, centrifuge.UnsubscribeEvent)
}

SocketHandler describe the interface

type StatusResponse added in v0.5.0

type StatusResponse struct {
	Payload      string          `json:"payload"`
	ProviderID   string          `json:"providerId"`
	ProviderName string          `json:"providerName"`
	PublicKey    string          `json:"publicKey"`
	Signature    string          `json:"signature"`
	Status       *MerchantStatus `json:"status"`
}

StatusResponse is the response from requesting a status update

type SubmissionResponse added in v0.5.0

type SubmissionResponse struct {
	Error        *MerchantError    `json:"error"`
	Payload      string            `json:"payload"`
	ProviderID   string            `json:"providerId"`
	ProviderName string            `json:"providerName"`
	PublicKey    string            `json:"publicKey"`
	Response     *MerchantResponse `json:"response"`
	Signature    string            `json:"signature"`
}

SubmissionResponse is the response from submitting a tx via Merchant API

type TransactionService added in v0.9.1

type TransactionService interface {
	BroadcastTx(ctx context.Context, txHex string) (txID string, err error)
	BulkBroadcastTx(ctx context.Context, rawTxs []string, feedback bool) (response *BulkBroadcastResponse, err error)
	BulkRawTransactionDataProcessor(ctx context.Context, hashes *TxHashes) (txList TxList, err error)
	BulkTransactionDetails(ctx context.Context, hashes *TxHashes) (txList TxList, err error)
	BulkTransactionDetailsProcessor(ctx context.Context, hashes *TxHashes) (txList TxList, err error)
	BulkUnspentTransactions(ctx context.Context, list *AddressList) (response BulkUnspentResponse, err error)
	BulkUnspentTransactionsProcessor(ctx context.Context, list *AddressList) (response BulkUnspentResponse, err error)
	DecodeTransaction(ctx context.Context, txHex string) (txInfo *TxInfo, err error)
	GetMerkleProof(ctx context.Context, hash string) (merkleResults MerkleResults, err error)
	GetMerkleProofTSC(ctx context.Context, hash string) (merkleResults MerkleTSCResults, err error)
	GetRawTransactionData(ctx context.Context, hash string) (string, error)
	GetRawTransactionOutputData(ctx context.Context, hash string, vOutIndex int) (string, error)
	GetTxByHash(ctx context.Context, hash string) (txInfo *TxInfo, err error)
}

TransactionService is the WhatsOnChain transaction related requests

type TxHashes added in v0.2.2

type TxHashes struct {
	TxIDs []string `json:"txids"`
}

TxHashes is the list of tx hashes for the post request

type TxInfo

type TxInfo struct {
	BlockHash     string     `json:"blockhash"`
	BlockHeight   int64      `json:"blockheight"`
	BlockTime     int64      `json:"blocktime"`
	Confirmations int64      `json:"confirmations"`
	Hash          string     `json:"hash"`
	Hex           string     `json:"hex"`
	LockTime      int64      `json:"locktime"`
	Size          int64      `json:"size"`
	Time          int64      `json:"time"`
	TxID          string     `json:"txid"`
	Version       int64      `json:"version"`
	Vin           []VinInfo  `json:"vin"`
	Vout          []VoutInfo `json:"vout"`
}

TxInfo is the response info about a returned tx

type TxList added in v0.2.2

type TxList []*TxInfo

TxList is the list of tx info structs returned from the /txs post response

type VinInfo

type VinInfo struct {
	Coinbase  string        `json:"coinbase"`
	ScriptSig ScriptSigInfo `json:"scriptSig"`
	Sequence  int64         `json:"sequence"`
	TxID      string        `json:"txid"`
	Vout      int64         `json:"vout"`
}

VinInfo is the vin info inside the CoinbaseTxInfo

type VoutInfo

type VoutInfo struct {
	N            int64            `json:"n"`
	ScriptPubKey ScriptPubKeyInfo `json:"scriptPubKey"`
	Value        float64          `json:"value"`
}

VoutInfo is the vout info inside the CoinbaseTxInfo

type WebsocketService added in v0.10.0

type WebsocketService interface {
	NewMempoolWebsocket(handler SocketHandler) *centrifuge.Client
	NewBlockHeadersWebsocket(handler SocketHandler) *centrifuge.Client
}

WebsocketService is the WhatsOnCHain websocket related clients

Jump to

Keyboard shortcuts

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