package peer

import "github.com/threefoldtech/tfgrid-sdk-go/rmb-sdk-go/peer"

Package direct package provides the functionality to create a direct websocket connection to rmb relays without the need to rmb peers.

Example

Code:

{
	items := []WeightItem[string]{
		{
			Item:   "Banana",
			Weight: 0,
		},
		{
			Item:   "Apple",
			Weight: 0,
		},
		{
			Item:   "Mellon",
			Weight: 0,
		},
		{
			Item:   "Pineapple",
			Weight: 9,
		},
	}

	randomizer, err := NewWeightSlice(items)
	if err != nil {
		log.Fatal(err)
	}

	i, fruit := randomizer.Choose()
	fmt.Printf("%v: %s", i, fruit)
	// Output: 3: Pineapple
}

Output:

3: Pineapple

Index

Examples

Constants

const (
	KeyTypeEd25519 = "ed25519"
	KeyTypeSr25519 = "sr25519"
)
const (
	SignatureTypeEd25519 = "ed25519"
	SignatureTypeSr25519 = "sr25519"
)
const CustomSigning = "RMB"

Variables

var (
	// ErrFunctionNotFound is an err returned if the handler function is not found
	ErrFunctionNotFound = fmt.Errorf("function is not found")
)

Functions

func Challenge

func Challenge(env *types.Envelope) ([]byte, error)

func GetEnvelope

func GetEnvelope(ctx context.Context) *types.Envelope

GetEnvelope gets an envelope from the context, panics if it's not there

func GetTwinID

func GetTwinID(ctx context.Context) uint32

GetTwinID returns the twin id from context.

func Json

func Json(response *types.Envelope, callBackErr error) ([]byte, error)

Json extracts the json payload envelope and validate the schema

func NewJWT

func NewJWT(identity substrate.Identity, id uint32, session string, ttl uint32) (string, error)

func Sign

func Sign(signer substrate.Identity, input []byte) ([]byte, error)

func VerifySignature

func VerifySignature(twinDB TwinDB, env *types.Envelope) error

VerifySignature is responsible for verifying that the source produced this signature

Types

type Ed25519VerifyingKey

type Ed25519VerifyingKey []byte

func (Ed25519VerifyingKey) Verify

func (k Ed25519VerifyingKey) Verify(msg []byte, sig []byte) bool

type Handler

type Handler func(ctx context.Context, peer *Peer, env *types.Envelope, err error)

Handler is a call back that is called with verified and decrypted incoming messages. An error can be non-nil error if verification or decryption failed

type HandlerFunc

type HandlerFunc func(ctx context.Context, payload []byte) (interface{}, error)

Handler is a handler function type

type InnerConnection

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

InnerConnection holds the required state to create a self healing websocket connection to the rmb relay.

func NewConnection

func NewConnection(identity substrate.Identity, url string, session string, twinID uint32) InnerConnection

NewConnection creates a new InnerConnection instance

func (*InnerConnection) Start

func (c *InnerConnection) Start(ctx context.Context, output chan []byte)

Start initiates the websocket connection

type Middleware

type Middleware func(ctx context.Context, payload []byte) (context.Context, error)

Middleware is middleware function type

type Peer

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

Peer exposes the functionality to talk directly to an rmb relay

func NewPeer

func NewPeer(
	ctx context.Context,
	mnemonics string,
	subManager substrate.Manager,
	handler Handler,
	opts ...PeerOpt,
) (*Peer, error)

NewPeer creates a new RMB peer client. It connects directly to the RMB-Relay, and tries to reconnect if the connection broke.

You can close the connection by canceling the passed context.

Make sure the context passed to Call() does not outlive the directClient's context. Call() will panic if called while the directClient's context is canceled.

func (*Peer) Encoder

func (p *Peer) Encoder() encoder.Encoder

Encoder returns the peer's encoder.

func (*Peer) SendRequest

func (d *Peer) SendRequest(ctx context.Context, id string, twin uint32, session *string, fn string, data interface{}) error

SendRequest sends an rmb message to the relay

func (*Peer) SendResponse

func (d *Peer) SendResponse(ctx context.Context, id string, twin uint32, session *string, responseError error, data interface{}) error

SendResponse sends an rmb message to the relay

type PeerOpt

type PeerOpt func(*peerCfg)

func WithEncoder

func WithEncoder(encoder encoder.Encoder) PeerOpt

WithEncoder sets encoding of the payload default is application/json

func WithEncryption

func WithEncryption(enable bool) PeerOpt

enable or disable encryption, default is enabled

func WithInMemoryExpiration

func WithInMemoryExpiration(ttl uint64) PeerOpt

if ttl == 0 twins are cached forever

func WithKeyType

func WithKeyType(keyType string) PeerOpt

WithKeyType set up the mnemonic key type, default is Sr25519

func WithRelay

func WithRelay(urls ...string) PeerOpt

WithRelay set up the relay url, default is mainnet relay

func WithSession

func WithSession(session string) PeerOpt

WithSession set a custom session name, default is the nil session

func WithTmpCacheExpiration

func WithTmpCacheExpiration(ttl uint64) PeerOpt

WithTwinCache cache twin information for this ttl number of seconds if ttl == 0, twins are cached forever

type Reader

type Reader <-chan []byte

Reader is a channel that receives incoming messages

func (Reader) Read

func (r Reader) Read() []byte

type RmbSigner

type RmbSigner struct{}

func (*RmbSigner) Alg

func (s *RmbSigner) Alg() string

func (*RmbSigner) Sign

func (s *RmbSigner) Sign(signingString string, key interface{}) (string, error)

func (*RmbSigner) Verify

func (s *RmbSigner) Verify(signingString, signature string, key interface{}) error

type Router

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

func NewRouter

func NewRouter() *Router

func (*Router) Serve

func (r *Router) Serve(ctx context.Context, peer *Peer, env *types.Envelope, err error)

func (*Router) SubRoute

func (r *Router) SubRoute(prefix string) *Router

SubRoute add a route prefix to include more sub routes with handler from it

func (*Router) Use

func (r *Router) Use(mw Middleware)

Use adds a middleware to the router

func (*Router) WithHandler

func (r *Router) WithHandler(subCommand string, handler HandlerFunc)

WithHandler adds a handler function to a router sub command

type RpcClient

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

RpcClient is a peer connection that makes it easy to make rpc calls

func NewRpcClient

func NewRpcClient(
	ctx context.Context,
	mnemonics string,
	subManager substrate.Manager,
	opts ...PeerOpt) (*RpcClient, error)

NewRpcClient create a new rpc client the rpc client is a full peer, but provide a custom handler to make it easy to make rpc calls

func (*RpcClient) Call

func (d *RpcClient) Call(ctx context.Context, twin uint32, fn string, data interface{}, result interface{}) error

func (*RpcClient) CallWithSession

func (d *RpcClient) CallWithSession(ctx context.Context, twin uint32, session *string, fn string, data interface{}, result interface{}) error

type Sr25519VerifyingKey

type Sr25519VerifyingKey []byte

func (Sr25519VerifyingKey) Verify

func (k Sr25519VerifyingKey) Verify(msg []byte, sig []byte) bool

type Twin

type Twin struct {
	ID        uint32
	PublicKey []byte
	Relay     *string
	E2EKey    []byte
	Timestamp uint64
}

Twin is used to store a twin id and its public key

type TwinDB

type TwinDB interface {
	Get(id uint32) (Twin, error)
	GetByPk(pk []byte) (uint32, error)
}

TwinDB is used to get Twin instances

func NewTwinDB

func NewTwinDB(subConn *substrate.Substrate) TwinDB

NewTwinDB creates a new twinDBImpl instance, with a non expiring cache.

type Verifier

type Verifier interface {
	Verify(msg []byte, sig []byte) bool
}

type WeightItem

type WeightItem[T any] struct {
	Item   T
	Weight uint64
}

WeightItem is a generic wrapper that can be used to add weights for any item.

type WeightSlice

type WeightSlice[T any] struct {
	// contains filtered or unexported fields
}

A WeightSlice caches slice options for weighted random selection.

func NewWeightSlice

func NewWeightSlice[T any](items []WeightItem[T]) (*WeightSlice[T], error)

NewWeightSlice initializes a new weight slice for picking from the provided choices with their weights.

func (WeightSlice[T]) Choose

func (c WeightSlice[T]) Choose() (int, T)

Choose returns a single weighted random item from the slice.

Source Files

connection.go hashes.go jwt.go peer.go router.go rpc.go sig.go twindb.go weighted_rand.go

Directories

PathSynopsis
peer/encoder
peer/examples
peer/examples/peer
peer/examples/peer_pingmany
peer/examples/router_server
peer/examples/rpc
peer/types
Version
v0.16.6 (latest)
Published
Mar 17, 2025
Platform
linux/amd64
Imports
39 packages
Last checked
1 hour ago

Tools for package owners.