blockwatch

package module
v0.0.0-...-74d3856 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2021 License: MIT Imports: 20 Imported by: 1

README

blockwatch-go – Official Go SDK for the Blockwatch Data API

The official Blockwatch Go client library.

To use this SDK you need a free Blockwatch API key and a free or paid database subscription.

Installation

go get -u blockwatch.cc/blockwatch-go

Then import, using

import (
	"blockwatch.cc/blockwatch-go"
)

Documentation

For a comprehensive coverage of all API features read the Blockwatch Data API documentation.

Below are a few examples on how to use the Go SDK to access the Blockwatch Data API.

Authentication

Authentication for the Blockwatch Data API works by using API keys as secret tokens. You can get your API key by signing up for a free Blockwatch account and then creating your personal API key on your account settings page.

You also need to have an active subscription to the databases you like to query. You will get 404 Not Found errors if you try to access a databases without subscription.

Initializing the Go SDK Client

For convenient access to the Blockwatch Data API, the Go SDK defines a Client that exports all relevant functions. To create a new client object with default configuration call:

c, err := blockwatch.NewClient("MY_API_KEY", nil)

The default configuration should work just fine, but if you need special timeouts, proxy or TLS settings you may specify a separate ConnConfig struct.

type ConnConfig struct {
	// HTTP tuning parameters
	DialTimeout           time.Duration
	KeepAlive             time.Duration
	IdleConnTimeout       time.Duration
	ResponseHeaderTimeout time.Duration
	ExpectContinueTimeout time.Duration
	MaxIdleConns          int

	// Proxy specifies to connect through a SOCKS 5 proxy server.  It may
	// be an empty string if a proxy is not required.
	Proxy string

	// ProxyUser is an optional username to use for the proxy server if it
	// requires authentication.  It has no effect if the Proxy parameter
	// is not set.
	ProxyUser string

	// ProxyPass is an optional password to use for the proxy server if it
	// requires authentication.  It has no effect if the Proxy parameter
	// is not set.
	ProxyPass string

	// TLS configuration options
	ServerName         string
	AllowInsecureCerts bool
	TLSMinVersion      int
	TLSMaxVersion      int
	RootCaCerts        []string
	RootCaCertsFile    string
	ClientCert         []string
	ClientCertFile     string
	ClientKey          []string
	ClientKeyFile      string
}

Listing Databases

To fetch a list of all databases you're currently subscribed to, call

dbs, err := c.ListDatabases(ctx, blockwatch.DatabaseListParams{})

Getting Dataset Information

To get the list of all datasets in a particular database, call

sets, err := c.ListDatasets(ctx, "BTC", blockwatch.DatasetListParams{})

While the above call returns just the code and name of all datasets, you can fetch full details including the list of data fields with

set, err := c.GetDataset(ctx,  "BTC", "BLOCK")

Fetching Dataset Contents

The Blockwatch Data API supports two different kinds of datasets, tables and time-series with slightly different query arguments and semantics. Both contain a matrix of columns and rows which you can access using the same kind of functions.

Time series may contain at most one row of entries per unique timestamp. They have a default sampling frequency, are naturally ordered by timestamp and you may only filter them by time in most cases. You can request a different frequency using the collapse parameter in which case rows will be automatically aggregated by time.

Tables can contain arbitrary data and are ordered by a primary key, in most cases a unique row id. Usually you can filter tables by most of their columns. Please consult the dataset spec for details on which data fields are filterable.

The SDK keeps the raw data response and lazy-unmarshals data rows or columns only when accessed.

Getting Data from Tables
# using default parameters (limit = 500, all columns)
table, err := c.GetTable(ctx, "BTC", "BLOCK", blockwatch.TableParams{})

# with limit and filters
table, err = c.GetTable(ctx, "BTC", "BLOCK", blockwatch.TableParams{
	Limit:   10,
	Columns: "time,height,hash,volume",
	Filter: []*blockwatch.Filter{
		&blockwatch.Filter{
			Field: "height",
			Mode: blockwatch.FilterModeGte,
			Value: "500000",
		},
		blockwatch.NewFilter("volume", blockwatch.FilterModeRange, "10,100"),
	},
})
Getting Time-series Data
# using default parameters (limit = 500, all columns)
series, err := c.GetSeries(ctx, "BITFINEX:OHLCV", "BTC_USD", blockwatch.SeriesParams{})

# get hourly data from the last 24 hours
series, err = c.GetSeries(ctx, "BITFINEX:OHLCV", "BTC_USD", blockwatch.SeriesParams{
	Limit:     24,
	Columns:   "time,open,close,vwap,vol_base",
	Collapse:  blockwatch.CollapseModeOneHour,
	Order:     OrderModeDesc,
	StartDate: time.Now().Add(-24*time.Hour),
	EndDate:   time.Now(),
})

Decoding Data into Structs

To process data row-by-row it is often convenient to extract each row into a Go struct first. We've defined a couple of common structs for Blockwatch market and blockchain databases, but you can also define your own structs. This makes sense if you like to limit the number of struct fields for memory efficiency.

For extraction the SDK uses Go's built-in type reflection and matches column codes to struct field tags. Per default the SDK looks for json struct tags, but you can change that by setting blockwatch.TagName = "mytag".

// assuming you have fetched data from BTC/BLOCK into table
err := table.ForEach(func(r blockwatch.Row) error {
	var block blockwatch.Block

	// decode row into struct fields (uses json struct tags to match column codes)
	if err := r.Decode(&block); err != nil {
		return err
	}

	// handle block data here

	return nil
})

Decoding Columns as Slices

Sometimes it's more efficient to process data in column vectors. To support this mode you may extract an entire column in one step:

// assuming you have fetched data from BTC/BLOCK into table, you may now
// decode each column as slice (Note that an interface to slice is returned)
idx, col, err := table.Column("hash")

// to work with a native slice you'll have to cast the interface to type []<T>;
// either choose a static (i.e. implementation time) approach or a dynamic one

// static (requires you know the type for column 'hash' in advance)
slice, _ := col.([][]byte)

// or dynamic (using the actual column type in a switch statement)
switch table.Columns[idx].Type {
	case blockwatch.FieldTypeString:
		slice, _ := col.([]string)

	case blockwatch.FieldTypeBytes:
		slice, _ := col.([][]byte)

	case blockwatch.FieldTypeDate, blockwatch.FieldTypeDatetime:
		slice, _ := col.([]time.Time)

	case blockwatch.FieldTypeBoolean:
		slice, _ := col.([]bool)

	case blockwatch.FieldTypeFloat64:
		slice, _ := col.([]float64)

	case blockwatch.FieldTypeInt64:
		slice, _ := col.([]int64)

	case blockwatch.FieldTypeUint64:
		slice, _ := col.([]uint64)

	default:
		// handle unsupported column type
}

Cursoring through large result sets

A query can match millions of rows, but for efficiency reasons we limit each result to at most 50,000 rows. A result contains a cursor value that allows you to fetch the next chunk of rows right after the current one in a subsequent query. When a result contains no more data you know that you've reached the end of a table. Because most tables grow in real-time you can also store the latest cursor and poll for new data after a while.

params := blockwatch.TableParams{}

for {
	table, err := blockwatch.GetTable(ctx, "BTC", "BLOCK", params)
	// handle error if necessary

	// handle data here

	// prepare for next iteration
	params.Cursor = table.Cursor
}

Gracefully handling rate-limits

To avoid excessive overload of our API we limit the rate at which we process your requests. This means your program may from time to time run into a rate limit. To let you gracefully handle retries by waiting until a rate limit resets, we expose the deadline and a done channel much like Go's network context does. Here's how you may use this feature:

var (
	table *blockwatch.Table
	err   error
)
for {
	table, err = blockwatch.GetTable(ctx, "BTC", "BLOCK", blockwatch.TableParams{})
	if err != nil {
		if e, ok := blockwatch.IsRateLimited(err); ok {
			fmt.Printf("Rate limited, waiting for %s\n", e.Deadline())
			select {
			case <-ctx.Done():
				// wait until external context is canceled
				err = ctx.Err()
			case <-e.Done():
				// wait until rate limit reset and retry
				continue
			}
		}
	}
	break
}

// handle error and/or result here

License

The MIT License (MIT) Copyright (c) 2020 Blockwatch Data Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Overview

Copyright (c) 2020 Blockwatch Data Inc. Author: alex@blockwatch.cc

Copyright (c) 2020 Blockwatch Data Inc. Author: alex@blockwatch.cc

Index

Constants

This section is empty.

Variables

View Source
var (
	// Defines the User Agent string sent to HTTP servers. May be overwritten
	// by clients.
	UserAgent = "Blockwatch-Data-SDK/" + sdkVersion

	// ERootCAFailed is the error returned when a failure to add a provided
	// root CA to the list of known CAs occurs.
	ERootCAFailed = errors.New("failed to add Root CAs to certificate pool")
)
View Source
var (
	TagName = "json"
)

Functions

func BasicAuth

func BasicAuth(username, password string) string

See 2 (end of page 4) http://www.ietf.org/rfc/rfc2617.txt "To receive authorization, the client sends the userid and password, separated by a single colon (":") character, within a base64 encoded string in the credentials." It is not meant to be urlencoded.

Types

type AddressActivityStats

type AddressActivityStats struct {
	Timestamp             time.Time `json:"time"`
	BlockCount            int64     `json:"n_blocks"`
	AverageBlockTime      float64   `json:"avg_solvetime"`
	BlockchainGrowth      int64     `json:"size_growth"`
	SumRewards            float64   `json:"sum_rewards"`
	SumBurned             float64   `json:"sum_burned"`
	SumCoinDaysDestroyed  float64   `json:"sum_cdd"`
	TransactionVolume     float64   `json:"sum_vol"`
	TransactionFees       float64   `json:"sum_fee"`
	TransactionCount      int64     `json:"n_tx"`
	UtxoCreated           int64     `json:"n_vout"`
	SpendableUtxoCreated  int64     `json:"n_svout"`
	UnspendableTxoCreated int64     `json:"n_uvout"`
	UtxoConsumed          int64     `json:"n_vin"`
	AddressesSeen         int64     `json:"n_addr_active"`
	AddressesCreated      int64     `json:"n_addr_new"`
	AddressesFunded       int64     `json:"n_addr_funded"`
	AddressesEmpty        int64     `json:"n_addr_empty"`
	AddressReusePercent   float64   `json:"pct_addr_reuse"`
	Top1ByVolume          float64   `json:"vol_top1"`
	Top10ByVolume         float64   `json:"vol_top10"`
	Top100ByVolume        float64   `json:"vol_top100"`
	Top1kByVolume         float64   `json:"vol_top1k"`
	Top10kByVolume        float64   `json:"vol_top10k"`
	Top100kByVolume       float64   `json:"vol_top100k"`
	Top1ByTx              int64     `json:"tx_top1"`
	Top10ByTx             int64     `json:"tx_top10"`
	Top100ByTx            int64     `json:"tx_top100"`
	Top1kByTx             int64     `json:"tx_top1k"`
	Top10kByTx            int64     `json:"tx_top10k"`
	Top100kByTx           int64     `json:"tx_top100k"`
}

AddressActivityStats is a Go struct type that can hold blockchain statistics data as stored in blockchain *-EOD:ACTIVITY time series.

type AddressAgeStats

type AddressAgeStats struct {
	Timestamp       time.Time `json:"time"`
	Y1DormantAddr   int64     `json:"y1_addr"`
	Y1DormantFunds  float64   `json:"y1_funds"`
	Y2DormantAddr   int64     `json:"y2_addr"`
	Y2DormantFunds  float64   `json:"y2_funds"`
	Y3DormantAddr   int64     `json:"y3_addr"`
	Y3DormantFunds  float64   `json:"y3_funds"`
	Y4DormantAddr   int64     `json:"y4_addr"`
	Y4DormantFunds  float64   `json:"y4_funds"`
	Y5DormantAddr   int64     `json:"y5_addr"`
	Y5DormantFunds  float64   `json:"y5_funds"`
	Y6DormantAddr   int64     `json:"y6_addr"`
	Y6DormantFunds  float64   `json:"y6_funds"`
	Y7DormantAddr   int64     `json:"y7_addr"`
	Y7DormantFunds  float64   `json:"y7_funds"`
	Y8DormantAddr   int64     `json:"y8_addr"`
	Y8DormantFunds  float64   `json:"y8_funds"`
	Y9DormantAddr   int64     `json:"y9_addr"`
	Y9DormantFunds  float64   `json:"y9_funds"`
	Y10DormantAddr  int64     `json:"y10_addr"`
	Y10DormantFunds float64   `json:"y10_funds"`
	Y11DormantAddr  int64     `json:"y11_addr"`
	Y11DormantFunds float64   `json:"y11_funds"`
	Y12DormantAddr  int64     `json:"y12_addr"`
	Y12DormantFunds float64   `json:"y12_funds"`
	Y13DormantAddr  int64     `json:"y13_addr"`
	Y13DormantFunds float64   `json:"y13_funds"`
	Y14DormantAddr  int64     `json:"y14_addr"`
	Y14DormantFunds float64   `json:"y14_funds"`
	Y15DormantAddr  int64     `json:"y15_addr"`
	Y15DormantFunds float64   `json:"y15_funds"`
	Y16DormantAddr  int64     `json:"y16_addr"`
	Y16DormantFunds float64   `json:"y16_funds"`
	Y17DormantAddr  int64     `json:"y17_addr"`
	Y17DormantFunds float64   `json:"y17_funds"`
	Y18DormantAddr  int64     `json:"y18_addr"`
	Y18DormantFunds float64   `json:"y18_funds"`
	Y19DormantAddr  int64     `json:"y19_addr"`
	Y19DormantFunds float64   `json:"y19_funds"`
	Y20DormantAddr  int64     `json:"y20_addr"`
	Y20DormantFunds float64   `json:"y20_funds"`
}

AddressAgeStats is a Go struct type that can hold blockchain statistics data as stored in blockchain *-EOD:AGE time series.

type AddressBalanceStats

type AddressBalanceStats struct {
	Timestamp                         time.Time `json:"time"`
	Top1Richest                       float64   `json:"rich_top1"`
	Top10Richest                      float64   `json:"rich_top10"`
	Top100Richest                     float64   `json:"rich_top100"`
	Top1kRichest                      float64   `json:"rich_top1k"`
	Top10kRichest                     float64   `json:"rich_top10k"`
	Top100kRichest                    float64   `json:"rich_top100k"`
	SumFundsAtAddressesAbove1atom     float64   `json:"funds_e0"`
	SumFundsAtAddressesAbove10atoms   float64   `json:"funds_e1"`
	SumFundsAtAddressesAbove100atoms  float64   `json:"funds_e2"`
	SumFundsAtAddressesAbove1katoms   float64   `json:"funds_e3"`
	SumFundsAtAddressesAbove10katoms  float64   `json:"funds_e4"`
	SumFundsAtAddressesAbove100katoms float64   `json:"funds_e5"`
	SumFundsAtAddressesAbove1Matoms   float64   `json:"funds_e6"`
	SumFundsAtAddressesAbove10Matoms  float64   `json:"funds_e7"`
	SumFundsAtAddressesAbove1coin     float64   `json:"funds_e8"`
	SumFundsAtAddressesAbove10coins   float64   `json:"funds_e9"`
	SumFundsAtAddressesAbove100coins  float64   `json:"funds_e10"`
	SumFundsAtAddressesAbove1kcoins   float64   `json:"funds_e11"`
	SumFundsAtAddressesAbove10kcoins  float64   `json:"funds_e12"`
	SumFundsAtAddressesAbove100kcoins float64   `json:"funds_e13"`
	SumFundsAtAddressesAbove1Mcoins   float64   `json:"funds_e14"`
	SumFundsAtAddressesAbove10Mcoins  float64   `json:"funds_e15"`
	SumFundsAtAddressesAbove100Mcoins float64   `json:"funds_e16"`
	AddresssCountAbove1atom           int64     `json:"addrs_e0"`
	AddresssCountAbove10atoms         int64     `json:"addrs_e1"`
	AddresssCountAbove100atoms        int64     `json:"addrs_e2"`
	AddresssCountAbove1katoms         int64     `json:"addrs_e3"`
	AddresssCountAbove10katoms        int64     `json:"addrs_e4"`
	AddresssCountAbove100katoms       int64     `json:"addrs_e5"`
	AddresssCountAbove1Matoms         int64     `json:"addrs_e6"`
	AddresssCountAbove10Matoms        int64     `json:"addrs_e7"`
	AddresssCountAbove1coin           int64     `json:"addrs_e8"`
	AddresssCountAbove10coins         int64     `json:"addrs_e9"`
	AddresssCountAbove100coins        int64     `json:"addrs_e10"`
	AddresssCountAbove1kcoins         int64     `json:"addrs_e11"`
	AddresssCountAbove10kcoins        int64     `json:"addrs_e12"`
	AddresssCountAbove100kcoins       int64     `json:"addrs_e13"`
	AddresssCountAbove1Mcoins         int64     `json:"addrs_e14"`
	AddresssCountAbove10Mcoins        int64     `json:"addrs_e15"`
	AddresssCountAbove100Mcoins       int64     `json:"addrs_e16"`
}

AddressBalanceStats is a Go struct type that can hold blockchain statistics data as stored in blockchain *-EOD:BALANCE time series.

type Block

type Block struct {
	RowID                uint64    `json:"row_id"`
	ParentID             uint64    `json:"parent_id"`
	Orphan               bool      `json:"is_orphan"`
	Hash                 string    `json:"hash"`
	Timestamp            time.Time `json:"time"`
	MedianTime           time.Time `json:"mediantime"`
	Height               uint64    `json:"height"`
	Version              int64     `json:"version"`
	Size                 uint64    `json:"size"`
	Weight               uint64    `json:"weight"`
	Bits                 uint64    `json:"bits"`
	ChainWork            float64   `json:"chainwork"`
	Difficulty           float64   `json:"difficulty"`
	Coinbase             []byte    `json:"coinbase"`
	AddressesSeen        uint64    `json:"n_addr"`
	AddressesCreated     uint64    `json:"n_new_addr"`
	AddressesEmptied     uint64    `json:"n_empty_addr"`
	AddressesFunded      uint64    `json:"n_funded_addr"`
	TransactionCount     uint64    `json:"n_tx"`
	UtxoConsumed         uint64    `json:"n_vin"`
	UtxoCreated          uint64    `json:"n_vout"`
	SpendableUtxoCreated uint64    `json:"n_vout_spendable"`
	TransactionVolume    float64   `json:"volume"`
	MiningReward         float64   `json:"reward"`
	TransactionFees      float64   `json:"fee"`
	BurnedCoins          float64   `json:"burned"`
	DaysDestroyed        float64   `json:"days_destroyed"`
	Solvetime            uint64    `json:"solvetime"`
}

Block is a Go struct type that can hold raw data about a blockchain block as stored in blockchain *:BLOCK tables.

type Chain

type Chain struct {
	Height            uint64    `json:"height"`
	Timestamp         time.Time `json:"time"`
	Difficulty        float64   `json:"difficulty"`
	AvgHashrate3h     float64   `json:"hashrate_3h"`
	AvgHashrate12h    float64   `json:"hashrate_12h"`
	TotalWork         float64   `json:"total_work"`
	TotalSize         uint64    `json:"total_size"`
	TotalTransactions uint64    `json:"total_tx"`
	TotalUtxos        uint64    `json:"total_utxo"`
	TotalAddresses    uint64    `json:"total_addr"`
	FundedAddresses   uint64    `json:"funded_addr"`
	TotalSupply       float64   `json:"total_supply"`
	MintedSupply      float64   `json:"minted_supply"`
	MinedSupply       float64   `json:"mined_supply"`
	CurrentSupply     float64   `json:"current_supply"`
	LockedSupply      float64   `json:"locked_supply"`
	BurnedSupply      float64   `json:"burned_supply"`
}

Chain is a Go struct type that can hold running blockchain totals as stored in blockchain *:CHAIN tables.

type Client

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

func NewClient

func NewClient(apikey string, config *ConnConfig) (*Client, error)

NewClient creates a new API client based on the provided connection configuration.

func (*Client) Get

func (c *Client) Get(ctx context.Context, urlpath string, headers http.Header, result interface{}) error

func (*Client) GetDataset

func (c *Client) GetDataset(ctx context.Context, dbcode, setcode string) (*Dataset, error)

func (*Client) GetSeries

func (c *Client) GetSeries(ctx context.Context, dbcode, setcode string, params SeriesParams) (*Series, error)

func (*Client) GetTable

func (c *Client) GetTable(ctx context.Context, dbcode, setcode string, params TableParams) (*Table, error)

func (*Client) ListDatabases

func (c *Client) ListDatabases(ctx context.Context, params DatabaseListParams) (*DatabaseList, error)

func (*Client) ListDatasets

func (c *Client) ListDatasets(ctx context.Context, dbcode string, params DatasetListParams) ([]Dataset, error)

type CollapseMode

type CollapseMode string
const (
	CollapseInvalid        CollapseMode = ""
	CollapseNone           CollapseMode = "none"
	CollapseOneMinute      CollapseMode = "1m"
	CollapseFiveMinutes    CollapseMode = "5m"
	CollapseFifteenMinutes CollapseMode = "15m"
	CollapseThirtyMinutes  CollapseMode = "30m"
	CollapseOneHour        CollapseMode = "1h"
	CollapseThreeHours     CollapseMode = "3h"
	CollapseSixHours       CollapseMode = "6h"
	CollapseTwelveHours    CollapseMode = "12h"
	CollapseDaily          CollapseMode = "1d"
	CollapseWeekly         CollapseMode = "1w"
	CollapseMonthly        CollapseMode = "1M"
	CollapseQuarterly      CollapseMode = "3M"
	CollapseAnnual         CollapseMode = "1y"
)

func NewCollapseMode

func NewCollapseMode(d time.Duration) CollapseMode

func ParseCollapseMode

func ParseCollapseMode(s string) (CollapseMode, error)

func ParseCollapseModeIgnoreError

func ParseCollapseModeIgnoreError(s string) CollapseMode

func (CollapseMode) Duration

func (m CollapseMode) Duration() time.Duration

func (CollapseMode) IsValid

func (m CollapseMode) IsValid() bool

func (CollapseMode) MarshalText

func (m CollapseMode) MarshalText() ([]byte, error)

Text/JSON conversion

func (CollapseMode) String

func (m CollapseMode) String() string

func (*CollapseMode) UnmarshalText

func (m *CollapseMode) UnmarshalText(data []byte) error

type ConnConfig

type ConnConfig struct {
	// HTTP tuning parameters
	DialTimeout           time.Duration `json:"dial_timeout"`
	KeepAlive             time.Duration `json:"keepalive"`
	IdleConnTimeout       time.Duration `json:"idle_timeout"`
	ResponseHeaderTimeout time.Duration `json:"response_timeout"`
	ExpectContinueTimeout time.Duration `json:"continue_timeout"`
	MaxIdleConns          int           `json:"idle_conns"`

	// Proxy specifies to connect through a SOCKS 5 proxy server.  It may
	// be an empty string if a proxy is not required.
	Proxy string `json:"proxy"`

	// ProxyUser is an optional username to use for the proxy server if it
	// requires authentication.  It has no effect if the Proxy parameter
	// is not set.
	ProxyUser string `json:"proxy_user"`

	// ProxyPass is an optional password to use for the proxy server if it
	// requires authentication.  It has no effect if the Proxy parameter
	// is not set.
	ProxyPass string `json:"proxy_pass"`

	// TLS configuration options
	ServerName         string   `json:"server_name"`
	AllowInsecureCerts bool     `json:"disable_tls"`
	TLSMinVersion      int      `json:"tls_min_version"`
	TLSMaxVersion      int      `json:"tls_max_version"`
	RootCaCerts        []string `json:"tls_ca"`
	RootCaCertsFile    string   `json:"tls_ca_file"`
	ClientCert         []string `json:"tls_cert"`
	ClientCertFile     string   `json:"tls_cert_file"`
	ClientKey          []string `json:"tls_key"`
	ClientKeyFile      string   `json:"tls_key_file"`
}

ConnConfig describes the connection configuration parameters for the client.

func DefaultConnConfig

func DefaultConnConfig() *ConnConfig

sane defaults

type Database

type Database struct {
	Id                string    `json:"database_id"`
	AuthorId          string    `json:"author_id"`
	Code              string    `json:"code"`
	Name              string    `json:"name"`
	DatasetType       string    `json:"type"`
	State             string    `json:"state"`
	Description       string    `json:"description"`
	Documentation     string    `json:"documentation"`
	ImageId           string    `json:"imageId"`
	IsPremium         bool      `json:"is_premium"`
	HasSample         bool      `json:"has_sample"`
	DeliveryFrequency string    `json:"delivery_frequency"`
	DataFrequency     string    `json:"data_frequency"`
	ReportingLag      string    `json:"reporting_lag"`
	History           string    `json:"history"`
	Coverage          string    `json:"coverage"`
	Labels            string    `json:"labels"`
	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
	Subscribed        bool      `json:"subscribed"`
}

type DatabaseList

type DatabaseList struct {
	Meta struct {
		Count  int    `json:"count"`
		Cursor string `json:"cursor"`
	} `json:"meta"`
	Databases []*Database `json:"databases"`
}

type DatabaseListParams

type DatabaseListParams struct {
	Limit  int
	Cursor string
}

func (DatabaseListParams) Query

func (p DatabaseListParams) Query() url.Values

func (DatabaseListParams) Url

func (p DatabaseListParams) Url() string

type Datafield

type Datafield struct {
	Name string    `json:"name"`
	Code string    `json:"code"`
	Type FieldType `json:"type"`
}

type Dataframe

type Dataframe struct {
	Columns []Datafield       `json:"columns"`
	Data    []json.RawMessage `json:"data"`
	// contains filtered or unexported fields
}

func (*Dataframe) Column

func (t *Dataframe) Column(name string) (int, interface{}, error)

func (*Dataframe) DecodeAt

func (t *Dataframe) DecodeAt(row int, val interface{}) error

func (*Dataframe) FieldAt

func (t *Dataframe) FieldAt(col, row int) (interface{}, error)

func (*Dataframe) ForEach

func (t *Dataframe) ForEach(fn func(r Row) error) error

func (*Dataframe) ResetType

func (t *Dataframe) ResetType()

type Dataset

type Dataset struct {
	Database      string      `json:"database_code"`
	Dataset       string      `json:"dataset_code"`
	Type          string      `json:"type"`
	Name          string      `json:"name"`
	Description   string      `json:"description"`
	Columns       []Datafield `json:"columns"`
	FilterFields  []string    `json:"filters"`
	PrimaryFields []string    `json:"primary_key"`
}

type DatasetListParams

type DatasetListParams struct {
	Limit  int
	Cursor string
}

func (DatasetListParams) Query

func (p DatasetListParams) Query() url.Values

func (DatasetListParams) Url

func (p DatasetListParams) Url(dbcode string) string

type Error

type Error struct {
	Code      int    `json:"code"`
	Status    int    `json:"status"`
	Message   string `json:"message"`
	Scope     string `json:"scope"`
	Detail    string `json:"detail"`
	RequestId string `json:"requestId"`
	Reason    string `json:"reason"`
}

func (*Error) Error

func (e *Error) Error() string

type Errors

type Errors struct {
	Errors []Error `json:"errors"`
}

func (Errors) Error

func (e Errors) Error() string

type FieldType

type FieldType string
const (
	FieldTypeUndefined FieldType = ""
	FieldTypeString    FieldType = "string"
	FieldTypeBytes     FieldType = "bytes"
	FieldTypeDate      FieldType = "date"
	FieldTypeDatetime  FieldType = "datetime"
	FieldTypeBoolean   FieldType = "boolean"
	FieldTypeFloat64   FieldType = "float64"
	FieldTypeInt64     FieldType = "int64"
	FieldTypeUint64    FieldType = "uint64"
)

func ParseFieldType

func ParseFieldType(s string) FieldType

func (FieldType) IsValid

func (t FieldType) IsValid() bool

func (FieldType) MarshalText

func (r FieldType) MarshalText() ([]byte, error)

func (FieldType) String

func (f FieldType) String() string

func (*FieldType) UnmarshalText

func (t *FieldType) UnmarshalText(data []byte) error

type Filter

type Filter struct {
	Field string
	Mode  FilterMode
	Value string
}

func NewFilter

func NewFilter(field string, mode FilterMode, value string) *Filter

func ParseFilter

func ParseFilter(key string, val string) (*Filter, error)

col_name.{ne|gt|gte|lt|lte|in|nin|re|rg}=value

func (Filter) AppendQuery

func (f Filter) AppendQuery(q url.Values)

func (Filter) String

func (f Filter) String() string

type FilterMode

type FilterMode int
const (
	FilterModeEqual FilterMode = iota
	FilterModeNotEqual
	FilterModeGt
	FilterModeGte
	FilterModeLt
	FilterModeLte
	FilterModeIn
	FilterModeNotIn
	FilterModeRange
	FilterModeRegexp
	FilterModeInvalid
)

func ParseFilterMode

func ParseFilterMode(s string) FilterMode

func (FilterMode) String

func (m FilterMode) String() string

type Flow

type Flow struct {
	RowID             uint64    `json:"row_id"`
	FundingTime       time.Time `json:"fund_time"`
	FundingHeight     uint64    `json:"fund_height"`
	FundingPosition   uint64    `json:"fund_txpos"`
	FundingOutput     uint64    `json:"fund_vout"`
	FundingTxID       string    `json:"fund_txid"`
	Volume            float64   `json:"volume"`
	CoinGenerationMin uint64    `json:"coin_gen_min"`
	CoinGenerationMax uint64    `json:"coin_gen_max"`
	AddressCount      uint64    `json:"n_addr"`
	SignatureCount    uint64    `json:"n_req_sig"`
	AddressType       string    `json:"addr_type"`
	Address           string    `json:"addr"`
	Data              []byte    `json:"data"`
	IsBurned          bool      `json:"is_burned"`
	IsSpendable       bool      `json:"is_spendable"`
	IsSpent           bool      `json:"is_spent"`
	SpendingTime      time.Time `json:"spend_time"`
	SpendingHeight    uint64    `json:"spend_height"`
	SpendingPosition  uint64    `json:"spend_txpos"`
	SpendingInput     uint64    `json:"spend_vin"`
	SpendingTxID      string    `json:"spend_txid"`
}

Flow is a Go struct type that can hold blockchain flow data as stored in blockchain *:FLOW tables.

type HTTPError

type HTTPError interface {
	error
	Status() string  // e.g. "200 OK"
	StatusCode() int // e.g. 200
	Body() []byte
	Unmarshal(val interface{}) error
}

HTTPError retains HTTP status

type Ohlcv

type Ohlcv struct {
	Timestamp       time.Time `json:"time"`
	Open            float64   `json:"open"`
	Close           float64   `json:"close"`
	High            float64   `json:"high"`
	Low             float64   `json:"low"`
	Vwap            float64   `json:"vwap"`
	Std             float64   `json:"stddev"`
	Mean            float64   `json:"mean"`
	TradeCount      int64     `json:"n_trades"`
	BuyCount        int64     `json:"n_buy"`
	SellCount       int64     `json:"n_sell"`
	BaseVolume      float64   `json:"vol_base"`
	QuoteVolume     float64   `json:"vol_quote"`
	BaseVolumeBuy   float64   `json:"vol_buy_base"`
	QuoteVolumeBuy  float64   `json:"vol_buy_quote"`
	BaseVolumeSell  float64   `json:"vol_sell_base"`
	QuoteVolumeSell float64   `json:"vol_sell_quote"`
}

Ohlvc is a Go struct type that can hold data stored in market *:OHLCV time-series

type OrderMode

type OrderMode string
const (
	OrderInvalid OrderMode = ""
	OrderAsc     OrderMode = "asc"
	OrderDesc    OrderMode = "desc"
)

func ParseOrderMode

func ParseOrderMode(s string) (OrderMode, error)

func ParseOrderModeIgnoreError

func ParseOrderModeIgnoreError(s string) OrderMode

func (OrderMode) IsValid

func (m OrderMode) IsValid() bool

func (OrderMode) MarshalText

func (m OrderMode) MarshalText() ([]byte, error)

func (OrderMode) String

func (m OrderMode) String() string

func (*OrderMode) UnmarshalText

func (m *OrderMode) UnmarshalText(data []byte) error

type RateLimitError

type RateLimitError interface {
	HTTPError
	Wait(context.Context) error
	Done() <-chan struct{}
	Deadline() time.Duration
}

RateLimitError helps manage rate limit errors

func IsRateLimited

func IsRateLimited(err error) (RateLimitError, bool)

type Row

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

func (Row) Column

func (r Row) Column(name string) (int, interface{}, error)

func (Row) Dataframe

func (r Row) Dataframe() *Dataframe

func (Row) Decode

func (r Row) Decode(val interface{}) error

type Series

type Series struct {
	Dataframe
	Collapse  CollapseMode `json:"collapse"`
	Order     OrderMode    `json:"order"`
	StartDate time.Time    `json:"start_date"`
	EndDate   time.Time    `json:"end_date"`
	Limit     int          `json:"limit"`
	Count     int          `json:"count"`
	Error     *Error       `json:"error"`
}

func (*Series) UnmarshalJSON

func (s *Series) UnmarshalJSON(data []byte) error

convert timestamps on unmarshal

type SeriesParams

type SeriesParams struct {
	Columns   []string
	Collapse  CollapseMode
	Order     OrderMode
	StartDate time.Time
	EndDate   time.Time
	Limit     int
	Format    string
	Filter    []*Filter
}

func (SeriesParams) Query

func (p SeriesParams) Query() url.Values

func (SeriesParams) Url

func (p SeriesParams) Url(db, set string) string

type SupplyStats

type SupplyStats struct {
	Timestamp               time.Time `json:"time"`
	TotalSupply             float64   `json:"total"`
	CurrentSupply           float64   `json:"current"`
	CirculatingSupply       float64   `json:"circulating"`
	MinedSupply             float64   `json:"mined"`
	LockedSupply            float64   `json:"locked"`
	BurnedSupply            float64   `json:"burned"`
	UntouchedSupply         float64   `json:"untouched"`
	HodlSupply3M            float64   `json:"hodl_3m"`
	TransactingSupply3M     float64   `json:"tx_3m"`
	DaysDestroyed3M         float64   `json:"cdd_3m"`
	InflationLast24h        float64   `json:"inflation"`
	AnnualizedInflationRate float64   `json:"inflation_rate"`
}

SupplyStats is a Go struct type that can hold blockchain statistics data as stored in blockchain *-EOD:SUPPY time series.

type Table

type Table struct {
	Dataframe
	Limit  int    `json:"limit"`
	Count  int    `json:"count"`
	Cursor string `json:"cursor"`
	Error  *Error `json:"error"`
}

type TableParams

type TableParams struct {
	Columns []string
	Cursor  string
	Limit   int
	Filter  []*Filter
	Format  string
}

func (TableParams) Query

func (p TableParams) Query() url.Values

func (TableParams) Url

func (p TableParams) Url(db, set string) string

type Trade

type Trade struct {
	ID        int64     `json:"id"`
	Timestamp time.Time `json:"time"`
	Price     float64   `json:"price"`
	Amount    float64   `json:"amount"`
	IsSell    bool      `json:"sell"`
}

Trade is a Go struct type that can hold raw tick data stored in market *:Trade tables.

type Tx

type Tx struct {
	RowID          uint64    `json:"row_id"`
	Timestamp      time.Time `json:"time"`
	Height         uint64    `json:"height"`
	Position       uint64    `json:"tx_n"`
	TransactionID  string    `json:"tx_id"`
	Locktime       int64     `json:"locktime"`
	Size           int64     `json:"size"`
	VirtualSize    int64     `json:"vsize"`
	Version        int64     `json:"version"`
	SpentInputs    int64     `json:"n_in"`
	CreatedOutputs int64     `json:"n_out"`
	Type           string    `json:"type"`
	HasData        bool      `json:"has_data"`
	Volume         float64   `json:"volume"`
	Fee            float64   `json:"fee"`
	DaysDestroyed  float64   `json:"days_destroyed"`
}

Tx is a Go struct type that can hold raw data about a blockchain transaction as stored in blockchain *:TX tables.

type TxStats

type TxStats struct {
	Timestamp              time.Time `json:"time"`
	Type                   string    `json:"type"`
	Count                  int64     `json:"n_tx"`
	MinFee                 float64   `json:"min_fee"`
	MaxFee                 float64   `json:"max_fee"`
	MeanFee                float64   `json:"mean_fee"`
	MedianFee              float64   `json:"median_fee"`
	SumFees                float64   `json:"sum_fee"`
	MinFeeRate             float64   `json:"min_fee_rate"`
	MaxFeeRate             float64   `json:"max_fee_rate"`
	MeanFeeRate            float64   `json:"mean_fee_rate"`
	MedianFeeRate          float64   `json:"median_fee_rate"`
	SumFeeRates            float64   `json:"sum_fee_rate"`
	MinSize                int64     `json:"min_size"`
	MaxSize                int64     `json:"max_size"`
	MeanSize               float64   `json:"mean_size"`
	MedianSize             float64   `json:"median_size"`
	SumSizes               int64     `json:"sum_size"`
	MinInputs              int64     `json:"min_n_vin"`
	MaxInputs              int64     `json:"max_n_vin"`
	MeanInputs             float64   `json:"mean_n_vin"`
	MedianInputs           float64   `json:"median_n_vin"`
	SumInputs              int64     `json:"sum_n_vin"`
	MinOutputs             int64     `json:"min_n_vout"`
	MaxOutputs             int64     `json:"max_n_vout"`
	MeanOutputs            float64   `json:"mean_n_vout"`
	MedianOutputs          float64   `json:"median_n_vout"`
	SumOutputs             int64     `json:"sum_n_vout"`
	MinVolume              float64   `json:"min_vol"`
	MaxVolume              float64   `json:"max_vol"`
	MeanVolume             float64   `json:"mean_vol"`
	MedianVolume           float64   `json:"median_vol"`
	SumVolume              float64   `json:"sum_vol"`
	MinDaysDestroyed       float64   `json:"min_cdd"`
	MaxDaysDestroyed       float64   `json:"max_cdd"`
	MeanDaysDestroyed      float64   `json:"mean_cdd"`
	MedianDaysDestroyed    float64   `json:"median_cdd"`
	SumDaysDestroyed       float64   `json:"sum_cdd"`
	MinAvgDaysDestroyed    float64   `json:"min_add"`
	MaxAvgDaysDestroyed    float64   `json:"max_add"`
	MeanAvgDaysDestroyed   float64   `json:"mean_add"`
	MedianAvgDaysDestroyed float64   `json:"median_add"`
	SumAvgDaysDestroyed    float64   `json:"sum_add"`
}

TxStats is a Go struct type that can hold blockchain statistics data as stored in blockchain *-EOD:TX time series.

type UtxoStats

type UtxoStats struct {
	Timestamp time.Time `json:"time"`
	Type      string    `json:"type"`
	Count     int64     `json:"n_out"`
	Volume    float64   `json:"vol"`
}

UtxoStats is a Go struct type that can hold blockchain statistics data as stored in blockchain *-EOD:UTXO time series.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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