zvcgo

package module
v0.0.0-...-9a9acc1 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2020 License: GPL-3.0 Imports: 23 Imported by: 0

README

ZVChain API library for Go

GoDoc

This library provides simple access to data structures and API calls to an ZVChain RPC server.

Install

go get -u github.com/zvchain/zvcgo

Basic usage

api := zvcgo.NewApi("http://node1.zvchain.io")

height, _ := api.BlockHeight()
fmt.Printf("Current block height: %d", height)

Transfer ZVC Example

package main

import (
	"fmt"
	"github.com/zvchain/zvcgo"
)

func main() {
	mnemonic, _ := zvcgo.NewMnemonic(zvcgo.Mnemonic12WordBitSize)
	fmt.Println("Mnemonic: ", mnemonic)
	wallet := zvcgo.NewWallet(mnemonic)
	if wallet == nil {
		panic("wrong mnemonic")
	}
	acc, _ := wallet.DeriveAccount(0)
	// acc, err := zvcgo.NewAccountFromString("you private key")
	fmt.Println("account address: ", acc.Address().String())
	api := zvcgo.NewApi("endpoint host")
	api.SetSigner(acc)
	asset, _ := zvcgo.NewAssetFromString("123 zvc")
	target, _ := zvcgo.NewAddressFromString("you address")
	tx := zvcgo.NewTransferTransaction(*acc.Address(), target, asset, []byte{})
	nonce, _ := api.GetNonce(*acc.Address())
	tx.SetNonce(nonce)
	hash, err := api.SignAndSendTransaction(tx)
	if err != nil {
		panic(err)
	}
	fmt.Println("transaction hash: ", hash.String())
}


License

GPL

Documentation

Index

Constants

View Source
const (
	DefaultGasPrice        = 500
	DefaultGasLimit        = 3000
	CodeBytePrice          = 19073 //1.9073486328125
	CodeBytePricePrecision = 10000
)
View Source
const (
	TransactionTypeTransfer       = 0
	TransactionTypeContractCreate = 1
	TransactionTypeContractCall   = 2
)
View Source
const (
	Ra = 1

	ZVC = 1000000000
)
View Source
const AddrPrefix = "zv"
View Source
const AddressLength = 32
View Source
const HashPrefix = "0x"
View Source
const Idlength = 32
View Source
const Mnemonic12WordBitSize = 128
View Source
const Mnemonic24WordBitSize = 256
View Source
const SignLength = 65 //length of signature,32 bytes r & 32 bytes s & 1 byte recid.
View Source
const ZVCPath = "m/44'/372'/0'/0/%d" // 372

Variables

View Source
var (
	ErrPassword    = fmt.Errorf("password error")
	ErrUnlocked    = fmt.Errorf("please unlock the Account first")
	ErrUnConnected = fmt.Errorf("please connect to one node first")
	ErrInternal    = fmt.Errorf("internal error")
)
View Source
var (
	ErrorInvalidAssetString   = errors.New("invalid asset string")
	ErrorInvalidAddressString = errors.New("invalid address string")
	ErrorInvalidPrivateKey    = errors.New("invalid private key")
	ErrorInvalid0xString      = errors.New("invalid hex String")
	ErrorInvalidZVString      = errors.New("invalid address String")
	ErrorSignerNotFound       = errors.New("signer not found")
	ErrorSourceEmpty          = errors.New("source should not be empty")
)
View Source
var (
	NoSignerError = errors.New("signer should be set before send a no-sign transaction")
)

Functions

func Decode

func Decode(input string) ([]byte, error)

Decode decodes a hex string with 0x prefix.

func DecodeZV

func DecodeZV(input string) ([]byte, error)

Decode decodes a hex string with zv prefix.

func Encode

func Encode(b []byte) string

Encode encodes b as a hex string with 0x prefix.

func NewMnemonic

func NewMnemonic(bitSize int) (string, error)

NewMnemonic Generate Mnemonic, returns of number of words depends on input: bitSize(eg: Mnemonic12WordBitSize, Mnemonic24WordBitSize)

func ToAddrHex

func ToAddrHex(b []byte) string

ToZvHex converts the input byte array to a hex string

func ValidateAddress

func ValidateAddress(addr string) bool

Types

type ABI

type ABI struct {
	FuncName string        `json:"func_name"`
	Args     []interface{} `json:"args"`
}

type ABIVerify

type ABIVerify struct {
	FuncName string
	Args     []string
}

ABIVerify stores the contract function name and args types, in order to facilitate the abi verify

type Account

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

func NewAccount

func NewAccount(privateKey []byte) (*Account, error)

func NewAccountFromString

func NewAccountFromString(key string) (*Account, error)

func (Account) Address

func (a Account) Address() *Address

func (Account) PrivateKey

func (a Account) PrivateKey() *PrivateKey

func (Account) PublicKey

func (a Account) PublicKey() *PublicKey

func (Account) Sign

func (a Account) Sign(tx Transaction) (*Sign, error)

type AccountMsg

type AccountMsg struct {
	Balance   *big.Int               `json:"balance"`
	Nonce     uint64                 `json:"nonce"`
	Type      uint32                 `json:"type"`
	CodeHash  string                 `json:"code_hash"`
	ABI       []ABIVerify            `json:"abi"`
	Code      string                 `json:"code"`
	StateData map[string]interface{} `json:"state_data"`
}

type Address

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

func NewAddressFromBytes

func NewAddressFromBytes(bs []byte) (addr Address, err error)

func NewAddressFromString

func NewAddressFromString(s string) (addr Address, err error)

func (Address) Bytes

func (a Address) Bytes() []byte

func (*Address) MarshalJSON

func (a *Address) MarshalJSON() ([]byte, error)

func (Address) String

func (a Address) String() string

func (*Address) UnmarshalJSON

func (a *Address) UnmarshalJSON(input []byte) error

type Api

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

func NewApi

func NewApi(url string) *Api

func (Api) Balance

func (api Api) Balance(address Address) (float64, error)

func (Api) BlockHeight

func (api Api) BlockHeight() (uint64, error)

func (Api) GetBlockByHash

func (api Api) GetBlockByHash(hash Hash) (*Block, error)

func (Api) GetBlockByHeight

func (api Api) GetBlockByHeight(height uint64) (*Block, error)

func (Api) GetBlockHashByHeight

func (api Api) GetBlockHashByHeight(height uint64) (*Hash, error)

func (Api) GetNonce

func (api Api) GetNonce(address Address) (uint64, error)

func (Api) GetTransactionByHash

func (api Api) GetTransactionByHash(hash Hash) (*RawTransaction, error)

func (Api) MinerInfo

func (api Api) MinerInfo(address Address, detail interface{}) (*MinerStakeDetails, error)

func (Api) SendTransaction

func (api Api) SendTransaction(tx Transaction) (*Hash, error)

func (*Api) SetSigner

func (api *Api) SetSigner(signer Signer)

func (Api) SignAndSendTransaction

func (api Api) SignAndSendTransaction(tx Transaction) (*Hash, error)

type Asset

type Asset struct {
	Value uint64
}

func NewAssetFromString

func NewAssetFromString(s string) (Asset, error)

func (Asset) KRa

func (a Asset) KRa() uint64

func (Asset) MRa

func (a Asset) MRa() uint64

func (Asset) Ra

func (a Asset) Ra() uint64

func (Asset) ZVC

func (a Asset) ZVC() uint64

type Block

type Block struct {
	Height      uint64    `json:"height" mapstructure:"height"`
	Hash        Hash      `json:"hash" mapstructure:"hash"`
	PreHash     Hash      `json:"pre_hash" mapstructure:"pre_hash"`
	CurTime     time.Time `json:"cur_time" mapstructure:"cur_time,squash"`
	PreTime     time.Time `json:"pre_time" mapstructure:"pre_time,squash"`
	Castor      ID        `json:"castor" mapstructure:"castor"`
	Group       Hash      `json:"group_id" mapstructure:"group_id"`
	Prove       string    `json:"prove" mapstructure:"prove"`
	TotalQN     uint64    `json:"total_qn" mapstructure:"total_qn"`
	Qn          uint64    `json:"qn" mapstructure:"qn"`
	TxNum       uint64    `json:"txs" mapstructure:"txs"`
	StateRoot   Hash      `json:"state_root" mapstructure:"state_root"`
	TxRoot      Hash      `json:"tx_root" mapstructure:"tx_root"`
	ReceiptRoot Hash      `json:"receipt_root" mapstructure:"receipt_root"`
	ProveRoot   Hash      `json:"prove_root" mapstructure:"prove_root"`
	Random      string    `json:"random" mapstructure:"random"`
}

type BlockDetail

type BlockDetail struct {
	Block
	GenRewardTx   RewardTransaction   `json:"gen_reward_tx"`
	Trans         []SimpleTx          `json:"trans"`
	BodyRewardTxs []RewardTransaction `json:"body_reward_txs"`
	PreTotalQN    uint64              `json:"pre_total_qn"`
}

type Contract

type Contract struct {
	Code            string          `json:"code"`
	ContractName    string          `json:"contract_name"`
	ContractAddress *common.Address `json:"-"`
}

type ContractCallTransaction

type ContractCallTransaction struct {
	RawTransaction
}

func (*ContractCallTransaction) ToRawTransaction

func (tt *ContractCallTransaction) ToRawTransaction() RawTransaction

type ContractCreateTransaction

type ContractCreateTransaction struct {
	RawTransaction
}

func NewContractCallTransaction

func NewContractCallTransaction(from, to Address, value Asset, funcName string, params ...interface{}) *ContractCreateTransaction

func NewContractCreateTransaction

func NewContractCreateTransaction(from Address, code string, contractName string, value Asset) *ContractCreateTransaction

func (*ContractCreateTransaction) ToRawTransaction

func (tt *ContractCreateTransaction) ToRawTransaction() RawTransaction

type ErrorResult

type ErrorResult struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

ErrorResult is rpc requestGzv error returned variable parameter

type Event

type Event struct {
	Deleted bool
	Height  uint64
	TxHash  Hash
	Index   uint64
	Message map[string]interface{}
	Default []interface{}
}

type Hash

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

func (Hash) Bytes

func (h Hash) Bytes() []byte

func (*Hash) MarshalJSON

func (h *Hash) MarshalJSON() ([]byte, error)

func (Hash) String

func (h Hash) String() string

func (*Hash) UnmarshalJSON

func (h *Hash) UnmarshalJSON(input []byte) error

type ID

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

func (*ID) MarshalJSON

func (id *ID) MarshalJSON() ([]byte, error)

func (ID) Serialize

func (id ID) Serialize() []byte

Serialize convert ID to byte slice (LittleEndian)

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(data []byte) error

type KeyBag

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

func NewKeyBag

func NewKeyBag() *KeyBag

func (KeyBag) AvailableAddresses

func (kb KeyBag) AvailableAddresses() []*Address

func (KeyBag) AvailablePublicKeys

func (kb KeyBag) AvailablePublicKeys() []*PublicKey

func (*KeyBag) ImportPrivateKey

func (kb *KeyBag) ImportPrivateKey(key []byte) (err error)

func (*KeyBag) ImportPrivateKeyFromString

func (kb *KeyBag) ImportPrivateKeyFromString(k string) (err error)

func (KeyBag) Sign

func (kb KeyBag) Sign(tx Transaction) (*Sign, error)

type MinerStakeDetails

type MinerStakeDetails struct {
	Overview []*MortGage               `json:"overview,omitempty"`
	Details  map[string][]*StakeDetail `json:"details,omitempty"`
}

type MortGage

type MortGage struct {
	Stake              uint64 `json:"stake"`
	ApplyHeight        uint64 `json:"apply_height"`
	Type               string `json:"type"`
	Status             string `json:"miner_status"`
	StatusUpdateHeight uint64 `json:"status_update_height"`
}

type PrivateKey

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

func NewPrivateKey

func NewPrivateKey(privateKey []byte) (*PrivateKey, error)

func (PrivateKey) Bytes

func (key PrivateKey) Bytes() []byte

Bytes serialize private key to bytes

func (*PrivateKey) ImportPrivateKey

func (key *PrivateKey) ImportPrivateKey(privateKey []byte) (err error)

ImportPrivateKey import private key by bytes of private key

func (PrivateKey) PublicKey

func (key PrivateKey) PublicKey() *PublicKey

func (PrivateKey) String

func (key PrivateKey) String() string

String serialize private key to hex string

type PublicKey

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

func (PublicKey) Address

func (pk PublicKey) Address() *Address

func (PublicKey) String

func (pk PublicKey) String() string

String serialize publicKey key to hex string

type RPCReqObj

type RPCReqObj struct {
	Method  string        `json:"method"`
	Params  []interface{} `json:"params"`
	Jsonrpc string        `json:"jsonrpc"`
	ID      uint          `json:"id"`
}

RPCReqObj is complete rpc requestGzv body

type RPCResObj

type RPCResObj struct {
	Result RawMessage   `json:"result,omitempty"`
	Error  *ErrorResult `json:"error,omitempty"`
}

type RawMessage

type RawMessage []byte

func (RawMessage) MarshalJSON

func (m RawMessage) MarshalJSON() ([]byte, error)

MarshalJSON returns m as the JSON encoding of m.

func (*RawMessage) UnmarshalJSON

func (m *RawMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON sets *m to a copy of data.

type RawTransaction

type RawTransaction struct {
	Data   []byte   `json:"data"`
	Value  uint64   `json:"value"`
	Nonce  uint64   `json:"nonce"`
	Target *Address `json:"target"`
	Type   int8     `json:"type"`

	GasLimit uint64 `json:"gas_limit"`
	GasPrice uint64 `json:"gas_price"`
	Hash     Hash   `json:"hash"`

	ExtraData []byte   `json:"extra_data"`
	Sign      *Sign    `json:"sign"`
	Source    *Address `json:"source"`
}

func (RawTransaction) GenHash

func (t RawTransaction) GenHash() Hash

func (*RawTransaction) SetData

func (t *RawTransaction) SetData(data []byte) *RawTransaction

func (*RawTransaction) SetExtraData

func (t *RawTransaction) SetExtraData(extraData []byte) *RawTransaction

func (*RawTransaction) SetGasLimit

func (t *RawTransaction) SetGasLimit(gasLimit uint64) *RawTransaction

func (*RawTransaction) SetGasPrice

func (t *RawTransaction) SetGasPrice(gasPrice uint64) *RawTransaction

func (*RawTransaction) SetNonce

func (t *RawTransaction) SetNonce(nonce uint64) *RawTransaction

func (RawTransaction) ToRawTransaction

func (t RawTransaction) ToRawTransaction() RawTransaction

type Result

type Result struct {
	Message string      `json:"message"`
	Status  int         `json:"status"`
	Data    interface{} `json:"data"`
}

Result is rpc requestGzv successfully returns the variable parameter

type RewardTransaction

type RewardTransaction struct {
	Hash         Hash   `json:"hash"`
	BlockHash    Hash   `json:"block_hash"`
	GroupSeed    Hash   `json:"group_id"`
	TargetIDs    []ID   `json:"target_ids"`
	Value        uint64 `json:"value"`
	PackFee      uint64 `json:"pack_fee"`
	StatusReport string `json:"status_report"`
	Success      bool   `json:"success"`
}

type Sign

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

Sign Data struct

func (Sign) Bytes

func (s Sign) Bytes() []byte

func (Sign) MarshalJSON

func (s Sign) MarshalJSON() ([]byte, error)

type Signer

type Signer interface {
	Sign(tx Transaction) (*Sign, error)
}

type SimpleTx

type SimpleTx struct {
	Data   []byte   `json:"data"`
	Value  float64  `json:"value"`
	Nonce  uint64   `json:"nonce"`
	Source *Address `json:"source"`
	Target *Address `json:"target"`
	Type   int8     `json:"type"`

	GasLimit uint64 `json:"gas_limit"`
	GasPrice uint64 `json:"gas_price"`
	Hash     Hash   `json:"hash"`

	ExtraData string `json:"extra_data"`
}

type StakeDetail

type StakeDetail struct {
	Value        uint64 `json:"value"`
	UpdateHeight uint64 `json:"update_height"`
	MType        string `json:"m_type"`
	Status       string `json:"stake_status"`
}

type Transaction

type Transaction interface {
	ToRawTransaction() RawTransaction
}

type TransferTransaction

type TransferTransaction struct {
	RawTransaction
}

func NewTransferTransaction

func NewTransferTransaction(from, to Address, value Asset, data []byte) *TransferTransaction

func (*TransferTransaction) ToRawTransaction

func (tt *TransferTransaction) ToRawTransaction() RawTransaction

type Wallet

type Wallet struct {
	KeyBag
	// contains filtered or unexported fields
}

func NewWallet

func NewWallet(mnemonic string) *Wallet

func (Wallet) DeriveAccount

func (m Wallet) DeriveAccount(index int) (*Account, error)

DeriveAccount derive account by index

Jump to

Keyboard shortcuts

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