cardano

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2022 License: GPL-3.0 Imports: 10 Imported by: 17

README

cardano-go

cardano-go is a library for creating go applicactions that interact with the Cardano Blockchain. [WIP]

Installation

$ go get github.com/echovl/cardano-node

Usage

Get protocol parameters
package main

import (
	"fmt"

	"github.com/echovl/cardano-go"
	"github.com/echovl/cardano-go/blockfrost"
)

func main() {
	node := blockfrost.NewNode(cardano.Mainnet, "project-id")

	pparams, err := node.ProtocolParams()
	if err != nil {
		panic(err)
	}

	fmt.Println(pparams)
}
Create simple transaction
package main

import (
	"fmt"

	"github.com/echovl/cardano-go"
)

func main() {
	txBuilder := cardano.NewTxBuilder(&cardano.ProtocolParams{})

	txInput, err := cardano.NewTxInput("txhash", 0, cardano.Coin(2000000))
	if err != nil {
		panic(err)
	}
	txOut, err := cardano.NewTxOutput("addr", cardano.Coin(1300000))
	if err != nil {
		panic(err)
	}

	txBuilder.AddInputs(txInput)
	txBuilder.AddOutputs(txOut)
	txBuilder.SetTTL(100000)
	txBuilder.SetFee(cardano.Coin(160000))
	txBuilder.Sign("addr_sk")

	tx, err := txBuilder.Build()
	if err != nil {
		panic(err)
	}

	fmt.Println(tx.Hex())
}
Set fee and change output
package main

import "github.com/echovl/cardano-go"

func main() {
	txBuilder := cardano.NewTxBuilder(&cardano.ProtocolParams{})

	// Transaction should be signed at this point
	err := txBuilder.AddChangeIfNeeded("addr")
	if err != nil {
		panic(err)
	}
}
Submit transaction
package main

import (
	"fmt"

	"github.com/echovl/cardano-go"
	"github.com/echovl/cardano-go/blockfrost"
)

func main() {
	node := blockfrost.NewNode(cardano.Mainnet, "project-id")

	txHash, err := node.SubmitTx(&cardano.Tx{})
	if err != nil {
		panic(err)
	}

	fmt.Println(txHash)
}
Add transaction metadata
package main

import "github.com/echovl/cardano-go"

func main() {
	txBuilder := cardano.NewTxBuilder(&cardano.ProtocolParams{})

	txBuilder.AddAuxiliaryData(&cardano.AuxiliaryData{
		Metadata: cardano.Metadata{
			0: map[string]interface{}{
				"hello": "cardano-go",
			},
		},
	})
}

cwallet

This package provides a cli cwallet for wallet management. It supports:

  • hierarchical deterministic wallets
  • fetching balances
  • transfering ADA
Configuration

cwallet uses blockfrost as a Node provider. It requires a config file in $XDG_CONFIG_HOME/cwallet.yml. Example:

blockfrost_project_id: "project-id"
Installation
$ git clone github.com/echovl/cardano-go
$ make && sudo make install
Usage

Wallet creation:

$ cwallet new-wallet jhon
mnemonic: various find knee churn bicycle current midnight visit artist help soon flower venture wasp problem

List wallet address:

$ cwallet list-address jhon
PATH                      ADDRESS
m/1852'/1815'/0'/0/0      addr1vxzfs9dj365gcdmv6dwj7auewf624ghwrtduecu37hrxsyst8gvu2

Send ADA:

$ cwallet transfer echo addr1vxzfs9dj365gcdmv6dwj7auewf624ghwrtduecu37hrxsyst8gvu2 2000000
fd3a7d6e9742fd9ddba2bd1740fa994f5c93a4f59bf88dc5f81d8d7413c5b3a9

Documentation

Overview

Package cardano-go is a library for the Cardano Blockchain.

Getting started

The best way to get started working with cardano-go is to use `go get` to add the library.

 go get github.com/echovl/cardano-go
	go get github.com/echovl/cardano-go/node
	go get github.com/echovl/cardano-go/tx

Hello cardano-go

This example shows how you can use cardano-go to query UTXOs.

package main

import (
    "fmt"

    "github.com/echovl/cardano-go/node/blockfrost"
    "github.com/echovl/cardano-go/types"
)

func main() {
    addr, err := types.NewAddress("addr1v9c7flddz5nqj448t78h5mdgau8p9ee24m7n62g2s48akkcjzfhw3")
    if err != nil {
        panic(err)
    }

    node := blockfrost.NewNode(types.Mainnet, "project-id")

    utxos, err := node.UTXOs(addr)
    if err != nil {
        panic(err)
    }

    fmt.Println(utxos)
}

Index

Constants

View Source
const (
	StakeRegistration        CertificateType = 0
	StakeDeregistration                      = 1
	StakeDelegation                          = 2
	PoolRegistration                         = 3
	PoolRetirement                           = 4
	GenesisKeyDelegation                     = 5
	MoveInstantaneousRewards                 = 6
)
View Source
const (
	SingleHostAddr RelayType = 0
	SingleHostName           = 1
	MultiHostName            = 2
)
View Source
const (
	ProtocolMagic = 1097911063
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AddrKeyHash

type AddrKeyHash = Hash28

type Address

type Address struct {
	Network Network
	Type    AddressType
	Pointer Pointer

	Payment StakeCredential
	Stake   StakeCredential
}

Address represents a cardano address.

func NewAddress

func NewAddress(bech string) (Address, error)

NewAddress creates an Address from a bech32 encoded string.

func NewAddressFromBytes

func NewAddressFromBytes(bytes []byte) (Address, error)

NewAddressFromBytes creates an Address from bytes.

func NewBaseAddress

func NewBaseAddress(network Network, payment StakeCredential, stake StakeCredential) (Address, error)

func NewEnterpriseAddress

func NewEnterpriseAddress(network Network, payment StakeCredential) (Address, error)

func NewPointerAddress

func NewPointerAddress(network Network, payment StakeCredential, ptr Pointer) (Address, error)

func (*Address) Bech32

func (addr *Address) Bech32() string

Bech32 returns the Address encoded as bech32.

func (*Address) Bytes

func (addr *Address) Bytes() []byte

func (*Address) MarshalCBOR

func (addr *Address) MarshalCBOR() ([]byte, error)

MarshalCBOR implements cbor.Marshaler.

func (*Address) UnmarshalCBOR

func (addr *Address) UnmarshalCBOR(data []byte) error

UnmarshalCBOR implements cbor.Unmarshaler.

type AddressType

type AddressType byte
const (
	Base       AddressType = 0x00
	Ptr        AddressType = 0x04
	Enterprise AddressType = 0x06
)

type AuxiliaryData

type AuxiliaryData struct {
	Metadata      Metadata    `cbor:"0,keyasint,omitempty"`
	NativeScripts interface{} `cbor:"1,keyasint,omitempty"`
	PlutusScripts interface{} `cbor:"2,keyasint,omitempty"`
}

func (*AuxiliaryData) MarshalCBOR

func (d *AuxiliaryData) MarshalCBOR() ([]byte, error)

MarshalCBOR implements cbor.Marshaler

func (*AuxiliaryData) UnmarshalCBOR

func (d *AuxiliaryData) UnmarshalCBOR(data []byte) error

UnmarshalCBOR implements cbor.Unmarshaler

type Certificate

type Certificate struct {
	Type CertificateType

	// Common fields
	StakeCredential StakeCredential
	PoolKeyHash     PoolKeyHash
	VrfKeyHash      Hash32

	// Pool related fields
	Operator      PoolKeyHash
	Pledge        Coin
	Margin        UnitInterval
	RewardAccount Address
	Owners        []AddrKeyHash
	Relays        []Relay
	PoolMetadata  *PoolMetadata // or null
	Epoch         uint64

	// Genesis fields
	GenesisHash         Hash28
	GenesisDelegateHash Hash28
}

TODO: MoveInstantaneousRewardsCert requires a map with StakeCredential as a key

func (*Certificate) MarshalCBOR

func (c *Certificate) MarshalCBOR() ([]byte, error)

MarshalCBOR implements cbor.Marshaler.

func (*Certificate) UnmarshalCBOR

func (c *Certificate) UnmarshalCBOR(data []byte) error

UnmarshalCBOR implements cbor.Unmarshaler.

type CertificateType

type CertificateType uint

type Coin

type Coin uint64

type Hash28

type Hash28 []byte

func NewHash28

func NewHash28(h string) (Hash28, error)

NewHash28 creates a new Hash28 from a hex encoded string.

func (Hash28) String

func (h Hash28) String() string

String returns the hex encoding representation of a Hash28.

type Hash32

type Hash32 []byte

func NewHash32

func NewHash32(h string) (Hash32, error)

NewHash32 creates a new Hash32 from a hex encoded string.

func (Hash32) String

func (h Hash32) String() string

String returns the hex encoding representation of a Hash32

type Metadata

type Metadata map[uint]interface{}

type Network

type Network byte
const (
	Testnet Network = 0
	Mainnet Network = 1
)

func (Network) String

func (n Network) String() string

type Node

type Node interface {
	// UTxOs returns a list of unspent transaction outputs for a given address
	UTxOs(Address) ([]UTxO, error)

	// Tip returns the node's current tip
	Tip() (*NodeTip, error)

	// SubmitTx submits a transaction to the node using cbor encoding
	SubmitTx(*Tx) (*Hash32, error)

	// ProtocolParams returns the Node's Protocol Parameters
	ProtocolParams() (*ProtocolParams, error)

	// Network returns the node's current network type
	Network() Network
}

Node is the interface required for a Cardano backend/node. A backend/node is used to interact with the Cardano Blockchain, sending transactions and fetching state.

type NodeTip

type NodeTip struct {
	Block uint64
	Epoch uint64
	Slot  uint64
}

type Pointer

type Pointer struct {
	Slot      uint64
	TxIndex   uint64
	CertIndex uint64
}

type PoolKeyHash

type PoolKeyHash = Hash28

type PoolMetadata

type PoolMetadata struct {
	URL  string
	Hash Hash32
	// contains filtered or unexported fields
}

type ProtocolParams

type ProtocolParams struct {
	CoinsPerUTXOWord Coin
	PoolDeposit      Coin
	KeyDeposit       Coin
	MinFeeA          Coin
	MinFeeB          Coin
}

type RationalNumber

type RationalNumber struct {
	P uint64
	Q uint64
	// contains filtered or unexported fields
}

func (*RationalNumber) MarshalCBOR

func (r *RationalNumber) MarshalCBOR() ([]byte, error)

MarshalCBOR implements cbor.Marshaler

func (*RationalNumber) UnmarshalCBOR

func (r *RationalNumber) UnmarshalCBOR(data []byte) error

UnmarshalCBOR implements cbor.Unmarshaler

type Relay

type Relay struct {
	Type    RelayType
	Port    Uint64
	Ipv4    []byte
	Ipv6    []byte
	DNSName string
}

func (*Relay) MarshalCBOR

func (r *Relay) MarshalCBOR() ([]byte, error)

MarshalCBOR implements cbor.Marshaler.

func (*Relay) UnmarshalCBOR

func (r *Relay) UnmarshalCBOR(data []byte) error

UnmarshalCBOR implements cbor.Unmarshaler.

type RelayType

type RelayType uint64

type StakeCredential

type StakeCredential struct {
	Type        StakeCredentialType
	AddrKeyHash AddrKeyHash
	ScriptHash  Hash28
}

func NewAddrKeyCredential

func NewAddrKeyCredential(publicKey crypto.PubKey) (StakeCredential, error)

func NewScriptCredential

func NewScriptCredential(script []byte) (StakeCredential, error)

func (*StakeCredential) Hash

func (s *StakeCredential) Hash() Hash28

func (*StakeCredential) MarshalCBOR

func (s *StakeCredential) MarshalCBOR() ([]byte, error)

MarshalCBOR implements cbor.Marshaler.

func (*StakeCredential) UnmarshalCBOR

func (s *StakeCredential) UnmarshalCBOR(data []byte) error

UnmarshalCBOR implements cbor.Unmarshaler.

type StakeCredentialType

type StakeCredentialType uint64
const (
	AddrKeyCredential StakeCredentialType = 0
	ScriptCredential                      = 1
)

type String

type String *string

func NewString

func NewString(s string) String

type Tx

type Tx struct {
	Body          TxBody
	WitnessSet    WitnessSet
	IsValid       bool
	AuxiliaryData *AuxiliaryData // or null
	// contains filtered or unexported fields
}

func (*Tx) Bytes

func (tx *Tx) Bytes() []byte

Bytes returns the CBOR encoding of the transaction as bytes.

func (*Tx) Hash

func (tx *Tx) Hash() (Hash32, error)

Hash returns the transaction body hash using blake2b.

func (Tx) Hex

func (tx Tx) Hex() string

Hex returns the CBOR encoding of the transaction as hex.

type TxBody

type TxBody struct {
	Inputs  []*TxInput  `cbor:"0,keyasint"`
	Outputs []*TxOutput `cbor:"1,keyasint"`
	Fee     Coin        `cbor:"2,keyasint"`

	// Optionals
	TTL                   Uint64        `cbor:"3,keyasint,omitempty"`
	Certificates          []Certificate `cbor:"4,keyasint,omitempty"`
	Withdrawals           interface{}   `cbor:"5,keyasint,omitempty"` // unsupported
	Update                interface{}   `cbor:"6,keyasint,omitempty"` // unsupported
	AuxiliaryDataHash     *Hash32       `cbor:"7,keyasint,omitempty"`
	ValidityIntervalStart Uint64        `cbor:"8,keyasint,omitempty"`
	Mint                  interface{}   `cbor:"9,keyasint,omitempty"` // unsupported
	ScriptDataHash        *Hash32       `cbor:"10,keyasint,omitempty"`
	Collateral            []TxInput     `cbor:"11,keyasint,omitempty"`
	RequiredSigners       []AddrKeyHash `cbor:"12,keyasint,omitempty"`
	NetworkID             Uint64        `cbor:"13,keyasint,omitempty"`
}

func (*TxBody) AddSignatures

func (body *TxBody) AddSignatures(publicKeys [][]byte, signatures [][]byte) (*Tx, error)

AddSignatures sets the transaction's witness set.

func (*TxBody) Hash

func (body *TxBody) Hash() (Hash32, error)

Hash returns the transaction body hash using blake2b.

type TxBuilder

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

func NewTxBuilder

func NewTxBuilder(protocol *ProtocolParams) *TxBuilder

NewTxBuilder returns a new instance of TxBuilder.

func (*TxBuilder) AddAuxiliaryData

func (tb *TxBuilder) AddAuxiliaryData(data *AuxiliaryData)

func (*TxBuilder) AddChangeIfNeeded

func (tb *TxBuilder) AddChangeIfNeeded(changeAddr string) error

AddChangeIfNeeded calculates the required fee for the transaction and adds an aditional output for the change if there is any. This assumes that the tb inputs and outputs are defined.

func (*TxBuilder) AddInputs

func (tb *TxBuilder) AddInputs(inputs ...*TxInput)

AddInputs adds inputs to the transaction being builded.

func (*TxBuilder) AddOutputs

func (tb *TxBuilder) AddOutputs(outputs ...*TxOutput)

AddOutputs adds outputs to the transaction being builded.

func (*TxBuilder) Build

func (tb *TxBuilder) Build() (*Tx, error)

Build creates a new transaction using the inputs, outputs and keys provided.

func (*TxBuilder) MinFee

func (tb *TxBuilder) MinFee() (Coin, error)

MinFee computes the minimal fee required for the transaction.

func (*TxBuilder) SetFee

func (tb *TxBuilder) SetFee(fee Coin)

SetFee sets the transactions's fee.

func (*TxBuilder) SetTTL

func (tb *TxBuilder) SetTTL(ttl uint64)

SetTtl sets the transaction's time to live.

func (*TxBuilder) Sign

func (tb *TxBuilder) Sign(privateKeys ...string) error

Sign adds signing keys to create signatures for the witness set.

type TxInput

type TxInput struct {
	TxHash Hash32
	Index  uint64
	Amount Coin `cbor:"-"`
	// contains filtered or unexported fields
}

func NewTxInput

func NewTxInput(txHash string, index uint, amount Coin) (*TxInput, error)

NewTxInput creates a new instance of TxInput

type TxOutput

type TxOutput struct {
	Address Address
	Amount  Coin
	// contains filtered or unexported fields
}

func NewTxOutput

func NewTxOutput(addr string, amount Coin) (*TxOutput, error)

NewTxOutput creates a new instance of TxOutput

type UTxO

type UTxO struct {
	TxHash  Hash32
	Spender Address
	Amount  Coin
	Index   uint64
}

type Uint64

type Uint64 *uint64

func NewUint64

func NewUint64(u uint64) Uint64

type UnitInterval

type UnitInterval = RationalNumber

type VKeyWitness

type VKeyWitness struct {
	VKey      crypto.PubKey // ed25519 public key
	Signature []byte        // ed25519 signature
	// contains filtered or unexported fields
}

type WitnessSet

type WitnessSet struct {
	VKeyWitnessSet []VKeyWitness `cbor:"0,keyasint,omitempty"`
}

Directories

Path Synopsis
cli
cmd

Jump to

Keyboard shortcuts

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