v1.5.7 Latest Latest

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

Go to latest
Published: Jul 28, 2023 License: Apache-2.0, MIT Imports: 17 Imported by: 20



Package client provides transport-agnostic logic to retrieve and verify randomness from drand, including retry, validation, caching and optimization features.


import (


var chainHash, _ = hex.DecodeString("8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce")

func main() {
	c, err := client.New(
		client.From("..."), // see concrete client implementations

	// e.g. use the client to get the latest randomness round:
	r := c.Get(context.Background(), 0)

	fmt.Println(r.Round(), r.Randomness())

The "From" option allows you to specify clients that work over particular transports. HTTP, gRPC and libp2p PubSub clients are provided in drand's subpackages, and respectively. Note that you are not restricted to just one client. You can use multiple clients of the same type or of different types. The base client will periodically "speed test" it's clients, failover, cache results and aggregate calls to "Watch" to reduce requests.

WARNING: When using the client you should use the "WithChainHash" or "WithChainInfo" option in order for your client to validate the randomness it receives is from the correct chain. You may use the "Insecurely" option to bypass this validation but it is not recommended.

In an application that uses the drand client, the following options are likely to be needed/customized:

	should be set to something sensible for your application.

	both should be set for increased security if you have
	persistent state and expect to be following the chain.

	will pre-load new results as they become available adding them
	to the cache for speedy retreival when you need them.

	enables metrics reporting on speed and performance to a
	provided prometheus registry.



This section is empty.


This section is empty.


func PollingWatcher added in v1.0.0

func PollingWatcher(ctx context.Context, c Client, chainInfo *chain.Info, l log.Logger) <-chan Result

PollingWatcher generalizes the `Watch` interface for clients which learn new values by asking for them once each group period.


type Cache added in v1.0.0

type Cache interface {
	// TryGet provides a round beacon or nil if it is not cached.
	TryGet(round uint64) Result
	// Add adds an item to the cache
	Add(uint64, Result)

Cache provides a mechanism to check for rounds in the cache.

type Client

type Client interface {
	// Get returns a the randomness at `round` or an error.
	// Requesting round = 0 will return randomness for the most
	// recent known round, bounded at a minimum to the `RoundAt(time.Now())`
	Get(ctx context.Context, round uint64) (Result, error)

	// Watch returns new randomness as it becomes available.
	Watch(ctx context.Context) <-chan Result

	// Info returns the parameters of the chain this client is connected to.
	// The public key, when it started, and how frequently it updates.
	Info(ctx context.Context) (*chain.Info, error)

	// RoundAt will return the most recent round of randomness that will be available
	// at time for the current client.
	RoundAt(time time.Time) uint64

	// Close will halt the client, any background processes it runs and any
	// in-flight Get, Watch or Info requests. Behavior for usage of the client
	// after Close is called is undefined.

Client represents the drand Client interface.

func EmptyClientWithInfo added in v1.0.0

func EmptyClientWithInfo(info *chain.Info) Client

EmptyClientWithInfo makes a client that returns the given info but no randomness

func New

func New(options ...Option) (Client, error)

New Creates a client with specified configuration.

func NewCachingClient

func NewCachingClient(client Client, cache Cache) (Client, error)

NewCachingClient is a meta client that stores an LRU cache of recently fetched random values.

func Wrap added in v1.0.0

func Wrap(clients []Client, options ...Option) (Client, error)

Wrap provides a single entrypoint for wrapping a concrete client implementation with configured aggregation, caching, and retry logic

type LoggingClient added in v1.0.0

type LoggingClient interface {

LoggingClient sets the logger for use by clients that suppport it

type Option

type Option func(cfg *clientConfig) error

Option is an option configuring a client.

func From added in v1.0.0

func From(c ...Client) Option

From constructs the client from a set of clients providing randomness

func Insecurely added in v1.0.0

func Insecurely() Option

Insecurely indicates the client should be allowed to provide randomness when the root of trust is not fully provided in a validate-able way.

func WithAutoWatch added in v1.0.0

func WithAutoWatch() Option

WithAutoWatch causes the client to automatically attempt to get randomness for rounds, so that it will hopefully already be cached when `Get` is called.

func WithAutoWatchRetry added in v1.1.0

func WithAutoWatchRetry(interval time.Duration) Option

WithAutoWatchRetry specifies the time after which the watch channel created by the autoWatch is re-opened when no context error occurred. Set to a negative value to disable retrying auto watch.

func WithCacheSize

func WithCacheSize(size int) Option

WithCacheSize specifies how large of a cache of randomness values should be kept locally. Default 32

func WithChainHash added in v1.0.0

func WithChainHash(chainHash []byte) Option

WithChainHash configures the client to root trust with a given randomness chain hash, the chain parameters will be fetched from an HTTP endpoint.

func WithChainInfo added in v1.0.0

func WithChainInfo(chainInfo *chain.Info) Option

WithChainInfo configures the client to root trust in the given randomness chain information

func WithFullChainVerification added in v1.0.0

func WithFullChainVerification() Option

WithFullChainVerification validates random beacons not just as being generated correctly from the group signature, but ensures that the full chain is deterministic by making sure each round is derived correctly from the previous one. In cases of compromise where a single party learns sufficient shares to derive the full key, malicious randomness could otherwise be generated that is signed, but not properly derived from previous rounds according to protocol.

func WithLogger

func WithLogger(l log.Logger) Option

WithLogger overrides the logging options for the client, allowing specification of additional tags, or redirection / configuration of logging level and output.

func WithPrometheus added in v1.0.0

func WithPrometheus(r prometheus.Registerer) Option

WithPrometheus specifies a registry into which to report metrics

func WithVerifiedResult added in v1.0.0

func WithVerifiedResult(result Result) Option

WithVerifiedResult provides a checkpoint of randomness verified at a given round. Used in combination with `VerifyFullChain`, this allows for catching up only on previously not-yet-verified results.

func WithWatcher added in v1.0.0

func WithWatcher(wc WatcherCtor) Option

WithWatcher specifies a channel that can provide notifications of new randomness bootstrappeed from the chain info.

type RandomData

type RandomData struct {
	Rnd               uint64 `json:"round,omitempty"`
	Random            []byte `json:"randomness,omitempty"`
	Sig               []byte `json:"signature,omitempty"`
	PreviousSignature []byte `json:"previous_signature,omitempty"`

RandomData holds the full random response from the server, including data needed for validation.

func (*RandomData) Randomness

func (r *RandomData) Randomness() []byte

Randomness exports the randomness

func (*RandomData) Round

func (r *RandomData) Round() uint64

Round provides access to the round associated with this random data.

func (*RandomData) Signature

func (r *RandomData) Signature() []byte

Signature provides the signature over this round's randomness

type Result

type Result interface {
	Round() uint64
	Randomness() []byte
	Signature() []byte

Result represents the randomness for a single drand round.

type Watcher added in v1.0.0

type Watcher interface {
	Watch(ctx context.Context) <-chan Result

Watcher supplies the `Watch` portion of the drand client interface.

type WatcherCtor added in v1.0.0

type WatcherCtor func(chainInfo *chain.Info, cache Cache) (Watcher, error)

WatcherCtor creates a Watcher once chain info is known.


Path Synopsis
Package grpc provides a drand client implementation that uses drand's gRPC API.
Package grpc provides a drand client implementation that uses drand's gRPC API.
Package http provides a drand client implementation that uses drand's HTTP API.
Package http provides a drand client implementation that uses drand's HTTP API.

Jump to

Keyboard shortcuts

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