nownodes

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 5, 2023 License: MIT Imports: 15 Imported by: 1

README

go-nownodes

The unofficial golang implementation for the NOWNodes.io API

Release Build Status Report codecov Mergify Status Go
Gitpod Ready-to-Code standard-readme compliant Makefile Included Sponsor Donate


Table of Contents


Installation

go-nownodes requires a supported release of Go.

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

Documentation

View the generated documentation

GoDoc

Features

Repository Features

This repository was created using MrZ's go-template

Built-in Features
Package Dependencies
Library Deployment

Releases are automatically created when you create a new git tag!

If you want to manually make releases, please install GoReleaser:

goreleaser for easy binary or library deployment to GitHub and can be installed:

  • using make: make install-releaser
  • using brew: brew install goreleaser

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


Automatic releases via GitHub Actions from creating a new tag:

make tag version=1.2.3

Manual Releases (optional)

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


Makefile Commands

View all makefile commands

make help

List of all current commands:

all                           Runs multiple commands
clean                         Remove previous builds and any cached 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-all-contributors      Installs all contributors locally
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-contributors           Regenerates the contributors html/list
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

Checkout all the examples!


Contributing

View the contributing guidelines and 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


Contributors ✨

Thank you to these wonderful people (emoji key):


Mr. Z

🚇 💻 🚧 🛡️

This project follows the all-contributors specification.


License

License

Documentation

Overview

Package nownodes is the unofficial golang implementation for the nownodes.io API

If you have any suggestions or comments, please feel free to open an issue on this GitHub repository!

By MrZ (https://github.com/mrz1836)

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidAddress = errors.New("missing or invalid address")

ErrInvalidAddress is when the address is missing or invalid

View Source
var ErrInvalidTxHex = errors.New("missing or invalid tx hex")

ErrInvalidTxHex is when the tx hex is missing or invalid

View Source
var ErrInvalidTxID = errors.New("missing or invalid tx id")

ErrInvalidTxID is when the tx id is missing or invalid

View Source
var ErrUnsupportedBlockchain = errors.New("unsupported blockchain for this method")

ErrUnsupportedBlockchain is when the given blockchain is not supported by the method

Functions

This section is empty.

Types

type AddressInfo added in v0.0.2

type AddressInfo struct {
	Address            string   `json:"address"`
	Balance            string   `json:"balance"`
	ItemsOnPage        uint64   `json:"itemsOnPage"`
	Page               uint64   `json:"page"`
	TotalPages         uint64   `json:"totalPages"`
	TotalReceived      string   `json:"totalReceived"`
	TotalSent          string   `json:"totalSent"`
	TxIDs              []string `json:"txids,omitempty"`
	Txs                uint64   `json:"txs"`
	UnconfirmedBalance string   `json:"unconfirmedBalance"`
	UnconfirmedTxs     uint64   `json:"unconfirmedTxs"`
}

AddressInfo is the address information returned to the GetAddress request

type AddressService added in v0.0.2

type AddressService interface {
	GetAddress(ctx context.Context, chain Blockchain, address string) (*AddressInfo, error)
}

AddressService is the address related requests

type Blockchain

type Blockchain string

Blockchain is the supported blockchain networks

const (
	BCH        Blockchain = blockchainBCH        // BitcoinCash: https://bch.info/
	BSV        Blockchain = blockchainBSV        // BitCoin: https://bitcoinsv.com
	BTC        Blockchain = blockchainBTC        // BitCore: https://bitcoin.org
	BTCTestnet Blockchain = blockchainBTCTestnet // BitCore Testnet: https://bitcoin.org
	BTG        Blockchain = blockchainBTG        // BitGold: https://bitcoingold.org/
	DASH       Blockchain = blockchainDASH       // Dash: https://www.dash.org/
	DOGE       Blockchain = blockchainDOGE       // DogeCoin: https://dogecoin.com/
	LTC        Blockchain = blockchainLTC        // LiteCoin: https://litecoin.org/
	ETH        Blockchain = blockchainETH        // Ethereum: https://ethereum.org/
)

Supported blockchains

func (Blockchain) BlockBookURL

func (n Blockchain) BlockBookURL() string

BlockBookURL is the url for the block book API

func (Blockchain) NodeAPIURL added in v0.0.4

func (n Blockchain) NodeAPIURL() string

NodeAPIURL is the url for the Node API

func (Blockchain) String

func (n Blockchain) String() string

String is the string version of the blockchain

func (Blockchain) ValidateAddress added in v0.0.2

func (n Blockchain) ValidateAddress(address string) bool

ValidateAddress will do basic validations on the address

func (Blockchain) ValidateTxHex added in v0.0.3

func (n Blockchain) ValidateTxHex(txHex string) bool

ValidateTxHex will do basic validations on the tx hex string

func (Blockchain) ValidateTxID added in v0.0.3

func (n Blockchain) ValidateTxID(txID string) bool

ValidateTxID will do basic validations on the tx id string

type BroadcastResult added in v0.0.3

type BroadcastResult struct {
	NodeError
	ID     string `json:"id,omitempty"`     // The unique ID you provided {"result": "15e78db3a6247ca320de2202240f6a4877ea3af338e23bf5ff3e5cbff3763bf6"}
	Result string `json:"result,omitempty"` // The Tx ID {"result": "15e78db3a6247ca320de2202240f6a4877ea3af338e23bf5ff3e5cbff3763bf6"}
}

BroadcastResult is the successful broadcast results

type Client

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

Client is the client configuration and options

func (*Client) GetAddress added in v0.0.2

func (c *Client) GetAddress(ctx context.Context, chain Blockchain, address string) (*AddressInfo, error)

GetAddress will get address information by a given address

This method supports the following chains: BCH, BSV, BTC, BTCTestnet, BTG, DASH, DOGE, LTC

Example
c := NewClient(WithHTTPClient(&validAddressResponse{}))
info, _ := c.GetAddress(context.Background(), BSV, testAddress(BSV))
fmt.Println("address found: " + info.Address)
Output:

address found: 1GenocdBC1NSHLMbk61fqJXqTdXjevCxCL

func (*Client) GetMempoolEntry added in v0.0.4

func (c *Client) GetMempoolEntry(ctx context.Context, chain Blockchain, txID, id string) (*MempoolEntryResult, error)

GetMempoolEntry will get the mempool entry information for a given txID

This method supports the following chains: BSV, BTC, BTCTestnet, BTG, DASH, DOGE, LTC

Example
c := NewClient(WithHTTPClient(&validNodeResponse{}))
info, _ := c.GetMempoolEntry(context.Background(), BSV, testTxID(BSV), testUniqueID)
fmt.Printf("tx in mempool time: %d", info.Result.Time)
Output:

tx in mempool time: 1643661192

func (*Client) GetTransaction

func (c *Client) GetTransaction(ctx context.Context, chain Blockchain, txID string) (*TransactionInfo, error)

GetTransaction will get transaction information by a given TxID

This method supports the following chains: BCH, BSV, BTC, BTCTestnet, BTG, DASH, DOGE, LTC

Example
c := NewClient(WithHTTPClient(&validTxResponse{}))
info, _ := c.GetTransaction(context.Background(), BSV, testTxID(BSV))
fmt.Println("tx found: " + info.TxID)
Output:

tx found: 17961a51337369bf64e45e8410a7ce4cfb0c88b5d883d9e8a939dfdd0f7591fd

func (*Client) HTTPClient

func (c *Client) HTTPClient() HTTPInterface

HTTPClient will return the current HTTP client

func (*Client) SendRawTransaction added in v0.0.4

func (c *Client) SendRawTransaction(ctx context.Context, chain Blockchain, txHex, id string) (*BroadcastResult, error)

SendRawTransaction will submit a broadcast request (POST) with the given tx hex payload

param: id is a unique identifier for your own use This method supports the following chains: BSV, BTC, BTCTestnet, BTG, DASH, DOGE, LTC

Example
c := NewClient(WithHTTPClient(&validNodeResponse{}))
results, _ := c.SendRawTransaction(context.Background(), BSV, testTxHex(BSV), testUniqueID)
fmt.Println("broadcast success: " + results.Result)
Output:

broadcast success: 15e78db3a6247ca320de2202240f6a4877ea3af338e23bf5ff3e5cbff3763bf6

func (*Client) SendTransaction added in v0.0.3

func (c *Client) SendTransaction(ctx context.Context, chain Blockchain, txHex string) (*BroadcastResult, error)

SendTransaction will submit a broadcast request (GET) with the given tx hex payload

NOTE: max hex size of 2000 characters (otherwise it will use SendRawTransaction) This method supports the following chains: BCH, BSV, BTC, BTCTestnet, BTG, DASH, DOGE, LTC

Example
c := NewClient(WithHTTPClient(&validTxResponse{}))
results, _ := c.SendTransaction(context.Background(), BSV, testTxHex(BSV))
fmt.Println("broadcast success: " + results.Result)
Output:

broadcast success: 15e78db3a6247ca320de2202240f6a4877ea3af338e23bf5ff3e5cbff3763bf6

func (*Client) UserAgent

func (c *Client) UserAgent() string

UserAgent will return the current user agent

type ClientInterface

type ClientInterface interface {
	AddressService
	MempoolService
	TransactionService
	HTTPClient() HTTPInterface
	UserAgent() string
}

ClientInterface is the client interface

func NewClient

func NewClient(opts ...ClientOps) ClientInterface

NewClient will make a new client with the provided options

type ClientOps

type ClientOps func(c *ClientOptions)

ClientOps allow functional options to be supplied that overwrite default client options.

func WithAPIKey

func WithAPIKey(apiKey string) ClientOps

WithAPIKey will store the API key on the client for all future requests

func WithHTTPClient

func WithHTTPClient(client HTTPInterface) ClientOps

WithHTTPClient will overwrite the default client with a custom client

func WithHTTPOptions

func WithHTTPOptions(opts *HTTPOptions) ClientOps

WithHTTPOptions will overwrite the default HTTP client options

func WithUserAgent

func WithUserAgent(userAgent string) ClientOps

WithUserAgent will overwrite the default useragent

type ClientOptions

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

ClientOptions holds all the configuration for client requests and default resources

type HTTPInterface

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

HTTPInterface is used for the HTTP client

type HTTPOptions

type HTTPOptions struct {
	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"`
	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"`
}

HTTPOptions holds all the configuration for the HTTP client

func DefaultHTTPOptions

func DefaultHTTPOptions() (clientOptions *HTTPOptions)

DefaultHTTPOptions will return the default HTTP option values

type Input

type Input struct {
	Addresses []string `json:"addresses,omitempty"`
	Coinbase  string   `json:"coinbase,omitempty"`
	Hex       string   `json:"hex,omitempty"`
	IsAddress bool     `json:"isAddress"`
	N         uint64   `json:"n"`
	Sequence  int64    `json:"sequence"`
	TxID      string   `json:"txid,omitempty"`
	Value     string   `json:"value,omitempty"`
	VOut      uint64   `json:"vout"`
}

Input is the transaction input

type MempoolEntry added in v0.0.4

type MempoolEntry struct {
	Depends     []string `json:"depends"`
	Fee         float64  `json:"fee,omitempty"`
	Height      uint64   `json:"height"`
	ModifiedFee float64  `json:"modifiedfee,omitempty"`
	Size        int64    `json:"size,omitempty"`
	Time        int64    `json:"time"`
}

MempoolEntry is the mempool entry

type MempoolEntryResult added in v0.0.4

type MempoolEntryResult struct {
	NodeError               // Error message
	ID        string        `json:"id,omitempty"`     // Your unique ID
	Result    *MempoolEntry `json:"result,omitempty"` // Mempool entry
}

MempoolEntryResult is the mempool entry result

type MempoolService added in v0.0.4

type MempoolService interface {
	GetMempoolEntry(ctx context.Context, chain Blockchain, txID, id string) (*MempoolEntryResult, error)
}

MempoolService is the mempool related requests

type NodeError added in v0.0.4

type NodeError struct {
	Error *nodeAPIError `json:"error,omitempty"` // The error message from NodeAPI requests
}

NodeError is an internal error from the NodeAPI

type Output

type Output struct {
	Addresses []string `json:"addresses,omitempty"`
	Hex       string   `json:"hex,omitempty"`
	IsAddress bool     `json:"isAddress"`
	N         uint64   `json:"n"`
	Spent     bool     `json:"spent"`
	Value     string   `json:"value,omitempty"`
}

Output is the transaction output

type RequestResponse

type RequestResponse struct {
	BodyContents []byte `json:"body_contents"` // Raw body response
	Error        error  `json:"error"`         // If an error occurs
	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 used for the request
}

RequestResponse is the response from a request

type TransactionInfo

type TransactionInfo struct {
	BlockHash     string    `json:"blockHash"`
	BlockHeight   int64     `json:"blockHeight"`
	BlockTime     int64     `json:"blockTime"`
	Confirmations int64     `json:"confirmations"`
	Fees          string    `json:"fees"`
	Hex           string    `json:"hex"`
	LockTime      int64     `json:"lockTime,omitempty"` // BTC
	TxID          string    `json:"txid"`
	Value         string    `json:"value"`
	ValueIn       string    `json:"valueIn"`
	Version       int8      `json:"version"`
	Vin           []*Input  `json:"vin"`
	VOut          []*Output `json:"vout"`
}

TransactionInfo is the transaction information returned to the GetTransaction request

type TransactionService

type TransactionService interface {
	GetTransaction(ctx context.Context, chain Blockchain, txID string) (*TransactionInfo, error)
	SendTransaction(ctx context.Context, chain Blockchain, txHex string) (*BroadcastResult, error)
	SendRawTransaction(ctx context.Context, chain Blockchain, txHex, id string) (*BroadcastResult, error)
}

TransactionService is the transaction related requests

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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