package module
Version: v0.0.0-...-fb4d25c Latest Latest

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

Go to latest
Published: Sep 22, 2022 License: Apache-2.0 Imports: 23 Imported by: 0


Dragonchain Golang SDK

Build Status Test Coverage License

Talk to your dragonchain.

⚠️Warning!⚠️ This repository is not currently actively maintained. We will still welcome PRs for updates, but note that parts of this SDK may not be fully working.

These docs are auto-generated.

go get https://github.com/dragonchain/dragonchain-sdk-go
import (

httpClient := &http.Client{}
myDcID := "3f2fef78-0000-0000-0000-9f2971607130";
myCreds := dragonchain.NewCredentials(mydcID, apiKey, apiKeyID, dragonchain.HashSHA256)
client := dragonchain.NewClient(myCreds, baseURL, httpClient)

call, err := await client.GetBlock("block-id-here");

if err != nil {
  fmt.Println("Something went wrong!");
  fmt.Printf("HTTP status code from chain: %s", call.status);
  fmt.Printf("Error response from chain: %s", call.response);
fmt.Println("Successful call!");
fmt.Printf("Block: %s", call.response);
searchResult := client.QueryTransactions(Query.NewQuery("tag=MyAwesomeTransactionTag"))

This is fine for quick tests. For actual production use, you should use the credential ini file or environment variables

newHttpClient := &http.Client{}
client.overrideCredentials("AUTH_KEY_ID","AUTH_KEY", newHttpClient)


In order to use this SDK, you need to have an Auth Key as well as an Auth Key ID for a given dragonchain. This can be loaded into the sdk in various ways, and are checked in the following order of precedence:

  1. The environment variables AUTH_KEY and AUTH_KEY_ID can be set with the appropriate values
  2. Write an ini-style credentials file at ~/.dragonchain/credentials (or on Windows: %LOCALAPPDATA%\dragonchain\credentials) where the section name is the dragonchain id, with values for auth_key and auth_key_id like so:
auth_key_id = JSDMWFUJDVTC
auth_key = n3hlldsFxFdP2De0yMu6A4MFRh1HGzFvn6rJ0ICZzkE


Dragonchain is happy to welcome contributions from the community. You can get started here.



Package dragonchain is used to interact programmatically with dragonchains.



View Source
const (
	HashSHA256     = "SHA256"
	HashSHA3256    = "SHA3-256"
	HashBLAKE2b512 = "BLAKE2b512"

Supported hash functions

View Source
const MaxBulkPutSize = 250

MaxBulkPutSize is the configurable limit of how many txn can be included in a bulk operation.


View Source
var (
	EnvKeyName   = "AUTH_KEY"
	EnvKeyIDName = "AUTH_KEY_ID"

Environment variables used to get chainID and Keys. These can be overridden before calling NewCredentials.

View Source
var BitcoinNetworks = map[string]bool{
	"BTC_MAINNET":  true,
	"BTC_TESTNET3": true,

BitcoinNetworks supported for interchain capabilities

View Source
var ConfigFilePath = ""

ConfigFilePath points to the location of the Configuration file Default on windows '%LOCALAPPDATA%\dragonchain\credentials' Default on linux '$HOME/.dragonchain/credentials' This may be overridden before creating Credentials

View Source
var ErrDCTimeout = errors.New("chain api returned 408 timeout request")

ErrDCTimeout is thrown when the chain API returns a timeout.

View Source
var ErrInvalidLimit = errors.New("invalid limit given, must be positive int")

ErrInvalidLimit is thrown when a negative limit is provided.

View Source
var ErrInvalidOffset = errors.New("invalid offset given, must be positive int")

ErrInvalidOffset is thrown when a negative offset is provided.

View Source
var ErrMaxBulkSizeExceeded = errors.New("too many transactions. transaction count can not be greater than MaxBulkPutSize")

ErrMaxBulkSizeExceeded is thrown when bulk requests exceed MaxBulkPutSize.

View Source
var ErrNoConfigurationFileFound = errors.New("no Configuration file found")

ErrNoConfigurationFileFound is returned if no config was found in ConfigFilePath.

View Source
var ErrNoCredentials = errors.New("no credentials found")

ErrNoCredentials is thrown if no credentials file can be found.

View Source
var ErrUnsupportedHashAlgo = errors.New("hash method not supported")

ErrUnsupportedHashAlgo is thrown when an unsupported hash method is provided.

View Source
var EthereumNetworks = map[string]bool{
	"ETH_MAINNET": true,
	"ETH_ROPSTEN": true,
	"ETC_MAINNET": true,
	"ETC_MORDEN":  true,

EthereumNetworks supported for interchain capabilities


This section is empty.


type AuthKey

type AuthKey struct {
	AuthKey   string
	AuthKeyID string

AuthKey defines the structure of the chain's HMAC authorization keys.

type Authenticator

type Authenticator interface {
	GetDragonchainID() string
	GetAuthorization(httpVerb, path string, timestamp, contentType, content string) string

Authenticator generates the authentication header for requests to chain.

type BitcoinOutputs

type BitcoinOutputs struct {
	ScriptPubKey string  `json:"scriptPubKey"`
	Value        float32 `json:"value,omitempty"`

BitcoinOutputs are optional outputs for a bitcoin transaction.

type BitcoinTransaction

type BitcoinTransaction struct {
	Network         string           `json:"network"`
	SatoshisPerByte float32          `json:"satoshisPerByte,omitempty"`
	Data            string           `json:"data,omitempty"`
	ChangeAddress   string           `json:"changeAddress,omitempty"`
	Outputs         []BitcoinOutputs `json:"outputs,omitempty"`

BitcoinTransaction represents a transaction on a bitcoin chain.

type Block

type Block struct {
	Version       string           `json:"version"`
	DCRN          string           `json:"dcrn"`
	Header        BlockHeader      `json:"header"`
	Proof         BlockProof       `json:"proof"`
	Transactions  []Transaction    `json:"transactions,omitempty"`   // L1 only
	Validation    L1Verification   `json:"validation,omitempty"`     // L2 only
	L2Validations L2Verification   `json:"l2-validations,omitempty"` // L3 only
	L3Validations []L3Verification `json:"l3-validations,omitempty"` // L4 only
	L4Blocks      []string         `json:"l4-blocks,omitempty"`      // L5 only

Block defines the structure of a finalized block.

type BlockHeader

type BlockHeader struct {
	DcID       string `json:"dc_id"`
	DDSS       string `json:"current_ddss"`
	Level      int    `json:"level"`
	BlockID    string `json:"block_id"`
	Timestamp  string `json:"timestamp"`
	PrevProof  string `json:"prev_proof"`
	PreviousID string `json:"prev_id"`
	// L4 only headers
	L1BlockID string `json:"l1_block_id,omitempty"`
	L1ChainID string `json:"l1_dc_id,omitempty"`
	L1Proof   string `json:"l1_proof,omitempty"`

BlockHeader defines the structure of a block's header

type BlockProof

type BlockProof struct {
	Scheme string `json:"scheme"`
	Proof  string `json:"proof,omitempty"`
	Nonce  int    `json:"nonce,omitempty"` // Used for PoW chains.
	// L5 only proofs
	BlockLastSentAt int64    `json:"block_last_sent_at,omitempty"`
	TxnHash         []string `json:"transaction_hash,omitempty"`
	Network         string   `json:"network,omitempty"`

BlockProof defines the structure of a signature proof.

type Client

type Client struct {
	// contains filtered or unexported fields

Client defines the structure of the DragonchainSDK client.

func NewClient

func NewClient(creds Authenticator, apiBaseURL string, httpClient httpClient) *Client

NewClient creates a new instance of client. By default, it does not generate usable credentials. Accepts Authenticator credentials created using dragonchain.NewCredentials. apiBaseUrl is optional and for use when interacting with chains outside of the managed service. httpClient is optional if you wish to designate custom headers for requests.

func (*Client) CreateAPIKey

func (client *Client) CreateAPIKey() (*Response, error)

CreateAPIKey to access chain with.

func (*Client) CreateBitcoinTransaction

func (client *Client) CreateBitcoinTransaction(btcTransaction *BitcoinTransaction) (*Response, error)

CreateBitcoinTransaction creates an interchain btc transaction using this chain's interchain address.

func (*Client) CreateBulkTransaction

func (client *Client) CreateBulkTransaction(txn []*CreateTransaction) (_ *Response, err error)

CreateBulkTransaction sends many transactions to a chain in a single HTTP request.

func (*Client) CreateEthereumTransaction

func (client *Client) CreateEthereumTransaction(ethTransaction *EthereumTransaction) (*Response, error)

CreateEthereumTransaction creates an interchain eth transaction using this chain's interchain address.

func (*Client) CreateFactor

func (client *Client) CreateFactor(factor string) (_ *Response, err error)

CreateFactor creates a new factor.

func (*Client) CreateSmartContract

func (client *Client) CreateSmartContract(contract *ContractConfiguration) (_ *Response, err error)

CreateSmartContract creates a new smart contract on the chain.

func (*Client) CreateTransaction

func (client *Client) CreateTransaction(txn *CreateTransaction) (_ *Response, err error)

CreateTransaction creates a transaction on the chain.

func (*Client) CreateTransactionType

func (client *Client) CreateTransactionType(transactionType string, customIndexes []CustomIndexStructure) (_ *Response, err error)

CreateTransactionType creates a new transaction type.

func (*Client) DeleteAPIKey

func (client *Client) DeleteAPIKey(apiKey string) (*Response, error)

DeleteAPIKey from chain.

func (*Client) DeleteContract

func (client *Client) DeleteContract(smartContractID string) (*Response, error)

DeleteContract removes a contract from the chain.

func (*Client) DeleteFactor

func (client *Client) DeleteFactor(id string) (*Response, error)

DeleteFactor removes the specified factor.

func (*Client) DeleteTransactionType

func (client *Client) DeleteTransactionType(transactionType string) (*Response, error)

DeleteTransactionType removes the specified transaction type. It will not affect transactions that have already been processed.

func (*Client) GetAPIKey

func (client *Client) GetAPIKey(keyID string) (*Response, error)

GetAPIKey returns an HMAC API key.

func (*Client) GetBlock

func (client *Client) GetBlock(blockID string) (*Response, error)

GetBlock returns a block by ID.

func (*Client) GetPublicBlockchainAddress

func (client *Client) GetPublicBlockchainAddress() (*Response, error)

GetPublicBlockchainAddress returns a dictionary of this chain's interchain addresses. This method is only supported on L1 and L5 chains.

func (*Client) GetSmartContract

func (client *Client) GetSmartContract(smartContractID, transactionType string) (*Response, error)

GetSmartContract returns details on a smart contract by ID or transactionType. If both contractID and transactionType are provided, contractID is used.

func (*Client) GetSmartContractObject

func (client *Client) GetSmartContractObject(key, smartContractID string) (*Response, error)

GetSmartContractObject returns a specific key from a smart contract's heap. If SCName is not provided, the SDK will try to pull it from the environment.

func (*Client) GetSmartContractSecret

func (client *Client) GetSmartContractSecret(secretName string) (_ string, err error)

GetSmartContractSecret pulls a secret for the running smart contract from the chain.

func (*Client) GetStatus

func (client *Client) GetStatus() (*Response, error)

GetStatus returns the chain's status, such as Active or Updating.

func (*Client) GetTransaction

func (client *Client) GetTransaction(txnID string) (*Response, error)

GetTransaction gets a transaction from the chain by id.

func (*Client) GetTransactionType

func (client *Client) GetTransactionType(transactionType string) (*Response, error)

GetTransactionType returns a transaction type on chain by its name.

func (*Client) GetVerifications

func (client *Client) GetVerifications(blockID string, level int) (*Response, error)

GetVerifications returns a block's verification at a specific level of DragonNet.

func (*Client) ListAPIKeys

func (client *Client) ListAPIKeys() (*Response, error)

ListAPIKeys for a chain.

func (*Client) ListFactors

func (client *Client) ListFactors() (*Response, error)

ListFactors lists out all registered factors for a chain.

func (*Client) ListSmartContractObjects

func (client *Client) ListSmartContractObjects(folder, smartContractID string) (*Response, error)

ListSmartContractObjects lists out all keys from a smart contract's heap. Optionally, folder can be provided to only list a subset of keys.

func (*Client) ListTransactionTypes

func (client *Client) ListTransactionTypes() (*Response, error)

ListTransactionTypes lists out all registered transaction types for a chain.

func (*Client) QueryBlocks

func (client *Client) QueryBlocks(query *Query) (*Response, error)

QueryBlocks gets all blocks matching the given query.

func (*Client) QuerySmartContracts

func (client *Client) QuerySmartContracts(query *Query) (*Response, error)

QuerySmartContracts returns a list of matching contracts on the chain.

func (*Client) QueryTransactions

func (client *Client) QueryTransactions(query *Query) (*Response, error)

QueryTransactions gets all transactions matching the given query on the chain.

func (*Client) UpdateSmartContract

func (client *Client) UpdateSmartContract(contract *ContractConfiguration) (*Response, error)

UpdateSmartContract updates an existing contract with a new configuration. Configuration details that aren't provided will not be changed.

func (*Client) UpdateTransactionType

func (client *Client) UpdateTransactionType(transactionType string, customIndexes []CustomIndexStructure) (*Response, error)

UpdateTransactionType updates a given transaction type.

type Configuration

type Configuration struct {
	DefaultDcID string
	AuthKeys    map[string]*AuthKey

Configuration defines the SDK configuration of chainID and AuthKeys.

func GetCredentialConfigs

func GetCredentialConfigs() (*Configuration, error)

GetCredentialConfigs returns

type Contract

type Contract struct {
	TransactionType string                 `json:"txn_type"`
	ContractID      string                 `json:"id"`
	Status          ContractStatus         `json:"status"`
	Image           string                 `json:"image"`
	AuthKeyID       string                 `json:"auth_key_id"`
	ImageDigest     string                 `json:"image_digest"`
	Cmd             string                 `json:"cmd"`
	Args            []string               `json:"args"`
	Env             map[string]interface{} `json:"env"`
	ExistingSecrets []string               `json:"existing_secrets"`
	Cron            string                 `json:"cron"`
	Seconds         string                 `json:"seconds"`
	ExecutionOrder  string                 `json:"execution_order"`

Contract defines the structure of a deployed smart contract.

type ContractConfiguration

type ContractConfiguration struct {
	TransactionType           string                 `json:"txn_type"`
	Image                     string                 `json:"image"`
	Cmd                       string                 `json:"cmd"`
	Args                      []string               `json:"args"`
	ExecutionOrder            string                 `json:"execution_order"`
	Enabled                   bool                   `json:"enabled"`
	EnvironmentVariables      []string               `json:"env"`
	Secrets                   map[string]interface{} `json:"secrets"`
	ScheduleIntervalInSeconds int                    `json:"seconds"`
	CronExpression            string                 `json:"cron"`
	RegistryCredentials       string                 `json:"auth"`

ContractConfiguration defines the structure of a request to create a new smart contract.

type ContractStatus

type ContractStatus struct {
	State     string `json:"state"`
	Msg       string `json:"msg"`
	Timestamp string `json:"timestamp"`

ContractStatus defines the status object for contracts.

type CreateTransaction

type CreateTransaction struct {
	Version         string                 `json:"version"`
	TransactionType string                 `json:"txn_type"`
	Tag             string                 `json:"tag"`
	Payload         map[string]interface{} `json:"payload"`

CreateTransaction defines the transaction schema for dragonchain.

type Credentials

type Credentials struct {
	// contains filtered or unexported fields

Credentials implements the Authenticator interface to generate authentication headers.

func NewCredentials

func NewCredentials(dcID, authKey, authKeyID, algorithm string) (*Credentials, error)

NewCredentials uses the provided values to create a new Credentials instance for the given chain.

func (*Credentials) GetAuthorization

func (creds *Credentials) GetAuthorization(httpVerb, path string, timestamp, contentType, content string) string

GetAuthorization returns the current chain's authorization as a string.

func (*Credentials) GetDragonchainID

func (creds *Credentials) GetDragonchainID() string

GetDragonchainID returns the current chain's ID.

type CustomIndexStructure

type CustomIndexStructure struct {
	Key  string `json:"key"`
	Path string `json:"path"`

CustomIndexStructure defines the valid format of custom indexes on a transaction type.

type ErrFailedRequest

type ErrFailedRequest struct {
	Status  int    `json:"status"`
	Message string `json:"message"`

ErrFailedRequest defines the structure of an error returned by the chain.

func NewRequestError

func NewRequestError(resp *http.Response) *ErrFailedRequest

NewRequestError returns a formatted ErrFailedRequest object from the chain's http response.

func (ErrFailedRequest) Error

func (err ErrFailedRequest) Error() string

type EthereumTransaction

type EthereumTransaction struct {
	Network  string `json:"network"`
	To       string `json:"to"`
	Value    string `json:"value"`
	Data     string `json:"data,omitempty"`
	GasPrice string `json:"gasPrice,omitempty"`
	Gas      string `json:"gas,omitempty"`

EthereumTransaction represents a transaction on an ethereum chain.

type Factor

type Factor struct {
	Version string `json:"version,omitempty"`
	Id      string `json:"fct_id,omitempty"`
	Factor  string `json:"factor,omitempty"`

Factor defines the complete factor on a dragonchain.

type GetSmartContractHeap

type GetSmartContractHeap struct {
	SCName string `json:"sc_name"`
	Key    string `json:"key"`

GetSmartContractHeap defines the request format for getting a key from a Smart Contract's heap.

type Header struct {
	TransactionType string `json:"txn_type"`
	DcID            string `json:"dc_id"`
	TxnID           string `json:"txn_id"`
	BlockID         string `json:"block_id"`
	TimeStamp       string `json:"timestamp"`
	Tag             string `json:"tag"`
	Invoker         string `json:"invoker"`

Header defines the HTTP headers required for dragonchain authentication

type L1Verification

type L1Verification struct {
	BlockID       string `json:"block_id"`
	ChainID       string `json:"dc_id"`
	StrippedProof string `json:"stripped_proof"`
	Transactions  string `json:"transactions"`

L1Verification is a representation of an L1 block verified by an L2 chain.

type L2Verification

type L2Verification struct {
	Clouds    []string
	Count     string
	DDSS      string `json:"ddss"`
	L1BlockID string `json:"l1_block_id"`
	L1ChainID string `json:"l1_dc_id"`
	L1Proof   string `json:"l1_proof"`
	Regions   []string

L2Verification is a representation of an L2 block verified by an L3 chain.

type L3Verification

type L3Verification struct {
	L3ChainID string `json:"l3_dc_id"`
	L3BlockID string `json:"l3_block_id"`
	L3Proof   string `json:"l3_proof"`
	Valid     bool   `json:"valid"`

L3Verification is a representation of an L3 block verified by an L4 chain.

type L4Verification

type L4Verification struct {
	L1ChainID string `json:"l1_dc_id"`
	L1BlockID string `json:"l1_block_id"`
	L4ChainID string `json:"l4_dc_id"`
	L4BlockID string `json:"l4_block_id"`
	L4Proof   string `json:"l4_proof"`

L4Verification is a representation of an L4 block verified by an L4 chain.

type Proof

type Proof struct {
	Full     string `json:"full"`
	Stripped string `json:"stripped"`

Proof defines the proof object returned by L1 dragonchains.

type Query

type Query struct {
	Query  string `json:"q"`
	Sort   string `json:"sort"`
	Offset int    `json:"offset"`
	Limit  int    `json:"limit"`

Query defines the structure of a lucene query on the Dragonchain.

func NewQuery

func NewQuery(query, sort string, offset int, limit int) (*Query, error)

NewQuery constructs a Query based on provided parameters.

type Response

type Response struct {
	OK       bool        `json:"ok"`
	Status   int         `json:"status"`
	Response interface{} `json:"response"`

Response defines the standard response all chains will use.

type Transaction

type Transaction struct {
	Version string                 `json:"version"`
	DCRN    string                 `json:"dcrn"`
	Header  Header                 `json:"header"`
	Payload map[string]interface{} `json:"payload"`
	Proof   Proof                  `json:"proof"`

Transaction defines the complete transaction on a dragonchain.

type TransactionType

type TransactionType struct {
	Version       string                 `json:"version"`
	Type          string                 `json:"txn_type"`
	CustomIndexes []CustomIndexStructure `json:"custom_indexes"`
	IsContract    bool                   `json:"is_contract"`

TransactionType defines the properties of a valid Dragonchain transaction type.

type Verification

type Verification struct {
	L2 []Block `json:"2,omitempty"`
	L3 []Block `json:"3,omitempty"`
	L4 []Block `json:"4,omitempty"`
	L5 []Block `json:"5,omitempty"`

Verification is a representation of the verification object for a block.

Jump to

Keyboard shortcuts

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