alsdk

package module
v2.0.0-...-44ffc9c Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2023 License: MIT Imports: 11 Imported by: 0

README

Activeledger

Activeledger - Golang SDK

The Activeledger Golang SDK has been built to provide an easy way to connect your Go application to an Activeledger Network

Activeledger

Visit Activeledger.io

Read Activeledgers documentation

Installation

go get github.com/activeledger/SDK-Golang/v2

Usage

The SDK currently supports the following functionality

  • Connection handling
  • Key generation
  • Key onboarding
  • Transaction building
Import
import (
  alsdk "github.com/activeledger/SDK-Golang/v2"
)
Connection

When sending a transaction, you must pass a connection that provides the information needed to establish a link to the network and specified node.

To do this a connection object must be created. This object must be passed the protocol, address, and port.

address := "localhost"
port := "2560"

connection := alsdk.NewConnection(alsdk.HTTP, {address}, {port})
Example - Connecting to the Activeledger public testnet
address := "localhost"
port := "2560"

connection := alsdk.NewConnection(alsdk.HTTP, address, port)

NewConnection() returns a Connection{} object which looks like this:

type Connection struct {
	Protocol Protocol
	Url      string
	Port     string
}

Later this is passed to the Send() function and used to connect to the given node.


Key

Activeledger uses RSA and Elliptic Curve keys. Currently EC is only partialy implemented in this SDK. RSA is fully implemented.

Generating a key
Example
// RSA
// Generate the private key
keyHandler := alsdk.GenerateRSA()
Exporting Key
Example
// RSA Public key string PEM
publicKey := keyHandler.GetPublicPem()
Onboarding a key and creating a transaction

Once you have a key generated, to use it to sign transactions it must be onboarded to the ledger network

Example
// The identity of the stream
streamId := "someidentity"

// Create a new RSA key handler
keyHandler, err := alsdk.GenerateRSA()
if err != nil {// ... }

// Convert our stream ID to a StreamID struct
alStreamId := alsdk.StreamID(streamId)

// Create a new instance of the DataWrapper to hold the Tx input data
input := alsdk.DataWrapper{
	"type":      "rsa",
	"publicKey": keyHandler.GetPublicPEM(),
}

// Use our previously created data to create an object of transaction objects
// which will be used to build the transaction
txOpts := alsdk.TransactionOpts{
	StreamID:  alStreamId,
	Contract:  "onboard",
	Namespace: "namespace",
	Input:     input,
	SelfSign:  true,
	Key:       keyHandler,
}

// Build transaction returns the following:
// txHandler - This handles making modifications to the tx we have just built
// hash      - The checksum hash generated when signing the transaction, 
//              you can use this to perform validity checks
txHandler, hash, err := alsdk.BuildTransaction(txOpts)
if err != nil {// ... }

// Get the transaction object
tx := txHandler.GetTransaction()

// Send the transaction to the network and receive the Activeledger response data
resp, err := alsdk.Send(tx, l.conn)
if err != nil {// ... }

The resp returns the following structs

// Holds the response data from Activeledger
type Response struct {
	UMID           string        `json:"$umid"`
	Summary        Summary       `json:"$summary"`
	Response       []interface{} `json:"$responses"`
	Territoriality string        `json:"$territoriality"`
	Streams        Streams       `json:"$streams"`
}

// Summary structure in Response
type Summary struct {
	Total  int      `json:"total"`
	Vote   int      `json:"vote"`
	Commit int      `json:"commit"`
	Errors []string `json:"errors"`
}

// Streams structure in Response
type Streams struct {
	New     []StreamData `json:"new"`
	Updated []StreamData `json:"updated"`
}

// Stream data structure in Streams
type StreamData struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

Signing & sending a transaction

When signing a transaction you must send the finished version of it. No changes can be made after signing as this will cause the ledger to reject it as the signature will no longer be valid.

The key must be one that has been successfully onboarded to the ledger which the transaction is being sent to.

Events Subscription

SDK contains different helper functions for the purpose of subscribing to different events.

  • Subscribe(host) // host=protocol://ip:port
  • SubscribeStream(host,stream)
  • EventSubscribeContract(host,contract,event)
  • EventSubscribe(host,contract)
  • AllEventSubscribe(host)

They all return events which can then be used by developers.

ActivityStreams

SDK also contains helper functions to get and search streams from Activeledger.

  • GetActivityStreams(host, ids) // host=protocol://ip:port
  • GetActivityStream(host, id)
  • GetActivityStreamVolatile(host, id)
  • SetActivityStreamVolatile(host, id, bdy) // Anything in the bdy will be written to that location for that stream id.
  • GetActivityStreamChanges(host)
  • SearchActivityStreamPost(host, query) //post request
  • SearchActivityStreamGet(host, query) //get Request
  • FindTransaction(host, umid )

They all return map[string]interface{}.

License


This project is licensed under the MIT License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrActiveledgerResp error              = errors.New("activeledger returned errors, see response.summary.errors")
	ErrJSON             alerror.ALSDKError = *alerror.NewAlError("there was an error converting the transaction into a json string")
	ErrSend             alerror.ALSDKError = *alerror.NewAlError("sending the request to the activeledger node failed")
)
View Source
var (
	ErrNotImplemented = errors.New("not implemented")
	ErrUnknownKey     = errors.New("unknown key type")
)
View Source
var (
	ErrMarshalFail alerror.ALSDKError = *alerror.NewAlError("error marshaling stream")
)
View Source
var (
	ErrNoStreamID error = errors.New("stream id not given")
)

Functions

func VerifyUsingPem

func VerifyUsingPem(sig []byte, checksum []byte, pubPem string, keyType KeyType) (bool, error)

VerifyUsingPem - Verify a given signature using a given public key PEM

Types

type Connection

type Connection struct {
	Protocol Protocol
	Url      string
	Port     string
}

func NewConnection

func NewConnection(protocol Protocol, url string, port string) Connection

NewConnection - Create a new connection

func (Connection) String

func (c Connection) String() string

String - Returns the URL as a string

type DataWrapper

type DataWrapper map[string]interface{}

type Key

type Key struct {
	RSA      key.RSAHandler
	Elliptic key.EllipticHandler
	// contains filtered or unexported fields
}

func (Key) GetEllipticKey

func (k Key) GetEllipticKey() *ecdsa.PrivateKey

func (Key) GetPrivatePEM

func (k Key) GetPrivatePEM() string

func (Key) GetPublicPEM

func (k Key) GetPublicPEM() string

func (Key) GetRSAKey

func (k Key) GetRSAKey() *rsa.PrivateKey

func (Key) GetType

func (k Key) GetType() KeyType

func (Key) Sign

func (k Key) Sign(data []byte) (Signature []byte, Hash []byte, SignError error)

Sign a byte slice, returns the signature and checksum hash

func (Key) Verify

func (k Key) Verify(signature []byte, checksum []byte) (bool, error)

Verify a signature with a given checksum

type KeyHandler

type KeyHandler interface {
	Sign(Data []byte) (Signature []byte, Hash []byte, SignError error)
	Verify(Signature []byte, Checksum []byte) (Ok bool, VerifError error)

	GetType() KeyType
	GetRSAKey() (Key *rsa.PrivateKey)
	GetEllipticKey() (Key *ecdsa.PrivateKey)
	GetPrivatePEM() (KeyPublicPem string)
	GetPublicPEM() (KeyPrivatePem string)
}

func GenerateElliptic

func GenerateElliptic() (KeyHandler, error)

Generate new Elliptic Curve Key

func GenerateRSA

func GenerateRSA() (KeyHandler, error)

Generate a new RSA key

func SetKey

func SetKey(pem string, keyType KeyType) (KeyHandler, error)

type KeyType

type KeyType string
const (
	RSA      KeyType = "rsa"
	Elliptic KeyType = "elliptic"
)

type Neighbour

type Neighbour struct {
	IsHome bool `json:"isHome"`
}

type Neighbourhood

type Neighbourhood struct {
	Neighbours map[string]Neighbour `json:"neighbours"`
}

type Node

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

func (*Node) FindTransaction

func (n *Node) FindTransaction(umid string) (StreamResponse, error)

FindTransaction - Find a transaction using its UMID

func (*Node) GetChanges

func (n *Node) GetChanges() (StreamResponse, error)

GetChanges - Returns the latest activity stream changes

func (*Node) GetData

func (n *Node) GetData(streamId string) (StreamResponse, error)

GetData - Returns the stream data of the speicifed stream

func (*Node) GetList

func (n *Node) GetList(streamIds []string) (StreamResponse, error)

GetList - Returns an array of stream data from the specified streams

func (*Node) GetVolatile

func (n *Node) GetVolatile(streamId string) (StreamResponse, error)

GetVolatile - Returns the volatile data of the specified stream

func (*Node) SetVolatile

func (n *Node) SetVolatile(streamId string, volatileData interface{}) (StreamResponse, error)

SetVolatile - Sets the volatile data of a specified stream

type NodeHandler

type NodeHandler interface {
	GetList(StreamIDs []string) (StreamResponse, error)
	GetData(StreamID string) (StreamResponse, error)
	GetVolatile(StreamID string) (StreamResponse, error)
	SetVolatile(StreamID string, VolatileData interface{}) (StreamResponse, error)
	GetChanges() (StreamResponse, error)
	FindTransaction(UMID string) (StreamResponse, error)
}

func ConnectNode

func ConnectNode(c Connection) NodeHandler

type Nodes

type Nodes []string

func GetNodeReferences

func GetNodeReferences(connection Connection) (Nodes, error)

type Protocol

type Protocol string
const (
	HTTP  Protocol = "http"
	HTTPS Protocol = "https"
)

type Response

type Response struct {
	UMID           string        `json:"$umid"`
	Summary        Summary       `json:"$summary"`
	Response       []interface{} `json:"$responses"`
	Territoriality string        `json:"$territoriality"`
	Streams        Streams       `json:"$streams"`
}

Response - Holds the response data from Activeledger

func Send

func Send(tx Transaction, c Connection) (Response, error)

type StreamData

type StreamData struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

StreamData - Stream data structure in Streams

type StreamID

type StreamID string

type StreamIDWrapper

type StreamIDWrapper map[StreamID]interface{}

type StreamResponse

type StreamResponse map[string]interface{}

type Streams

type Streams struct {
	New     []StreamData `json:"new"`
	Updated []StreamData `json:"updated"`
}

Streams - Streams structure in Response

type Summary

type Summary struct {
	Total  int      `json:"total"`
	Vote   int      `json:"vote"`
	Commit int      `json:"commit"`
	Errors []string `json:"errors"`
}

Summary - Summary structure in Response

type Transaction

type Transaction struct {
	Territoriality string          `json:"$territoriality,omitempty"`
	Transaction    TxBody          `json:"$tx"`
	SelfSign       bool            `json:"$selfsign"`
	Signature      StreamIDWrapper `json:"$sigs"`
}

func (Transaction) GetTransaction

func (t Transaction) GetTransaction() Transaction

func (*Transaction) SetInput

func (t *Transaction) SetInput(id StreamID, d map[string]interface{})

SetInput - Set the input data of the transaction

func (*Transaction) SetOutput

func (t *Transaction) SetOutput(id StreamID, d map[string]interface{})

SetOutput - Set the output data of the transaction

func (*Transaction) SetReadonly

func (t *Transaction) SetReadonly(id StreamID, d map[string]interface{})

SetReadonly - Set the readonly data of a transaction

func (*Transaction) Sign

func (t *Transaction) Sign(key KeyHandler, id StreamID) error

Sign - Sign a transaction

type TransactionHandler

type TransactionHandler interface {
	Sign(Key KeyHandler, ID StreamID) error
	SetInput(ID StreamID, Input map[string]interface{})
	SetOutput(ID StreamID, Output map[string]interface{})
	SetReadonly(ID StreamID, ReadOnly map[string]interface{})
	GetTransaction() Transaction
}

func BuildTransaction

func BuildTransaction(o TransactionOpts) (Tx TransactionHandler, Hash []byte, TXError error)

BuildTransaction - Pass all required data and create a transaction from it

type TransactionOpts

type TransactionOpts struct {
	StreamID         StreamID
	OutputStreamID   StreamID
	ReadOnlyStreamID StreamID
	Key              KeyHandler
	Namespace        string
	Contract         string
	Entry            string
	SelfSign         bool
	Territoriality   string
	Input            DataWrapper
	Output           DataWrapper
	ReadOnly         DataWrapper
}

type TxBody

type TxBody struct {
	Namespace string          `json:"$namespace"`
	Contract  string          `json:"$contract"`
	Entry     string          `json:"$entry,omitempty"`
	Input     StreamIDWrapper `json:"$i"`
	Output    StreamIDWrapper `json:"$o,omitempty"`
	ReadOnly  StreamIDWrapper `json:"$t,omitempty"`
}

Directories

Path Synopsis
internal
key
sse

Jump to

Keyboard shortcuts

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