core

package
v0.1.8-alpha.4 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2019 License: GPL-3.0 Imports: 19 Imported by: 13

Documentation

Index

Constants

View Source
const (
	// AccountTypeBalance represents a balance account
	AccountTypeBalance = iota

	// AccountTypeRepo represents a repo account
	AccountTypeRepo
)
View Source
const (
	// EventNewBlock represents an event about a new block
	// that was successfully added to the main chain
	EventNewBlock = "event.newBlock"

	// EventProcessBlock represents an event about
	// a block that was relayed by a peer.
	EventProcessBlock = "event.relayedBlock"

	// EventNewTransaction represents an event about a new
	// transaction that was received
	EventNewTransaction = "event.newTx"

	// EventTransactionReceived indicates that a transaction
	// has been received.
	EventTransactionReceived = "event.txReceived"

	// EventTransactionPooled indicates that a transaction
	// has been added to the transaction pool
	EventTransactionPooled = "event.txPooled"

	// EventTransactionInvalid indicates that a transaction
	// has been declared invalid
	EventTransactionInvalid = "event.txInvalid"

	// EventOrphanBlock represents an event about an orphan block.
	EventOrphanBlock = "event.orphanBlock"

	// EventFoundBlock represents an event about a
	// block that has just been mined by the client
	EventFoundBlock = "event.foundBlock"

	// EventPeerChainInfo indicates an event about a peer's chain info
	EventPeerChainInfo = "event.newPeerChainInfo"

	// EventBlockProcessed describes an event about
	// a processed block
	EventBlockProcessed = "event.blockProcessed"
)

Variables

View Source
var (
	// ErrBlockNotFound means a block was not found
	ErrBlockNotFound = fmt.Errorf("block not found")

	// ErrMetadataNotFound means the blockchain metadata was not found
	ErrMetadataNotFound = fmt.Errorf("metadata not found")

	// ErrChainAlreadyKnown means a chain is already known to the blockchain manager
	ErrChainAlreadyKnown = fmt.Errorf("chain already known")

	// ErrChainNotFound means a chain does not exist
	ErrChainNotFound = fmt.Errorf("chain not found")

	// ErrBlockExists means a block exists
	ErrBlockExists = fmt.Errorf("block already exists")

	// ErrBlockRejected means a block has been rejected
	ErrBlockRejected = fmt.Errorf("rejected block")

	// ErrOrphanBlock means a block is orphaned
	ErrOrphanBlock = fmt.Errorf("orphan block")

	// ErrVeryStaleBlock means a block is stable and has a height not equal to the current tip
	ErrVeryStaleBlock = fmt.Errorf("very stale block")

	// ErrBlockStateRootInvalid means the state root on a block header does is not valid after
	// transactions are executed.
	ErrBlockStateRootInvalid = fmt.Errorf("block state root is not valid")

	// ErrBlockFailedValidation means a block failed validation
	ErrBlockFailedValidation = fmt.Errorf("block failed validation")

	// ErrAccountNotFound refers to a missing account
	ErrAccountNotFound = fmt.Errorf("account not found")

	// ErrBestChainUnknown means the best/main chain is yet to be determined
	ErrBestChainUnknown = fmt.Errorf("best chain unknown")

	// ErrTxNotFound means a transaction was not found
	ErrTxNotFound = fmt.Errorf("transaction not found")

	// ErrDecodeFailed means an attempt to decode data failed
	ErrDecodeFailed = func(msg string) error {
		if msg != "" {
			msg = ": " + msg
		}
		return fmt.Errorf("decode attempt failed%s", msg)
	}

	// ErrChainParentNotFound means a chain's parent was not found
	ErrChainParentNotFound = fmt.Errorf("chain parent not found")

	// ErrChainParentBlockNotFound means a chain's parent block was not found
	ErrChainParentBlockNotFound = fmt.Errorf("chain parent block not found")

	// ErrAbortedDueToSyncDisablement means an operation
	// was aborted due to block synchronization being disabled
	ErrAbortedDueToSyncDisablement = fmt.Errorf("aborted. Synchronization has been disabled")
)
View Source
var (
	// ErrTxVerificationFailed means a transaction signature could not be verified
	ErrTxVerificationFailed = fmt.Errorf("signature verification failed")

	// ErrTxInsufficientFee means fee is insufficient
	ErrTxInsufficientFee = fmt.Errorf("insufficient fee")

	// ErrTxLowValue means transaction value is less than or equal to zero
	ErrTxLowValue = fmt.Errorf("value must be greater than zero")

	//ErrTxTypeUnknown means transaction type is unknown
	ErrTxTypeUnknown = fmt.Errorf("unknown transaction type")
)
View Source
var (
	// TxTypeBalance represents a transaction from an account to another account
	TxTypeBalance int64 = 0x1

	// TxTypeAlloc represents a transaction to alloc coins to an account
	TxTypeAlloc int64 = 0x2
)
View Source
var Base58CheckVersionTxPayload byte = 95

Base58CheckVersionTxPayload is the base58 encode version adopted for compressed transaction payload

Functions

func BlockSign

func BlockSign(b types.Block, privKey string) ([]byte, error)

BlockSign signs a block. Expects private key in base58Check encoding

func BlockVerify

func BlockVerify(block *Block) error

BlockVerify checks whether a block's signature is valid. Expect block.Header.CreatorPubKey and block.Sig to be set.

func TxSign

func TxSign(tx *Transaction, privKey string) ([]byte, error)

TxSign signs a transaction. Expects private key in base58Check encoding

func TxVerify

func TxVerify(tx *Transaction) error

TxVerify checks whether a transaction's signature is valid. Expect tx.SenderPubKey and tx.Sig to be set.

Types

type Account

type Account struct {
	Type        int32        `json:"type" msgpack:"type"`
	Address     util.String  `json:"address" msgpack:"address"`
	Balance     util.String  `json:"balance" msgpack:"balance"`
	Nonce       uint64       `json:"nonce" msgpack:"nonce"`
	AccountInfo *AccountInfo `json:"accountInfo,omitempty" msgpack:"accountInfo"`
}

Account represents an entity on the network.

func (*Account) GetAddress

func (a *Account) GetAddress() util.String

GetAddress gets the address

func (*Account) GetBalance

func (a *Account) GetBalance() util.String

GetBalance gets the balance

func (*Account) GetNonce

func (a *Account) GetNonce() uint64

GetNonce gets the nonce

func (*Account) IncrNonce

func (a *Account) IncrNonce()

IncrNonce increments the nonce by 1

func (*Account) SetBalance

func (a *Account) SetBalance(b util.String)

SetBalance sets the balance

type AccountInfo

type AccountInfo struct {
}

AccountInfo represents the data specific to a regular account

type Addr

type Addr struct {
	Addresses []*Address `json:"addresses" msgpack:"addresses"`
}

Addr is used to send peer addresses in response to a GetAddr

type Address

type Address struct {
	Address   util.NodeAddr `json:"address" msgpack:"address"`
	Timestamp int64         `json:"timestamp" msgpack:"timestamp"`
}

Address represents a peer's address

type ArgGetMinedBlock

type ArgGetMinedBlock struct {
	Limit         int    `mapstructure:"limit"`
	LastHash      string `mapstructure:"lastHash"`
	CreatorPubKey string `mapstructure:"creatorPubKey"`
}

ArgGetMinedBlock represents arguments for fetching mined blocks

type BestBlockInfo

type BestBlockInfo struct {
	BestBlockHash            util.Hash
	BestBlockTotalDifficulty *big.Int
	BestBlockNumber          uint64
}

BestBlockInfo represent best block heard by the engine from other peers

type Block

type Block struct {
	Header       *Header        `json:"header" msgpack:"header"`
	Transactions []*Transaction `json:"transactions" msgpack:"transactions"`
	Hash         util.Hash      `json:"hash" msgpack:"hash"`
	Sig          []byte         `json:"sig" msgpack:"sig"`

	// Broadcaster is the peer responsible
	// for sending this block.
	Broadcaster Engine `json:"-" msgpack:"-"`

	// types.ValidationContext can be used to alter
	// the way the block is validated
	ValidationContexts []types.ValidationContext `json:"-" msgpack:"-"`
}

Block represents a block

func (*Block) ComputeHash

func (b *Block) ComputeHash() util.Hash

ComputeHash returns the SHA256 hash of the header as a hex string prefixed by '0x'

func (*Block) DecodeMsgpack

func (b *Block) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements msgpack.CustomDecoder

func (*Block) EncodeMsgpack

func (b *Block) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements msgpack.CustomEncoder

func (*Block) GetBroadcaster

func (b *Block) GetBroadcaster() Engine

GetBroadcaster gets the originator

func (*Block) GetBytes

func (b *Block) GetBytes() []byte

GetBytes gets the bytes representation of the block.

func (*Block) GetBytesNoHashSig

func (b *Block) GetBytesNoHashSig() []byte

GetBytesNoHashSig gets the bytes representation of the block without the hash and signature included.

func (*Block) GetBytesNoTxs

func (b *Block) GetBytesNoTxs() []byte

GetBytesNoTxs gets the bytes representation of the block without the adding the transactions' bytes

func (*Block) GetHash

func (b *Block) GetHash() util.Hash

GetHash returns the block's hash

func (*Block) GetHashAsHex

func (b *Block) GetHashAsHex() string

GetHashAsHex returns the block's hex equivalent of its hash preceded by 0x

func (*Block) GetHeader

func (b *Block) GetHeader() types.Header

GetHeader gets the block's header

func (*Block) GetNumber

func (b *Block) GetNumber() uint64

GetNumber returns the number

func (*Block) GetSignature

func (b *Block) GetSignature() []byte

GetSignature gets the signature

func (*Block) GetSize

func (b *Block) GetSize() int64

GetSize gets the byte size

func (*Block) GetSizeNoTxs

func (b *Block) GetSizeNoTxs() int64

GetSizeNoTxs gets the byte size

func (*Block) GetTransactions

func (b *Block) GetTransactions() (txs []types.Transaction)

GetTransactions gets the transactions

func (*Block) GetValidationContexts

func (b *Block) GetValidationContexts() []types.ValidationContext

GetValidationContexts gets the validation contexts

func (*Block) ReplaceHeader

func (b *Block) ReplaceHeader(h types.Header) types.Block

ReplaceHeader creates a copy of h and sets as the blocks header

func (*Block) SetBroadcaster

func (b *Block) SetBroadcaster(o Engine)

SetBroadcaster sets the originator

func (*Block) SetHash

func (b *Block) SetHash(h util.Hash)

SetHash sets the hash

func (*Block) SetHeader

func (b *Block) SetHeader(h types.Header)

SetHeader sets the block header

func (*Block) SetSig

func (b *Block) SetSig(sig []byte)

SetSig sets the signature

func (*Block) SetSignature

func (b *Block) SetSignature(sig []byte)

SetSignature sets the signature

func (*Block) SetValidationContexts

func (b *Block) SetValidationContexts(ctxs ...types.ValidationContext)

SetValidationContexts sets the validation contexts

type BlockBodies

type BlockBodies struct {
	Blocks []*BlockBody
}

BlockBodies represents a collection of block bodies

type BlockBody

type BlockBody struct {
	Header       *Header        `json:"header" msgpack:"header"`
	Transactions []*Transaction `json:"transactions" msgpack:"transactions"`
	Hash         util.Hash      `json:"hash" msgpack:"hash"`
	Sig          []byte         `json:"sig" msgpack:"sig"`
}

BlockBody represents the body of a block

type BlockHashes

type BlockHashes struct {
	Hashes []util.Hash
}

BlockHashes represents a message containing block hashes as a response to GetBlockHeaders

type BlockInfo

type BlockInfo struct {
	Hash util.Hash `json:"hash" msgpack:"hash"`
}

BlockInfo describes a block

type BlockOk

type BlockOk struct {
	Ok bool `json:"ok" msgpack:"ok"`
}

BlockOk describes a block hash received in BlockInfo as accepted/ok or not

type BroadcastPeers

type BroadcastPeers struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

BroadcastPeers is a type that contains randomly chosen peers that messages will be broadcast to.

func NewBroadcastPeers

func NewBroadcastPeers() *BroadcastPeers

NewBroadcastPeers creates a new BroadcastPeers instance

func (*BroadcastPeers) Add

func (b *BroadcastPeers) Add(p Engine)

Add adds a peer

func (*BroadcastPeers) Clear

func (b *BroadcastPeers) Clear()

Clear removes all peers

func (*BroadcastPeers) Has

func (b *BroadcastPeers) Has(p Engine) bool

Has checks whether a peer exists

func (*BroadcastPeers) LastUpdated

func (b *BroadcastPeers) LastUpdated() time.Time

LastUpdated is the last time the peers were updated

func (*BroadcastPeers) Len

func (b *BroadcastPeers) Len() int

Len returns the number of peers

func (*BroadcastPeers) Peers

func (b *BroadcastPeers) Peers() (peers []Engine)

Peers returns the stored peers

func (*BroadcastPeers) PeersID

func (b *BroadcastPeers) PeersID() (ids []string)

PeersID returns the id of the stored peers

func (*BroadcastPeers) Remove

func (b *BroadcastPeers) Remove(peer Engine)

Remove removes a peer

type ChainInfo

type ChainInfo struct {
	ID                util.String `json:"id" msgpack:"json"`
	ParentChainID     util.String `json:"parentChainID" msgpack:"parentChainID"`
	ParentBlockNumber uint64      `json:"parentBlockNumber" msgpack:"parentBlockNumber"`
	Timestamp         int64       `json:"timestamp" msgpack:"timestamp"`
}

ChainInfo describes a chain

func (*ChainInfo) GetID

func (c *ChainInfo) GetID() util.String

GetID returns the ID

func (*ChainInfo) GetParentBlockNumber

func (c *ChainInfo) GetParentBlockNumber() uint64

GetParentBlockNumber returns the parent block number

func (*ChainInfo) GetParentChainID

func (c *ChainInfo) GetParentChainID() util.String

GetParentChainID returns the ID

func (*ChainInfo) GetTimestamp

func (c *ChainInfo) GetTimestamp() int64

GetTimestamp returns the timestamp

type Engine

type Engine interface {

	// SetEventEmitter set the event emitter
	// used to broadcast/receive events
	SetEventEmitter(*emitter.Emitter)

	// DB is the laoded client database
	DB() elldb.DB

	// GetTxPool returns the transaction pool
	GetTxPool() types.TxPool

	// StringID is the peer ID of engine's
	// network host as a string
	StringID() string

	// ShortID is the short version the value
	// return by StringID. It meant to be
	// used for logging.
	ShortID() string

	// ID returns the peer ID of the engine's
	// network knows
	ID() peer.ID

	// GetLastSeen returns the time the engine
	// (or peer) was last seen
	GetLastSeen() time.Time

	// SetLastSeen sets the time the engine
	// (or peer) was last seen
	SetLastSeen(time.Time)

	// CreatedAt returns the time this engine
	// was first created.
	CreatedAt() time.Time

	// SetCreatedAt sets the time this engine
	// was first created
	SetCreatedAt(t time.Time)

	// IsSame checks whether the engine has
	// the same ID as another engine
	IsSame(Engine) bool

	// IsSameID is like IsSame but accepts a string
	IsSameID(id string) bool

	// IsHardcodedSeed indicates that the engine
	// was not discovered through the gossip protocol
	// but injected into the codebase
	IsHardcodedSeed() bool

	// GetAddress returns the listening address
	// of the host network
	GetAddress() util.NodeAddr

	// Connected checks whether the engine is connected
	// to the local node
	Connected() bool

	// Connect connects to rn
	Connect(rn Engine) error

	// IsNetworkDisabled checks whether networking is disabled
	IsNetworkDisabled() bool

	// GetBlockchain returns the blockchain instance
	GetBlockchain() types.Blockchain

	// SetBlockchain stores a reference to the
	// blockchain instance
	SetBlockchain(types.Blockchain)

	// ProdMode checks whether the engine
	// is in production mode
	ProdMode() bool

	// TestMode checks whether the engine
	// is in test mode
	TestMode() bool

	// IsInbound checks whether the engine (or peer) is
	// considered an inbound connection to the local node
	IsInbound() bool

	// IsInbound checks whether the engine (or peer) is
	// considered an outbound connection to the local node
	SetInbound(v bool)

	// HasStopped checks whether the peer has stopped
	HasStopped() bool

	// GetHost returns the engine's network host
	GetHost() host.Host

	// Gossip returns the gossip manager
	Gossip() Gossip

	// NewRemoteNode creates a node that will be used to
	// represent a remote peer.
	NewRemoteNode(address util.NodeAddr) Engine

	// GetCfg returns the engine configuration
	GetCfg() *config.EngineConfig

	// GetEventEmitter gets the event emitter
	GetEventEmitter() *emitter.Emitter

	// GetHistory returns the general items cache
	GetHistory() *cache.Cache

	// AddToPeerStore adds the ID of the engine
	// to the peerstore
	AddToPeerStore(node Engine) Engine

	// SetHardcoded sets the hardcoded seed state
	// of the engine.
	SetHardcoded(v bool)

	// SetGossipManager sets the gossip manager
	SetGossipManager(m Gossip)

	// GetName returns the pet name of the node
	GetName() string

	// SetName sets the name of the node
	SetName(name string)

	// GetSyncMode returns the sync mode
	GetSyncMode() SyncMode
}

Engine represents node functionalities not provided by the protocol. This can include peer discovery, configuration, APIs etc.

type GetAddr

type GetAddr struct {
}

GetAddr is used to request for peer addresses from other peers

type GetBlockBodies

type GetBlockBodies struct {
	Hashes []util.Hash
}

GetBlockBodies represents a message to fetch block bodies belonging to the given hashes

type GetBlockHashes

type GetBlockHashes struct {
	Locators  []util.Hash `json:"hash" msgpack:"hash"`
	Seek      util.Hash   `json:"seek" msgpack:"seek"`
	MaxBlocks int64       `json:"maxBlocks" msgpack:"maxBlocks"`
}

GetBlockHashes represents a message requesting for headers of blocks. The locator is used to compare with a remote node to determine which blocks to send back.

type Gossip

type Gossip interface {

	// Address messages
	OnAddr(s net.Stream, rp Engine) error
	RelayAddresses(addrs []*Address) []error

	// Block messages
	BroadcastBlock(block types.Block, remotePeers []Engine) []error
	OnBlockInfo(s net.Stream, rp Engine) error
	OnBlockBody(s net.Stream, rp Engine) error
	RequestBlock(rp Engine, blockHash util.Hash) error
	OnRequestBlock(s net.Stream, rp Engine) error
	SendGetBlockHashes(rp Engine, locators []util.Hash, seek util.Hash) (*BlockHashes, error)
	OnGetBlockHashes(s net.Stream, rp Engine) error
	SendGetBlockBodies(rp Engine, hashes []util.Hash) (*BlockBodies, error)
	OnGetBlockBodies(s net.Stream, rp Engine) error

	// Handshake messages
	SendHandshake(rp Engine) error
	OnHandshake(s net.Stream, rp Engine) error

	// GetAddr messages
	SendGetAddrToPeer(remotePeer Engine) ([]*Address, error)
	SendGetAddr(remotePeers []Engine) error
	OnGetAddr(s net.Stream, rp Engine) error

	// Ping messages
	SendPing(remotePeers []Engine)
	SendPingToPeer(remotePeer Engine) error
	OnPing(s net.Stream, rp Engine) error

	// Node advertisement
	SelfAdvertise(connectedPeers []Engine) int

	// Transaction messages
	BroadcastTx(tx types.Transaction, remotePeers []Engine) error
	OnTx(s net.Stream, rp Engine) error

	// PickBroadcasters selects N random addresses from
	// the given slice of addresses and caches them to
	// be used as broadcasters.
	// They are returned on subsequent calls and only
	// renewed when there are less than N addresses or the
	// cache is over 24 hours since it was last updated.
	PickBroadcasters(cache *BroadcastPeers, addresses []*Address, n int) *BroadcastPeers

	// GetBroadcasters returns the broadcasters
	GetBroadcasters() *BroadcastPeers
	GetRandBroadcasters() *BroadcastPeers

	// NewStream creates a stream for a given protocol
	// ID and between the local peer and the given remote peer.
	NewStream(remotePeer Engine, msgVersion string) (net.Stream,
		context.CancelFunc, error)

	// CheckRemotePeer performs validation against the remote peer.
	CheckRemotePeer(ws *WrappedStream, rp Engine) error

	// Handle wrappers a protocol handler providing an
	// interface to perform pre and post handling operations.
	Handle(handler func(s net.Stream, remotePeer Engine) error) func(net.Stream)
}

Gossip represent messages and interactions between nodes

type Handshake

type Handshake struct {
	Version                  string    `json:"version" msgpack:"version"`
	BestBlockHash            util.Hash `json:"bestBlockHash" msgpack:"bestBlockHash"`
	BestBlockTotalDifficulty *big.Int  `json:"bestBlockTD" msgpack:"bestBlockTD"`
	BestBlockNumber          uint64    `json:"bestBlockNumber" msgpack:"bestBlockNumber"`
	Name                     string    `json:"name" msgpack:"name"`
}

Handshake represents the first message between peers

func (*Handshake) DecodeMsgpack

func (h *Handshake) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements msgpack.CustomDecoder

func (*Handshake) EncodeMsgpack

func (h *Handshake) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements msgpack.CustomEncoder

type Header struct {
	Number           uint64          `json:"number" msgpack:"number"`
	Nonce            util.BlockNonce `json:"nonce" msgpack:"nonce"`
	Timestamp        int64           `json:"timestamp" msgpack:"timestamp"`
	CreatorPubKey    util.String     `json:"creatorPubKey" msgpack:"creatorPubKey"`
	ParentHash       util.Hash       `json:"parentHash" msgpack:"parentHash"`
	StateRoot        util.Hash       `json:"stateRoot" msgpack:"stateRoot"`
	TransactionsRoot util.Hash       `json:"transactionsRoot" msgpack:"transactionsRoot"`
	Difficulty       *big.Int        `json:"difficulty" msgpack:"difficulty"`
	TotalDifficulty  *big.Int        `json:"totalDifficulty" msgpack:"totalDifficulty"`
	Extra            []byte          `json:"extra" msgpack:"extra"`
}

Header represents the header of a block

func (*Header) ComputeHash

func (h *Header) ComputeHash() util.Hash

ComputeHash returns the SHA256 hash of the header

func (*Header) Copy

func (h *Header) Copy() types.Header

Copy creates a copy of the header

func (*Header) DecodeMsgpack

func (h *Header) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements msgpack.CustomDecoder

func (*Header) EncodeMsgpack

func (h *Header) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements msgpack.CustomEncoder

func (*Header) GetBytes

func (h *Header) GetBytes() []byte

GetBytes return the bytes representation of the header

func (*Header) GetCreatorPubKey

func (h *Header) GetCreatorPubKey() util.String

GetCreatorPubKey gets the public key of the creator

func (*Header) GetDifficulty

func (h *Header) GetDifficulty() *big.Int

GetDifficulty gets the difficulty

func (*Header) GetExtra

func (h *Header) GetExtra() []byte

GetExtra gets the extra data

func (*Header) GetHashNoNonce

func (h *Header) GetHashNoNonce() util.Hash

GetHashNoNonce gets the hash of the header without the nonce included in the computation

func (*Header) GetNonce

func (h *Header) GetNonce() util.BlockNonce

GetNonce gets the nonce

func (*Header) GetNumber

func (h *Header) GetNumber() uint64

GetNumber returns the header number which is the block number

func (*Header) GetParentHash

func (h *Header) GetParentHash() util.Hash

GetParentHash gets the parent hash

func (*Header) GetStateRoot

func (h *Header) GetStateRoot() util.Hash

GetStateRoot gets the state root

func (*Header) GetTimestamp

func (h *Header) GetTimestamp() int64

GetTimestamp gets the time stamp

func (*Header) GetTotalDifficulty

func (h *Header) GetTotalDifficulty() *big.Int

GetTotalDifficulty gets the total difficulty

func (*Header) GetTransactionsRoot

func (h *Header) GetTransactionsRoot() util.Hash

GetTransactionsRoot gets the transaction root

func (*Header) SetCreatorPubKey

func (h *Header) SetCreatorPubKey(key util.String)

SetCreatorPubKey sets the creator's public key

func (*Header) SetDifficulty

func (h *Header) SetDifficulty(diff *big.Int)

SetDifficulty sets the difficulty

func (*Header) SetNonce

func (h *Header) SetNonce(nonce util.BlockNonce)

SetNonce sets the nonce

func (*Header) SetNumber

func (h *Header) SetNumber(n uint64)

SetNumber sets the number

func (*Header) SetParentHash

func (h *Header) SetParentHash(hash util.Hash)

SetParentHash sets parent hash

func (*Header) SetStateRoot

func (h *Header) SetStateRoot(sr util.Hash)

SetStateRoot sets the state root

func (*Header) SetTimestamp

func (h *Header) SetTimestamp(timestamp int64)

SetTimestamp sets the timestamp

func (*Header) SetTotalDifficulty

func (h *Header) SetTotalDifficulty(td *big.Int)

SetTotalDifficulty sets the total difficulty

func (*Header) SetTransactionsRoot

func (h *Header) SetTransactionsRoot(txRoot util.Hash)

SetTransactionsRoot sets the transaction root

type Intro

type Intro struct {
	PeerID string `json:"id" msgpack:"id"`
}

Intro represents a message describing a peer's ID.

func (*Intro) Hash

func (m *Intro) Hash() util.Hash

Hash returns the hash representation

type InvokeArgs

type InvokeArgs struct {
	Func   string            `json:"func" msgpack:"func"`
	Params map[string][]byte `json:"params" msgpack:"params"`
}

InvokeArgs describes a function to be executed by a blockcode

func (*InvokeArgs) Bytes

func (m *InvokeArgs) Bytes() []byte

Bytes returns the byte equivalent

type MinedBlock

type MinedBlock struct {
	Number        uint64      `json:"number" msgpack:"number"`
	Timestamp     int64       `json:"timestamp" msgpack:"timestamp"`
	CreatorPubKey util.String `json:"creatorPubKey" msgpack:"creatorPubKey"`
	TxCount       uint        `json:"txCount" msgpack:"txCount"`
	TotalFees     string      `json:"totalFees" msgpack:"totalFees"`
	Hash          util.Hash   `json:"hash" msgpack:"hash"`
}

MinedBlock briefly describes a mined block. It is used as the data structure for indexing blocks mined on a node.

type Ping

type Ping struct {
	BestBlockHash            util.Hash `json:"bestBlockHash" msgpack:"bestBlockHash"`
	BestBlockTotalDifficulty *big.Int  `json:"bestBlockTD" msgpack:"bestBlockTD"`
	BestBlockNumber          uint64    `json:"bestBlockNumber" msgpack:"bestBlockNumber"`
}

Ping represents a ping message

func (*Ping) DecodeMsgpack

func (p *Ping) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements msgpack.CustomDecoder

func (*Ping) EncodeMsgpack

func (p *Ping) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements msgpack.CustomEncoder

type Pong

type Pong struct {
	BestBlockHash            util.Hash `json:"bestBlockHash" msgpack:"bestBlockHash"`
	BestBlockTotalDifficulty *big.Int  `json:"bestBlockTD" msgpack:"bestBlockTD"`
	BestBlockNumber          uint64    `json:"bestBlockNumber" msgpack:"bestBlockNumber"`
}

Pong represents a pong message

func (*Pong) DecodeMsgpack

func (p *Pong) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements msgpack.CustomDecoder

func (*Pong) EncodeMsgpack

func (p *Pong) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements msgpack.CustomEncoder

type Reject

type Reject struct {
	Message   string `json:"message" msgpack:"message"`
	Code      int32  `json:"code" msgpack:"code"`
	Reason    string `json:"reason" msgpack:"reason"`
	ExtraData []byte `json:"extraData" msgpack:"extraData"`
}

Reject defines information about a rejected action

type RequestBlock

type RequestBlock struct {
	Hash string `json:"hash" msgpack:"hash"`
}

RequestBlock represents a message requesting for a block

type SyncMode

type SyncMode interface {
	// IsDisabled checks whether synchronization has been disabled
	IsDisabled() bool

	// Enable enables the sync mode
	Enable()

	// Disable disables the sync mode
	Disable()
}

SyncMode describes how the state of the node should be synchronized with external nodes.

type SyncStateInfo

type SyncStateInfo struct {
	TargetTD           *big.Int `json:"targetTotalDifficulty"`
	TargetChainHeight  uint64   `json:"targetChainHeight" msgpack:"targetChainHeight"`
	CurrentTD          *big.Int `json:"currentTotalDifficulty" msgpack:"currentTotalDifficulty"`
	CurrentChainHeight uint64   `json:"currentChainHeight" msgpack:"currentChainHeight"`
	ProgressPercent    float64  `json:"progressPercent" msgpack:"progressPercent"`
}

SyncStateInfo describes the current state and progress of ongoing blockchain synchronization

type Transaction

type Transaction struct {
	Type         int64       `json:"type" msgpack:"type"`
	Nonce        uint64      `json:"nonce" msgpack:"nonce"`
	To           util.String `json:"to" msgpack:"to"`
	From         util.String `json:"from" msgpack:"from"`
	SenderPubKey util.String `json:"senderPubKey" msgpack:"senderPubKey"`
	Value        util.String `json:"value" msgpack:"value"`
	Timestamp    int64       `json:"timestamp" msgpack:"timestamp"`
	Fee          util.String `json:"fee" msgpack:"fee"`
	InvokeArgs   *InvokeArgs `json:"invokeArgs,omitempty" msgpack:"invokeArgs"`
	Sig          []byte      `json:"sig" msgpack:"sig"`
	Hash         util.Hash   `json:"hash" msgpack:"hash"`
}

Transaction represents a transaction

func NewTransaction

func NewTransaction(txType int64, nonce uint64, to util.String,
	senderPubKey util.String, value util.String,
	fee util.String, timestamp int64) (tx *Transaction)

NewTransaction creates a new transaction

func NewTx

func NewTx(txType int64, nonce uint64, to util.String, senderKey *crypto.Key, value util.String, fee util.String, timestamp int64) (tx *Transaction)

NewTx creates a new, signed transaction

func (*Transaction) Bytes

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

Bytes converts a transaction to bytes equivalent

func (*Transaction) ComputeHash

func (tx *Transaction) ComputeHash() util.Hash

ComputeHash returns the SHA256 hash of the transaction.

func (*Transaction) GetBytesNoHashAndSig

func (tx *Transaction) GetBytesNoHashAndSig() []byte

GetBytesNoHashAndSig converts a transaction to bytes equivalent but omits the hash and signature in the result.

func (*Transaction) GetFee

func (tx *Transaction) GetFee() util.String

GetFee gets the value

func (*Transaction) GetFrom

func (tx *Transaction) GetFrom() util.String

GetFrom gets the address of sender

func (*Transaction) GetHash

func (tx *Transaction) GetHash() util.Hash

GetHash returns the hash of tx

func (*Transaction) GetID

func (tx *Transaction) GetID() string

GetID returns the hex representation of Hash()

func (*Transaction) GetNonce

func (tx *Transaction) GetNonce() uint64

GetNonce gets the nonce

func (*Transaction) GetSenderPubKey

func (tx *Transaction) GetSenderPubKey() util.String

GetSenderPubKey gets the sender public key

func (*Transaction) GetSignature

func (tx *Transaction) GetSignature() []byte

GetSignature gets the signature

func (*Transaction) GetSizeNoFee

func (tx *Transaction) GetSizeNoFee() int64

GetSizeNoFee returns the virtual size of the transaction by summing up the size of field contents except the `fee` field. The value does not represent the true size of the transaction on disk. It is main required for computing minimum fees etc.

func (*Transaction) GetTimestamp

func (tx *Transaction) GetTimestamp() int64

GetTimestamp gets the timestamp

func (*Transaction) GetTo

func (tx *Transaction) GetTo() util.String

GetTo gets the address of receiver

func (*Transaction) GetType

func (tx *Transaction) GetType() int64

GetType gets the transaction type

func (*Transaction) GetValue

func (tx *Transaction) GetValue() util.String

GetValue gets the value

func (*Transaction) SetFrom

func (tx *Transaction) SetFrom(from util.String)

SetFrom sets the sender

func (*Transaction) SetHash

func (tx *Transaction) SetHash(h util.Hash)

SetHash sets the hash

func (*Transaction) SetSenderPubKey

func (tx *Transaction) SetSenderPubKey(pk util.String)

SetSenderPubKey sets the sender public key

func (*Transaction) SetSignature

func (tx *Transaction) SetSignature(s []byte)

SetSignature sets the signature

func (*Transaction) SetTimestamp

func (tx *Transaction) SetTimestamp(t int64)

SetTimestamp set the unix timestamp

func (*Transaction) SetValue

func (tx *Transaction) SetValue(v util.String)

SetValue gets the value

func (*Transaction) Sign

func (tx *Transaction) Sign(privKey string) ([]byte, error)

Sign the transaction

func (*Transaction) ToBase58

func (tx *Transaction) ToBase58() string

ToBase58 returns base58 encoded equivalent of the transaction

type TxInfo

type TxInfo struct {
	Hash util.Hash `json:"hash" msgpack:"hash"`
}

TxInfo describes a transaction

type TxOk

type TxOk struct {
	Ok bool `json:"ok" msgpack:"ok"`
}

TxOk describes a transaction hash received in TxInfo as accepted/ok or not

type WrappedStream

type WrappedStream struct {
	Stream net.Stream
	Extra  map[string]interface{}
}

WrappedStream encapsulates a stream along with extra data and behaviours

Jump to

Keyboard shortcuts

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