bitgo

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2018 License: MIT Imports: 7 Imported by: 0

README

Go client for BitGo.com API v2

Documentation Go Report Card Travis CI

This is unofficial API client. There are no plans to implement all resources.

Consolidate Wallet Unspents

This API call will consolidate Bitcoin Cash of 585951a5df8380e0e3063e9f wallet using max 0.001 BCH unspents with 5000 satoshis/kb fee rate. You can stop consolidation by cancelling a ctx context.

c := bitgo.NewClient(
	bitgo.WithCoin("bch"),
	bitgo.WithAccesToken("swordfish"),
)
tx, err := c.Wallet.Consolidate(ctx, "585951a5df8380e0e3063e9f", &bitgo.WalletConsolidateParams{
	WalletPassphrase: "root",
	MaxValue:         100000,
	FeeRate:          5000,
})
if err != nil {
	log.Fatalf("Failed to coalesce unspents: %v", err)
}
fmt.Printf("Consolidated transaction ID: %s", tx.TxID)

There is a CLI program to consolidate unspensts of a wallet.

$ go build ./cmd/consolidate/
$ ./consolidate -token=swordfish -coin=bch -wallet=585951a5df8380e0e3063e9f -passphrase=root -max-value=0.001 -fee-rate=5000
5885a7e6c7802206f69655ed763d14f101cf46501aef38e275c67c72cfcedb75

Also you can perform periodic consolidation with consolidated just like you would do with consolidate program. In this example consolidation runs every 12 hours.

$ go build ./cmd/consolidated/
$ ./consolidated -schedule=12h -token=swordfish -coin=bch -wallet=585951a5df8380e0e3063e9f -passphrase=root -max-value=0.001 -fee-rate=5000
5885a7e6c7802206f69655ed763d14f101cf46501aef38e275c67c72cfcedb75

List Wallet Unspents

This API call will retrieve the unspent transaction outputs (UTXOs) within a wallet. For example, we want to request 58ae81a5df8380e0e307e876 wallet's confirmed unspents and print amounts in BTC. You can stop pagination by cancelling a ctx context.

c := bitgo.NewClient(
	bitgo.WithCoin("bch"),
	bitgo.WithAccesToken("swordfish"),
)
params := url.Values{}
params.Set("minConfirms", "1")
err := c.Wallet.Unspents(ctx, "58ae81a5df8380e0e307e876", params, func(list *bitgo.UnspentList) {
	for _, utxo := range list.Unspents {
		fmt.Printf("%0.8f\n", toBitcoins(utxo.Value))
	}
})

There is a CLI program to list all unspensts of a wallet.

$ go build ./cmd/utxo/
$ ./utxo -token=swordfish -coin=bch -wallet=58ae81a5df8380e0e307e876 -min-confirms=1
0.00000117
0.00000001
0.00000001
0.00000562
0.00000001
0.00000562

You can use it to get a rough idea about unspents available in the wallet.

$ ./utxo -token=swordfish -coin=bch -wallet=58ae81a5df8380e0e307e876 > unspents.txt
$ sort unspents.txt | uniq -c | sort -n -r
   3 0.00000001
   2 0.00000562
   1 0.00000117

Error Handling

Dave Cheney recommends asserting errors for behaviour, not type.

package main

import (
	"fmt"

	"github.com/marselester/bitgo-v2"
	"github.com/pkg/errors"
)

// IsUnauthorized returns true if err caused by authentication problem.
func IsUnauthorized(err error) bool {
	e, ok := errors.Cause(err).(interface {
		IsUnauthorized() bool
	})
	return ok && e.IsUnauthorized()
}

func main() {
	err := bitgo.Error{Type: bitgo.ErrorTypeAuthentication}
	fmt.Println(IsUnauthorized(err))
	fmt.Println(IsUnauthorized(fmt.Errorf("")))
	fmt.Println(IsUnauthorized(nil))
	// Output: true
	// false
	// false
}

Testing

Quick tutorial on how to fuzz by Damian Gryski. Copy JSON files from testdata into workdir/corpus as sample inputs.

$ go-fuzz-build github.com/marselester/bitgo-v2
$ go-fuzz -bin=bitgo-fuzz.zip -workdir=workdir

Documentation

Overview

Package bitgo is a client for BitGo API v2.

Index

Constants

View Source
const (
	// ErrorTypeRequiresApproval indicates that request is accepted but requires approval.
	ErrorTypeRequiresApproval = "requires_approval"
	// ErrorTypeInvalidRequest errors arise when a request has invalid parameters.
	ErrorTypeInvalidRequest = "invalid_request_error"
	// ErrorTypeAuthentication is returned when a request is not authenticated.
	ErrorTypeAuthentication = "authentication_error"
	// ErrorTypeNotFound is returned when API resource is not found.
	ErrorTypeNotFound = "not_found"
	// ErrorTypeRateLimit indicates too many requests hit the API too quickly.
	ErrorTypeRateLimit = "rate_limit_error"
	// ErrorTypeAPI covers temporary problems with BitGo's API (50x status codes).
	ErrorTypeAPI = "api_error"
)

The error types are based on HTTP status codes.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	Wallet *walletService
	// contains filtered or unexported fields
}

Client manages communication with the BitGo REST-ful API.

func NewClient

func NewClient(options ...ConfigOption) *Client

NewClient returns a Client which can be configured with config options. By default requests are sent to https://www.bitgo.com, currency is "btc", and logs are discarded.

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error)

Do uses Client's HTTP client to execute the Request and unmarshals the Response into v. It also handles unmarshaling errors returned by the API.

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, method, path string, queryParams url.Values, bodyParams interface{}) (*http.Request, error)

NewRequest creates Request to access BitGo API. API path must not start or end with slash. Query string params are optional. If specified, the value pointed to by body is JSON encoded and included as the request body.

type Config

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

Config configures a Client. Config is set by the ConfigOption values passed to NewClient.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption configures how we set up the Client.

func WithAccesToken

func WithAccesToken(token string) ConfigOption

WithAccesToken sets access token to authenticate API requests.

func WithBaseURL

func WithBaseURL(baseURL string) ConfigOption

WithBaseURL configures Client to use BitGo API domain. Usually it's a URL where your BitGo Express REST-ful API service runs.

func WithCoin

func WithCoin(coin string) ConfigOption

WithCoin configures Client to use digital currency (default is "btc"). Full list of supported currencies https://www.bitgo.com/api/v2/?shell#coin-digital-currency-support.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ConfigOption

WithHTTPClient sets Client's underlying HTTP Client.

func WithLogger

func WithLogger(l Logger) ConfigOption

WithLogger configures a logger to debug API responses.

type Error

type Error struct {
	// Type is an API error type based on HTTP status code.
	Type           string
	HTTPStatusCode int
	// Body is the raw response returned by the server.
	Body      string
	Message   string `json:"error"`
	RequestID string `json:"requestId"`
}

Error is the response returned when a call is unsuccessful.

func (Error) Error

func (e Error) Error() string

func (Error) IsApprovalRequired

func (e Error) IsApprovalRequired() bool

IsApprovalRequired returns true if err indicates that request is accepted but requires approval.

func (Error) IsInvalidRequest

func (e Error) IsInvalidRequest() bool

IsInvalidRequest returns true if err caused by invalid request parameters.

func (Error) IsNotFound

func (e Error) IsNotFound() bool

IsNotFound returns true if err indicates that API resource is not found.

func (Error) IsRateLimited

func (e Error) IsRateLimited() bool

IsRateLimited returns true if err caused by API requests throttling.

func (Error) IsTemporary

func (e Error) IsTemporary() bool

IsTemporary returns true if err is temporary API error (50x status codes).

func (Error) IsUnauthorized

func (e Error) IsUnauthorized() bool

IsUnauthorized returns true if err caused by authentication problem.

type ListMeta

type ListMeta struct {
	// Can be used to iterate the next batch of results.
	NextBatchPrevID string
	// The digital currency of the unspents.
	Coin string
}

ListMeta is a pagination metadata.

type Logger

type Logger interface {
	Log(keyvals ...interface{}) error
}

Logger is the Go kit's interface which is mainly used here to debug API responses. Log creates a log event from keyvals, a variadic sequence of alternating keys and values. Implementations must be safe for concurrent use by multiple goroutines. In particular, any implementation of Logger that appends to keyvals or modifies or retains any of its elements must make a copy first.

There is "Standard logger interface" discussion https://github.com/go-commons/commons/issues/1 where the consensus is to emit events instead of logging in the library. There is no design doc yet https://github.com/go-commons/event/issues/1 at the time of writing. Anyhow I needed to debug API responses and decided to use Logger interface for structured logs from https://github.com/go-kit/kit project.

type LoggerFunc

type LoggerFunc func(...interface{}) error

LoggerFunc is an adapter to allow use of ordinary functions as Loggers. If f is a function with the appropriate signature, LoggerFunc(f) is a Logger object that calls f.

func (LoggerFunc) Log

func (f LoggerFunc) Log(keyvals ...interface{}) error

Log implements Logger by calling f(keyvals...).

type NoopLogger

type NoopLogger struct{}

NoopLogger provides a logger that discards logs.

func (*NoopLogger) Log

func (l *NoopLogger) Log(_ ...interface{}) error

Log implements no-op Logger.

type TxInfo

type TxInfo struct {
	// TxID is an id of the transaction.
	TxID string `json:"txid"`
	// Tx is the serialized transaction.
	Tx string `json:"tx"`
	// Status if the transaction was signed.
	Status string `json:"status"`
}

TxInfo is a response we get from consolidateunspents API endpoint.

type Unspent

type Unspent struct {
	// The outpoint of the unspent (txid:vout). For example, "952ac7fd9c1a5df8380e0e305fac8b42db:0".
	ID string
	// The address that owns this unspent.
	Address string
	// Value of the unspent in satoshis.
	Value int64
	// The height of the block that created this unspent.
	BlockHeight int64
	// The date the unspent was created.
	Date string
	// The id of the wallet the unspent is in.
	Wallet string
	// The id of the wallet the unspent came from (if it was sent from a BitGo wallet you're a member on)
	FromWallet string
	// The address type and derivation path of the unspent
	// (0 = normal unspent, 1 = change unspent, 10 = segwit unspent, 11 = segwit change unspent).
	Chain int
	// The position of the address in this chain's derivation path.
	Index int
	// The script defining the criteria to be satisfied to spend this unspent.
	RedeemScript string
	// A flag indicating whether this is a segwit unspent.
	IsSegwit bool
}

Unspent is an unspent transaction output (UTXO).

type UnspentList

type UnspentList struct {
	ListMeta
	Unspents []Unspent `json:"unspents"`
}

UnspentList is a list of unspents as retrieved from unspents endpoint.

type WalletConsolidateParams

type WalletConsolidateParams struct {
	// Passphrase to decrypt the wallet's private key.
	WalletPassphrase string `json:"walletPassphrase,omitempty"`
	// Number of outputs created by the consolidation transaction (defaults to 1).
	NumUnspentsToMake int `json:"numUnspentsToMake,omitempty"`
	// Number of unspents to select (defaults to 25, max is 200).
	Limit int `json:"limit,omitempty"`
	// Ignore unspents smaller than this amount of satoshis.
	MinValue int64 `json:"minValue,omitempty"`
	// Ignore unspents larger than this amount of satoshis.
	MaxValue int64 `json:"maxValue,omitempty"`
	// The minimum height of unspents on the block chain to use.
	MinHeight int `json:"minHeight,omitempty"`
	// The desired fee rate for the transaction in satoshis/KB.
	FeeRate int `json:"feeRate,omitempty"`
	// Fee rate is automatically chosen by targeting a transaction confirmation
	// in this number of blocks (only available on BTC, FeeRate takes precedence if also set).
	FeeTxConfirmTarget int `json:"feeTxConfirmTarget,omitempty"`
	// Maximum percentage of an unspent's value to be used for fees. Cannot be combined with MinValue.
	MaxFeePercentage int `json:"maxFeePercentage,omitempty"`
	// The required number of confirmations for each transaction input.
	MinConfirms int `json:"minConfirms,omitempty"`
	// Apply the required confirmations set in MinConfirms for change outputs.
	EnforceMinConfirmsForChange bool `json:"enforceMinConfirmsForChange,omitempty"`
}

WalletConsolidateParams represents API parameters used when coalescing UTXOs. For more details, see https://www.bitgo.com/api/v2/#consolidate-wallet-unspents.

Directories

Path Synopsis
cmd
consolidate
Consolidate the unspents currently held in a wallet to a smaller number.
Consolidate the unspents currently held in a wallet to a smaller number.
consolidated
Consolidated periodically consolidates the unspents currently held in a wallet to a smaller number, just like consolidate command, but with a schedule.
Consolidated periodically consolidates the unspents currently held in a wallet to a smaller number, just like consolidate command, but with a schedule.
utxo
List bitcoin unspent transaction outputs (UTXOs).
List bitcoin unspent transaction outputs (UTXOs).

Jump to

Keyboard shortcuts

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