bitindex

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2019 License: MIT Imports: 14 Imported by: 0

README

go-bitindex

go-bitindex is the unofficial golang implementation for the BitIndex API

Build Status Report Codacy Badge Release standard-readme compliant GoDoc

Table of Contents

Installation

go-bitindex requires a supported release of Go and dep.

$ go get -u github.com/mrz1836/go-bitindex

Updating dependencies in go-bitindex:

$ cd ../go-bitindex
$ dep ensure -update -v

Documentation

You can view the generated documentation here.

You can also view the BitIndex api documentation.

Features
  • Client is completely configurable
  • Customize User Agent per request
  • Customize the network per request (main, test or stn)
  • Using heimdall http client with exponential backoff & more
  • Current coverage for the BitIndex API
    • Address
    • Block
    • Chain Info
    • Transaction
    • Webhooks
    • Xpub

Examples & Tests

All unit tests and examples run via Travis CI and uses Go version 1.13.x. View the deployment configuration file.

Examples & Tests by API section:

Run all tests (including integration tests)

$ cd ../go-bitindex
$ go test ./... -v

Run tests (excluding integration tests)

$ cd ../go-bitindex
$ go test ./... -v -test.short

Benchmarks

Run the Go benchmarks:

$ cd ../go-bitindex
$ go test -bench . -benchmem

Code Standards

Read more about this Go project's code standards.

Usage

Basic implementation:

package main

import (
	"log"

	"github.com/mrz1836/go-bitindex"
)

func main() {

	// Create a new client
	client, _ := bitindex.NewClient("your-secret-api-key")

	// Get balance for an address
	info, _ := client.AddressInfo("16ZqP5Tb22KJuvSAbjNkoiZs13mmRmexZA")

	// What's the balance?
	log.Println("address balance:", info.Balance)
}

Maintainers

@MrZ

Contributing

View the contributing guidelines and follow the code of conduct.

Support the development of this project 🙏

Donate

Credits

@Attila & BitIndex for their hard work on the BitIndex API

Looking for a Javascript version? Check out the BitIndex JS SDK

License

License

Documentation

Overview

Package bitindex is the unofficial golang implementation for the bitindex API

Example:

// Create a new client client, _ := bitindex.NewClient("your-secret-api-key")

// Get balance for an address info, _ := client.AddressInfo("16ZqP5Tb22KJuvSAbjNkoiZs13mmRmexZA")

// What's the balance? log.Println("address balance:", info.Balance)

Index

Examples

Constants

View Source
const (
	// APIEndpoint is where we POST queries to
	APIEndpoint string = "https://api.bitindex.network/api/v3/"

	// 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"

	// ConnectionExponentFactor backoff exponent factor
	ConnectionExponentFactor float64 = 2.0

	// ConnectionInitialTimeout initial timeout
	ConnectionInitialTimeout = 2 * time.Millisecond

	// ConnectionMaximumJitterInterval jitter interval
	ConnectionMaximumJitterInterval = 2 * time.Millisecond

	// ConnectionMaxTimeout max timeout
	ConnectionMaxTimeout = 1000 * time.Millisecond

	// ConnectionRetryCount retry count
	ConnectionRetryCount int = 3

	// ConnectionWithHTTPTimeout with http timeout
	ConnectionWithHTTPTimeout = 1 * time.Second

	// ConnectionTLSHandshakeTimeout tls handshake timeout
	ConnectionTLSHandshakeTimeout = 5 * time.Second

	// ConnectionMaxIdleConnections max idle http connections
	ConnectionMaxIdleConnections int = 128

	// ConnectionIdleTimeout idle connection timeout
	ConnectionIdleTimeout = 30 * time.Second

	// ConnectionExpectContinueTimeout expect continue timeout
	ConnectionExpectContinueTimeout = 3 * time.Second

	// ConnectionDialerTimeout dialer timeout
	ConnectionDialerTimeout = 5 * time.Second

	// ConnectionDialerKeepAlive keep alive
	ConnectionDialerKeepAlive = 30 * time.Second

	// DefaultUserAgent is the default user agent for all requests
	DefaultUserAgent string = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36"
)

Package global constants and configuration

Variables

View Source
var (

	// ClientDefaultTransport is the default transport struct for the HTTP client
	ClientDefaultTransport = &http.Transport{
		DialContext:           _Dialer.DialContext,
		ExpectContinueTimeout: ConnectionExpectContinueTimeout,
		IdleConnTimeout:       ConnectionIdleTimeout,
		MaxIdleConns:          ConnectionMaxIdleConnections,
		Proxy:                 http.ProxyFromEnvironment,
		TLSHandshakeTimeout:   ConnectionTLSHandshakeTimeout,
	}
)

HTTP and Dialer connection variables

Functions

This section is empty.

Types

type APIErrorResponse

type APIErrorResponse struct {
	Errors  []string           `json:"errors,omitempty"`
	Message nestedErrorMessage `json:"message,omitempty"`
}

APIErrorResponse is from bitindex (broadcast related errors)

type APIInternalError

type APIInternalError struct {
	Errors       []string `json:"errors,omitempty"`
	ErrorMessage string   `json:"message,omitempty"`
	ErrorName    string   `json:"name,omitempty"`
}

APIInternalError is for internal server errors (most requests)

type AddressInfo

type AddressInfo struct {
	APIInternalError
	Address                    string   `json:"addrStr"`
	Balance                    float64  `json:"balance"`
	BalanceSatoshis            int64    `json:"balanceSat"`
	TotalReceived              float64  `json:"totalReceived"`
	TotalReceivedSatoshis      int64    `json:"totalReceivedSat"`
	TotalSent                  float64  `json:"totalSent"`
	TotalSentSatoshis          int64    `json:"totalSentSat"`
	Transactions               []string `json:"transactions"`
	TxAppearances              int64    `json:"txApperances"`
	UnconfirmedBalance         float64  `json:"unconfirmedBalance"`
	UnconfirmedBalanceSatoshis int64    `json:"unconfirmedBalanceSat"`
	UnconfirmedTxAppearances   int64    `json:"unconfirmedTxApperances"`
}

AddressInfo is the address info for a returned address request

type BlockHashByHeightResponse

type BlockHashByHeightResponse struct {
	APIInternalError
	BlockHash string `json:"blockHash"`
}

BlockHashByHeightResponse response struct for block hash by height request

type BlockHeaderResponse

type BlockHeaderResponse struct {
	APIInternalError
	Bits              string  `json:"bits"`
	ChainWork         string  `json:"chainwork"`
	Confirmations     int64   `json:"confirmations"`
	Difficulty        float64 `json:"difficulty"`
	Hash              string  `json:"hash"`
	Height            int64   `json:"height"`
	MedianTime        int64   `json:"mediantime"`
	MerkleRoot        string  `json:"merkleroot"`
	NextBlockHash     string  `json:"nextblockhash"`
	Nonce             int64   `json:"nonce"`
	PreviousBlockHash string  `json:"previousblockhash"`
	Time              int64   `json:"time"`
	Version           int     `json:"version"`
	VersionHex        string  `json:"versionHex"`
}

BlockHeaderResponse is the block header response

type BlockRawResponse

type BlockRawResponse struct {
	APIInternalError
	RawBlock string `json:"rawblock"`
}

BlockRawResponse response struct for raw block request

type BlockResponse

type BlockResponse struct {
	APIInternalError
	Bits              string   `json:"bits"`
	ChainWork         string   `json:"chainwork"`
	Confirmations     int64    `json:"confirmations"`
	Difficulty        float64  `json:"difficulty"`
	Hash              string   `json:"hash"`
	Height            int64    `json:"height"`
	MedianTime        int64    `json:"mediantime"`
	MerkleRoot        string   `json:"merkleroot"`
	NextBlockHash     string   `json:"nextblockhash"`
	Nonce             int64    `json:"nonce"`
	PreviousBlockHash string   `json:"previousblockhash"`
	Size              int64    `json:"size"`
	Time              int64    `json:"time"`
	Tx                []string `json:"tx"`
	Version           int      `json:"version"`
	VersionHex        string   `json:"versionHex"`
}

BlockResponse is the block response

type ChainBestBlockHashResponse

type ChainBestBlockHashResponse struct {
	BestBlockHash string `json:"bestblockhash"`
}

ChainBestBlockHashResponse response struct for best block hash request

type ChainDifficultyResponse

type ChainDifficultyResponse struct {
	Difficulty float64 `json:"difficulty"`
}

ChainDifficultyResponse response struct for chain difficulty request

type ChainInfoResponse

type ChainInfoResponse struct {
	Info chainInfo `json:"info"`
}

ChainInfoResponse response struct for chain info request

type ChainLastBlockHashResponse

type ChainLastBlockHashResponse struct {
	LastBlockHash string `json:"lastblockhash"`
	SyncTipHash   string `json:"syncTipHash"`
}

ChainLastBlockHashResponse response struct for last block hash request

type Client

type Client struct {

	// HTTPClient carries out the POST operations
	HTTPClient heimdall.Client

	// Parameters contains the search parameters that are submitted with your query,
	// which may affect the data returned
	Parameters *RequestParameters

	// LastRequest is the raw information from the last request
	LastRequest *LastRequest
}

Client holds client configuration settings

func NewClient

func NewClient(apiKey string) (c *Client, err error)

NewClient creates a new client to submit queries with. Parameters values are set to the defaults defined by the API documentation.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Authentication

Example

ExampleNewClient example using NewClient()

client, _ := NewClient(testAPIKey)
fmt.Println(client.Parameters.Network)
Output:
main

func (*Client) AddMonitoredAddresses

func (c *Client) AddMonitoredAddresses(addAddresses *MonitoredAddresses) (addresses MonitoredAddresses, err error)

AddMonitoredAddresses this endpoint takes new addresses and adds to monitor.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Webhook

func (*Client) AddressInfo

func (c *Client) AddressInfo(address string) (addressInfo *AddressInfo, err error)

AddressInfo this endpoint retrieves various address info.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Address

func (*Client) AddressUnspentTransactions

func (c *Client) AddressUnspentTransactions(address string) (transactions UnspentTransactions, err error)

AddressUnspentTransactions this endpoint retrieves list of UTXOs.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Address

func (*Client) ChainBestBlockHash

func (c *Client) ChainBestBlockHash() (bestBlockHash *ChainBestBlockHashResponse, err error)

ChainBestBlockHash this endpoint retrieves the current best block hash

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#ChainInfo

func (*Client) ChainDifficulty

func (c *Client) ChainDifficulty() (difficulty *ChainDifficultyResponse, err error)

ChainDifficulty this endpoint retrieves the current chain difficulty.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#ChainInfo

func (*Client) ChainInfo

func (c *Client) ChainInfo() (chainInfo *ChainInfoResponse, err error)

ChainInfo this endpoint retrieves the current chain info.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#ChainInfo

func (*Client) ChainLastBlockHash

func (c *Client) ChainLastBlockHash() (lastBlockHash *ChainLastBlockHashResponse, err error)

ChainLastBlockHash this endpoint retrieves the last block hash

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#ChainInfo

func (*Client) GetBlock

func (c *Client) GetBlock(hash string) (block *BlockResponse, err error)

GetBlock this endpoint retrieves the block by hash.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Block

func (*Client) GetBlockHashByHeight

func (c *Client) GetBlockHashByHeight(height int64) (blockHash *BlockHashByHeightResponse, err error)

GetBlockHashByHeight this endpoint retrieves the block hash by height.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Block

func (*Client) GetBlockHeader

func (c *Client) GetBlockHeader(hash string) (blockHeader *BlockHeaderResponse, err error)

GetBlockHeader this endpoint retrieves the block header by hash.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Block

func (*Client) GetBlockRaw

func (c *Client) GetBlockRaw(hash string) (rawBlock *BlockRawResponse, err error)

GetBlockRaw this endpoint retrieves the raw block by hash.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Block

func (*Client) GetMonitoredAddresses

func (c *Client) GetMonitoredAddresses() (addresses MonitoredAddresses, err error)

GetMonitoredAddresses this endpoint retrieves all the addresses being monitored by that API key.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Webhook

func (*Client) GetTransaction

func (c *Client) GetTransaction(txID string) (transaction *Transaction, err error)

GetTransaction this endpoint retrieves the transaction info.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Transactions

func (*Client) GetTransactionRaw

func (c *Client) GetTransactionRaw(txID string) (rawTx *TransactionRaw, err error)

GetTransactionRaw this endpoint retrieves the transaction in raw format.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Transactions

func (*Client) GetTransactions

func (c *Client) GetTransactions(transactionRequest *GetTransactionsRequest) (response *GetTransactionsResponse, err error)

GetTransactions this endpoint retrieves list of transactions.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Address

func (*Client) GetUnspentTransactions

func (c *Client) GetUnspentTransactions(transactionRequest *GetUnspentTransactionsRequest) (transactions UnspentTransactions, err error)

GetUnspentTransactions this endpoint retrieves list of unspent transactions.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Address

func (*Client) GetWebhookConfig

func (c *Client) GetWebhookConfig() (config *WebhookConfigResponse, err error)

GetWebhookConfig this endpoint retrieves the configuration for the existing webhook.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Webhook

func (*Client) GetXpubAddresses

func (c *Client) GetXpubAddresses(xPub string, offset, limit int, order, filterByAddress string) (addresses XpubAddresses, err error)

GetXpubAddresses this endpoint will return addresses for an xpub given the parameters.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Xpub

func (*Client) GetXpubBalance

func (c *Client) GetXpubBalance(xPub string) (balance *XpubBalance, err error)

GetXpubBalance this endpoint that gets the total balance for the xpub.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Xpub

func (*Client) GetXpubNextAddress

func (c *Client) GetXpubNextAddress(xPub string, reserveTimeSeconds int) (addresses XpubAddresses, err error)

GetXpubNextAddress this endpoint that gets the next address for a xpub and reserve if given.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Xpub

func (*Client) GetXpubTransactions

func (c *Client) GetXpubTransactions(xPub string) (transactions XpubAddresses, err error)

GetXpubTransactions this endpoint that gets the the history of transactions for the xpub.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Xpub

func (*Client) GetXpubUnspentTransactions

func (c *Client) GetXpubUnspentTransactions(xPub, sort string) (transactions UnspentTransactions, err error)

GetXpubUnspentTransactions this endpoint retrieves list of unspent transactions for a xpub address.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Xpub

func (*Client) Request

func (c *Client) Request(endpoint string, method string, payload []byte) (response string, err error)

Request is a generic bitindex request wrapper that can be used without constraints

func (*Client) SendTransaction

func (c *Client) SendTransaction(rawTx string) (txID *SendTransactionResponse, err error)

SendTransaction this endpoint broadcasts a raw transaction to the network.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Transactions

func (*Client) UpdateWebhookConfig

func (c *Client) UpdateWebhookConfig(updateConfig *WebhookUpdateConfig) (config *WebhookConfigResponse, err error)

UpdateWebhookConfig this endpoint updates the configuration for the existing webhook.

For more information: https://www.bitindex.network/developers/api-documentation-v3.html#Webhook

type GetTransactionsRequest

type GetTransactionsRequest struct {
	Address        string   `json:"addrs"` // single address or addr1,addr2,addr3
	Addresses      []string `json:"-"`     // (used for multiple)
	AfterBlockHash string   `json:"afterBlockHash,omitempty"`
	AfterHeight    string   `json:"afterHeight,omitempty"`
	FromIndex      int64    `json:"fromIndex,omitempty"`
	IncludeAsm     bool     `json:"includeAsm"`
	IncludeHex     bool     `json:"includeHex"`
	ToIndex        int64    `json:"toIndex,omitempty"`
}

GetTransactionsRequest is for making a POST to get transactions

type GetTransactionsResponse

type GetTransactionsResponse struct {
	APIInternalError
	TotalItems int64         `json:"totalItems"`
	From       int64         `json:"from"`
	To         int64         `json:"to"`
	Items      []Transaction `json:"items"`
}

GetTransactionsResponse is the response from the POST request

type GetUnspentTransactionsRequest

type GetUnspentTransactionsRequest struct {
	Address   string   `json:"addrs"` // single address or addr1,addr2,addr3
	Addresses []string `json:"-"`     // (used for multiple)
	Sort      string   `json:"sort"`  // Format is 'field:asc' such as 'value:desc' to sort by value descending
}

GetUnspentTransactionsRequest is for making the GetUnspentTransactions request

type LastRequest

type LastRequest struct {

	// Method is either POST or GET
	Method string

	// PostData is the post data submitted if POST request
	PostData string

	// StatusCode is the last code from the request
	StatusCode int

	// URL is the url used for the request
	URL string
}

LastRequest is used to track what was submitted to the Request()

type MonitoredAddress

type MonitoredAddress struct {
	Address string `json:"addr"`
}

MonitoredAddress is the address from get monitored addresses

type MonitoredAddresses

type MonitoredAddresses []MonitoredAddress

MonitoredAddresses is the response from get monitored addresses

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 RequestParameters

type RequestParameters struct {

	// UserAgent (optional for changing user agents)
	UserAgent string

	// Network is what this search should use IE: main
	Network NetworkType

	// APIKey is the api key to use
	APIKey string
}

RequestParameters holds options that can affect data returned by a request.

type SendTransactionResponse

type SendTransactionResponse struct {
	APIErrorResponse
	TxID string `json:"txid"`
}

SendTransactionResponse is the response for the request

type Transaction

type Transaction struct {
	APIInternalError
	BlockHash     string       `json:"blockhash"`
	BlockHeight   int64        `json:"blockheight"`
	BlockTime     int64        `json:"blocktime"`
	Confirmations int64        `json:"confirmations"`
	Fees          float64      `json:"fees"`
	Hash          string       `json:"hash"`
	LockTime      int64        `json:"locktime"`
	RawTx         string       `json:"rawtx"`
	Size          int64        `json:"size"`
	Time          int64        `json:"time"`
	TxID          string       `json:"txid"`
	ValueIn       float64      `json:"valueIn"`
	ValueOut      float64      `json:"valueOut"`
	Version       int          `json:"version"`
	Vin           []vinObject  `json:"vin"`
	Vout          []voutObject `json:"vout"`
}

Transaction is returned in the GetTransactionsResponse

type TransactionRaw

type TransactionRaw struct {
	APIInternalError
	RawTx string `json:"rawtx"`
}

TransactionRaw is the response for the raw tx request

type UnspentTransaction

type UnspentTransaction struct {
	Address       string  `json:"address"`
	Amount        float64 `json:"amount"`
	Chain         int     `json:"chain"`
	Confirmations int64   `json:"confirmations"`
	Height        int64   `json:"height"`
	Num           int     `json:"num"`
	OutputIndex   int64   `json:"outputIndex"`
	Path          string  `json:"path"`
	Satoshis      int64   `json:"satoshis"`
	Script        string  `json:"script"`
	ScriptPubKey  string  `json:"scriptPubKey"`
	TxID          string  `json:"txid"`
	Value         int64   `json:"value"`
	Vout          int     `json:"vout"`
}

UnspentTransaction is a standard UTXO response Also has some fields for xpub data (chain, num, path)

type UnspentTransactions

type UnspentTransactions []UnspentTransaction

UnspentTransactions is a list of unspent transactions

type WebhookConfigResponse

type WebhookConfigResponse struct {
	APIInternalError
	Enabled bool   `json:"enabled"`
	ID      string `json:"id"`
	Secret  string `json:"secret"`
	URL     string `json:"url"`
}

WebhookConfigResponse is the response from get config

type WebhookUpdateConfig

type WebhookUpdateConfig struct {
	Enabled bool   `json:"enabled"`
	Secret  string `json:"secret,omitempty"`
	URL     string `json:"url,omitempty"`
}

WebhookUpdateConfig is for updating a webhook config

type XPubAddress

type XPubAddress struct {
	Address string `json:"address"`
	Chain   int    `json:"chain"`
	Height  int64  `json:"height"`
	Num     int    `json:"num"`
	Path    string `json:"path"`
	TxID    string `json:"txid"`
}

XPubAddress is an address returned from xpub requests

type XpubAddresses

type XpubAddresses []XPubAddress

XpubAddresses is the list of next addresses

type XpubBalance

type XpubBalance struct {
	APIInternalError
	Confirmed   int64 `json:"confirmed"`
	UnConfirmed int64 `json:"unconfirmed"`
}

XpubBalance is the balance returned for a xpub address

Directories

Path Synopsis
Package main is an example package that uses go-bitindex
Package main is an example package that uses go-bitindex

Jump to

Keyboard shortcuts

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