core

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2017 License: LGPL-3.0 Imports: 22 Imported by: 0

README

core

Core blockchain data structures, logical codes are all located in this directory.

Documentation

Index

Constants

View Source
const (
	// AddressDataLength the length of data of address in byte.
	AddressDataLength = 20

	// AddressChecksumLength the checksum of address in byte.
	AddressChecksumLength = 4

	// AddressLength the length of address in byte.
	AddressLength = AddressDataLength + AddressChecksumLength
)
View Source
const (
	// TestNetID chain id for test net.
	TestNetID = 1

	// EagleNebula chain id for 1.x
	EagleNebula = 1 << 4

	// Tail Key in storage
	Tail = "blockchain_tail"
)
View Source
const (
	TxPayloadBinaryType = "binary"
	TxPayloadDeployType = "deploy"
	TxPayloadCallType   = "call"
	TxPayloadVoteType   = "vote"
)

const

View Source
const (
	MessageTypeNewBlock = "newblock"
	MessageTypeNewTx    = "newtx"
)

MessageType

Variables

View Source
var (
	// ErrInvalidAddress invalid address error.
	ErrInvalidAddress = errors.New("address: invalid address")

	// ErrInvalidAddressDataLength invalid data length error.
	ErrInvalidAddressDataLength = errors.New("address: invalid address data length")
)
View Source
var (
	// BlockHashLength define a const of the length of Hash of Block in byte.
	BlockHashLength = 32

	// BlockReward given to coinbase
	// TODO: block reward should calculates dynamic.
	BlockReward = util.NewUint128FromInt(16)
)
View Source
var (
	ErrInvalidBlockHash      = errors.New("invalid block hash")
	ErrInvalidBlockStateRoot = errors.New("invalid block state root hash")
	ErrInvalidBlockTxsRoot   = errors.New("invalid block txs root hash")
	ErrInvalidChainID        = errors.New("invalid transaction chainID")
	ErrDuplicatedTransaction = errors.New("duplicated transaction")
	ErrSmallTransactionNonce = errors.New("cannot accept a transaction with smaller nonce")
	ErrLargeTransactionNonce = errors.New("cannot accept a transaction with too bigger nonce")
)

Errors in block

View Source
var (
	// ErrInsufficientBalance insufficient balance error.
	ErrInsufficientBalance = errors.New("insufficient balance")

	// ErrInvalidSignature the signature is not sign by from address.
	ErrInvalidSignature = errors.New("invalid transaction signature")

	// ErrInvalidTransactionHash invalid hash.
	ErrInvalidTransactionHash = errors.New("invalid transaction hash")
)
View Source
var (
	ErrInvalidTxPayloadType   = errors.New("invalid transaction data payload type")
	ErrInvalidContractAddress = errors.New("invalid contract address")
)

ErrInvalidTxPayloadType

View Source
var (
	ErrDuplicatedBlock = errors.New("duplicated block")
)

Errors in block

Functions

func CheckGenesisBlock added in v0.3.0

func CheckGenesisBlock(block *Block) bool

CheckGenesisBlock if a block is a genesis block

func NewCallSCPayload added in v0.3.0

func NewCallSCPayload(function, args string) ([]byte, error)

NewCallSCPayload return a call SCPayload.

func NewDeploySCPayload added in v0.3.0

func NewDeploySCPayload(source, args string) ([]byte, error)

NewDeploySCPayload return SCPayload.

Types

type Account added in v0.2.0

type Account struct {
	UserBalance       *util.Uint128
	UserNonce         uint64
	UserGlobalStorage *trie.BatchTrie

	ContractOwner           *Address
	ContractTransactionHash Hash
	ContractLocalStorage    *trie.BatchTrie
	// contains filtered or unexported fields
}

Account info in state Trie

func NewAccount added in v0.3.0

func NewAccount(storage storage.Storage) *Account

NewAccount create a new account

func (*Account) AddBalance added in v0.3.0

func (acc *Account) AddBalance(value *util.Uint128)

AddBalance to an account

func (*Account) FromProto added in v0.2.0

func (acc *Account) FromProto(msg proto.Message) error

FromProto converts proto Account to domain Account

func (*Account) IncreNonce added in v0.3.0

func (acc *Account) IncreNonce()

IncreNonce by 1

func (*Account) SetContractOwner added in v0.3.0

func (acc *Account) SetContractOwner(address *Address)

SetContractOwner with a address

func (*Account) SetContractTransactionHash added in v0.3.0

func (acc *Account) SetContractTransactionHash(code []byte)

SetContractTransactionHash in account

func (*Account) SubBalance added in v0.3.0

func (acc *Account) SubBalance(value *util.Uint128)

SubBalance from an account

func (*Account) ToProto added in v0.2.0

func (acc *Account) ToProto() (proto.Message, error)

ToProto converts domain Account to proto Account

type Address

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

Address Similar to Bitcoin and Ethereum, Nebulas also adopts elliptic curve algorithm as its basic encryption algorithm for Nebulas accounts. A user’s private key is a randomly generated 256-bit binary number, based on which a 64-byte public key can be generated via elliptic curve multiplication. Bitcoin and Ethereum addresses are computed by public key via the deterministic Hash algorithm, and the difference between them lies in: Bitcoin address has the checksum design aiming to prevent a user from sending Bitcoins to a wrong user account accidentally due to entry of several incorrect characters; while Ethereum doesn’t have such checksum design.

We believe that checksum design is reasonable from the perspective of users, so Nebulas address also includes checksum, for which the specific calculation method is provided as follows:

Data = sha3_256(Public Key)[-20:]
CheckSum = sha3_256(Data)[0:4]
Address = "0x" + Hex(Data + CheckSum)

The last 20 bytes of SHA3-256 digest of a public key serve as the major component of an address, for which another SHA3-256 digest should be conducted and the first 4 bytes should be used as a checksum, which is equivalent to the practice of adding a 4-byte checksum to the end of an Ethereum address. For example:

The standard address of Alice’s Ethereum wallet is 0xdf4d22611412132d3e9bd322f82e2940674ec1bc; The final address of Nebulas Wallet should be: 0xdf4d22611412132d3e9bd322f82e2940674ec1bc03b20e40

In addition to standard address with 50 characters, we also support extended address in order to ensure the security of transfers conducted by users. The traditional bank transfer design is used for reference: In the process of a bank transfer, bank card number of the remittee should be verified, in addition to which the remitter must enter the name of the remittee. The transfer can be correctly processed only when the bank card number and the name match each other. The generating algorithm for extended address is described as follows:

Data = sha3_256(Public Key)[-20:]
CheckSum = sha3_256(Data)[0:4]
Address = "0x" + Hex(Data + CheckSum)

ExtData = Utf8Bytes({Nickname or any string})
ExtHash = sha3_256(Data + ExtData)[0:2]
ExtAddress = Address + Hex(ExtHash)

An extended address is generated through addition of 2-byte extended verification to the end of a standard address and contains a total of 54 characters. Addition of extended information allows the addition of another element verification to the Nebulas Wallet APP. For example:

The standard address of Alice’s wallet is  0xdf4d22611412132d3e9bd322f82e2940674ec1bc03b20e40, and the extended address after addition of the nickname "alice" should be 0xdf4d22611412132d3e9bd322f82e2940674ec1bc03b20e40e345.
Alice tells Bob the extended address 0xdf4d22611412132d3e9bd322f82e2940674ec1bc03b20e40e345 and her nickname alice.
Bob enters 0xdf4d22611412132d3e9bd322f82e2940674ec1bc03b20e40e345 and alice in the Wallet App.
The Wallet App verifies the consistency between the wallet address and the nickname in order to avoid the circumstance that Bob enters the account number of another user by mistake.

func AddressParse added in v0.2.0

func AddressParse(s string) (*Address, error)

AddressParse parse address string.

func AddressParseFromBytes added in v0.2.0

func AddressParseFromBytes(s []byte) (*Address, error)

AddressParseFromBytes parse address from bytes.

func NewAddress

func NewAddress(s []byte) (*Address, error)

NewAddress create new #Address according to data bytes.

func NewAddressFromPublicKey

func NewAddressFromPublicKey(s []byte) (*Address, error)

NewAddressFromPublicKey return new address from publickey bytes

func NewContractAddressFromHash added in v0.3.0

func NewContractAddressFromHash(s []byte) (*Address, error)

NewContractAddressFromHash return new contract address from bytes.

func (*Address) Bytes added in v0.2.0

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

Bytes returns address bytes

func (*Address) Equals added in v0.2.0

func (a *Address) Equals(b *Address) bool

Equals compare two Address. True is equal, otherwise false.

func (*Address) ToHex

func (a *Address) ToHex() string

ToHex convert address to hex

type Block

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

Block structure

func NewBlock

func NewBlock(chainID uint32, coinbase *Address, parent *Block, txPool *TransactionPool, storage storage.Storage) *Block

NewBlock return new block.

func NewGenesisBlock

func NewGenesisBlock(chainID uint32, storage storage.Storage) *Block

NewGenesisBlock create genesis @Block from file.

func (*Block) Coinbase added in v0.3.0

func (block *Block) Coinbase() *Address

Coinbase return block's coinbase

func (*Block) CollectTransactions added in v0.2.0

func (block *Block) CollectTransactions(n int)

CollectTransactions and add them to block.

func (*Block) Execute added in v0.3.0

func (block *Block) Execute() error

Execute block and return result.

func (*Block) FindAccount added in v0.2.0

func (block *Block) FindAccount(address *Address) *Account

FindAccount return account info in state Trie if not found, return a new account

func (*Block) FindOrCreateAccount added in v0.3.0

func (block *Block) FindOrCreateAccount(address *Address) (account *Account, created bool)

FindOrCreateAccount return account info in state Trie if not found, create one and return it.

func (*Block) FromProto added in v0.2.0

func (block *Block) FromProto(msg proto.Message) error

FromProto converts proto Block to domain Block

func (*Block) GetBalance added in v0.2.0

func (block *Block) GetBalance(address Hash) *util.Uint128

GetBalance returns balance for the given address on this block.

func (*Block) GetNonce added in v0.2.0

func (block *Block) GetNonce(address Hash) uint64

GetNonce returns nonce for the given address on this block.

func (*Block) GlobalContractStorage added in v0.3.0

func (block *Block) GlobalContractStorage(contract *Address) *trie.BatchTrie

GlobalContractStorage return the local storage trie of the contract

func (*Block) Hash

func (block *Block) Hash() Hash

Hash return block hash.

func (*Block) Height

func (block *Block) Height() uint64

Height return height from genesis block.

func (*Block) LinkParentBlock

func (block *Block) LinkParentBlock(parentBlock *Block) bool

LinkParentBlock link parent block, return true if hash is the same; false otherwise.

func (*Block) LocalContractStorage added in v0.3.0

func (block *Block) LocalContractStorage(contract *Address) *trie.BatchTrie

LocalContractStorage return the local storage trie of the contract

func (*Block) Nonce

func (block *Block) Nonce() uint64

Nonce return nonce.

func (*Block) ParentBlock

func (block *Block) ParentBlock() *Block

ParentBlock return parent block.

func (*Block) ParentHash

func (block *Block) ParentHash() Hash

ParentHash return parent hash.

func (*Block) Seal

func (block *Block) Seal()

Seal seal block, calculate stateRoot and block hash.

func (*Block) Sealed

func (block *Block) Sealed() bool

Sealed return true if block seals. Otherwise return false.

func (*Block) SetNonce

func (block *Block) SetNonce(nonce uint64)

SetNonce set nonce.

func (*Block) SetTimestamp

func (block *Block) SetTimestamp(timestamp int64)

SetTimestamp set timestamp

func (*Block) StateRoot

func (block *Block) StateRoot() Hash

StateRoot return state root hash.

func (*Block) String

func (block *Block) String() string

func (*Block) ToProto added in v0.2.0

func (block *Block) ToProto() (proto.Message, error)

ToProto converts domain Block into proto Block

func (*Block) TxsRoot added in v0.2.0

func (block *Block) TxsRoot() Hash

TxsRoot return txs root hash.

func (*Block) Verify

func (block *Block) Verify(chainID uint32) error

Verify return block verify result, including Hash, Nonce and StateRoot.

type BlockChain

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

BlockChain the BlockChain core type.

func NewBlockChain

func NewBlockChain(chainID uint32, storage storage.Storage) (*BlockChain, error)

NewBlockChain create new #BlockChain instance.

func (*BlockChain) BlockPool

func (bc *BlockChain) BlockPool() *BlockPool

BlockPool return block pool.

func (*BlockChain) ChainID

func (bc *BlockChain) ChainID() uint32

ChainID return the chainID.

func (*BlockChain) ConsensusHandler

func (bc *BlockChain) ConsensusHandler() Consensus

ConsensusHandler return consensus handler.

func (*BlockChain) DetachedTailBlocks

func (bc *BlockChain) DetachedTailBlocks() []*Block

DetachedTailBlocks return detached tail blocks, used by Fork Choice algorithm.

func (*BlockChain) Dump

func (bc *BlockChain) Dump(count int) string

Dump dump full chain.

func (*BlockChain) FetchDescendantInCanonicalChain added in v0.2.0

func (bc *BlockChain) FetchDescendantInCanonicalChain(n int, block *Block) ([]*Block, error)

FetchDescendantInCanonicalChain return the subsequent blocks of the block lookup the block's descendant from tail to genesis if the block is not in canonical chain, return err

func (*BlockChain) FindCommonAncestorWithTail added in v0.2.0

func (bc *BlockChain) FindCommonAncestorWithTail(block *Block) (*Block, error)

FindCommonAncestorWithTail return the block's common ancestor with current tail

func (*BlockChain) GetBlock

func (bc *BlockChain) GetBlock(hash Hash) *Block

GetBlock return block of given hash from local storage and detachedBlocks.

func (*BlockChain) GetTransaction added in v0.3.0

func (bc *BlockChain) GetTransaction(hash Hash) *Transaction

GetTransaction return transaction of given hash from local storage.

func (*BlockChain) NewBlock

func (bc *BlockChain) NewBlock(coinbase *Address) *Block

NewBlock create new #Block instance.

func (*BlockChain) NewBlockFromParent

func (bc *BlockChain) NewBlockFromParent(coinbase *Address, parentBlock *Block) *Block

NewBlockFromParent create new block from parent block and return it.

func (*BlockChain) PutVerifiedNewBlocks

func (bc *BlockChain) PutVerifiedNewBlocks(allBlocks, tailBlocks []*Block) error

PutVerifiedNewBlocks put verified new blocks and tails.

func (*BlockChain) SetConsensusHandler

func (bc *BlockChain) SetConsensusHandler(handler Consensus)

SetConsensusHandler set consensus handler.

func (*BlockChain) SetTailBlock

func (bc *BlockChain) SetTailBlock(newTail *Block)

SetTailBlock set tail block.

func (*BlockChain) Storage added in v0.3.0

func (bc *BlockChain) Storage() storage.Storage

Storage return the storage

func (*BlockChain) TailBlock

func (bc *BlockChain) TailBlock() *Block

TailBlock return the tail block.

func (*BlockChain) TransactionPool added in v0.2.0

func (bc *BlockChain) TransactionPool() *TransactionPool

TransactionPool return block pool.

type BlockHeader

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

BlockHeader of a block

func (*BlockHeader) FromProto added in v0.2.0

func (b *BlockHeader) FromProto(msg proto.Message) error

FromProto converts proto BlockHeader to domain BlockHeader

func (*BlockHeader) ToProto added in v0.2.0

func (b *BlockHeader) ToProto() (proto.Message, error)

ToProto converts domain BlockHeader to proto BlockHeader

type BlockPool

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

BlockPool a pool of all received blocks from network. Blocks will be sent to Consensus when it passes signature verification.

func NewBlockPool

func NewBlockPool() *BlockPool

NewBlockPool return new #BlockPool instance.

func (*BlockPool) Push added in v0.2.0

func (pool *BlockPool) Push(block *Block) error

Push block into block pool

func (*BlockPool) PushAndBroadcast added in v0.2.0

func (pool *BlockPool) PushAndBroadcast(block *Block) error

PushAndBroadcast push block into block pool and broadcast it.

func (*BlockPool) PushAndRelay added in v0.2.0

func (pool *BlockPool) PushAndRelay(block *Block) error

PushAndRelay push block into block pool and relay it.

func (*BlockPool) ReceivedBlockCh

func (pool *BlockPool) ReceivedBlockCh() chan *Block

ReceivedBlockCh return received block chan.

func (*BlockPool) RegisterInNetwork

func (pool *BlockPool) RegisterInNetwork(nm net.Manager)

RegisterInNetwork register message subscriber in network.

func (*BlockPool) Start

func (pool *BlockPool) Start()

Start start loop.

func (*BlockPool) Stop

func (pool *BlockPool) Stop()

Stop stop loop.

type Consensus

type Consensus interface {
	VerifyBlock(*Block) error
}

Consensus interface

type Hash

type Hash []byte

Hash by Sha3-256

func HashBlock

func HashBlock(block *Block) Hash

HashBlock return the hash of block.

func HashTransaction

func HashTransaction(tx *Transaction) (Hash, error)

HashTransaction hash the transaction.

func (Hash) Equals

func (h Hash) Equals(b Hash) bool

Equals compare two Hash. True is equal, otherwise false.

func (Hash) Hex

func (h Hash) Hex() HexHash

Hex return hex encoded hash.

func (Hash) String

func (h Hash) String() string

type HexHash

type HexHash string

HexHash is the hex string of a hash

func (HexHash) Hash

func (hh HexHash) Hash() Hash

Hash return hex decoded hash.

type Transaction

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

Transaction type is used to handle all transaction data.

func NewTransaction

func NewTransaction(chainID uint32, from, to *Address, value *util.Uint128, nonce uint64, data []byte) *Transaction

NewTransaction create #Transaction instance.

func (*Transaction) DataLen added in v0.2.0

func (tx *Transaction) DataLen() int

DataLen return data length

func (*Transaction) Execute

func (tx *Transaction) Execute(block *Block) error

Execute transaction and return result.

func (*Transaction) From added in v0.2.0

func (tx *Transaction) From() *Address

From return from address

func (*Transaction) FromProto added in v0.2.0

func (tx *Transaction) FromProto(msg proto.Message) error

FromProto converts proto Tx into domain Tx

func (*Transaction) Hash

func (tx *Transaction) Hash() Hash

Hash return the hash of transaction.

func (*Transaction) Nonce added in v0.2.0

func (tx *Transaction) Nonce() uint64

Nonce return tx nonce

func (*Transaction) Sign

func (tx *Transaction) Sign(signature keystore.Signature) error

Sign sign transaction,sign algorithm is

func (*Transaction) String added in v0.2.0

func (tx *Transaction) String() string

func (*Transaction) TargetContractAddress added in v0.3.0

func (tx *Transaction) TargetContractAddress() *Address

TargetContractAddress return the target contract address.

func (*Transaction) ToProto added in v0.2.0

func (tx *Transaction) ToProto() (proto.Message, error)

ToProto converts domain Tx to proto Tx

func (*Transaction) Verify

func (tx *Transaction) Verify(chainID uint32) error

Verify return transaction verify result, including Hash and Signature.

type TransactionPool

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

TransactionPool cache txs, is thread safe

func NewTransactionPool

func NewTransactionPool(size int) *TransactionPool

NewTransactionPool create a new TransactionPool

func (*TransactionPool) Empty added in v0.2.0

func (pool *TransactionPool) Empty() bool

Empty return if the pool is empty

func (*TransactionPool) Pop added in v0.2.0

func (pool *TransactionPool) Pop() *Transaction

Pop a transaction from pool

func (*TransactionPool) Push added in v0.2.0

func (pool *TransactionPool) Push(tx *Transaction) error

Push tx into pool

func (*TransactionPool) PushAndBroadcast added in v0.2.0

func (pool *TransactionPool) PushAndBroadcast(tx *Transaction) error

PushAndBroadcast push tx into pool and broadcast it

func (*TransactionPool) PushAndRelay added in v0.2.0

func (pool *TransactionPool) PushAndRelay(tx *Transaction) error

PushAndRelay push tx into pool and relay it

func (*TransactionPool) RegisterInNetwork added in v0.2.0

func (pool *TransactionPool) RegisterInNetwork(nm net.Manager)

RegisterInNetwork register message subscriber in network.

func (*TransactionPool) Start added in v0.2.0

func (pool *TransactionPool) Start()

Start start loop.

func (*TransactionPool) Stop added in v0.2.0

func (pool *TransactionPool) Stop()

Stop stop loop.

type Transactions

type Transactions []*Transaction

Transactions is an alias of Transaction array.

Directories

Path Synopsis
Package corepb is a generated protocol buffer package.
Package corepb is a generated protocol buffer package.

Jump to

Keyboard shortcuts

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