core

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2018 License: LGPL-3.0 Imports: 39 Imported by: 0

README

core

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

Documentation

Index

Constants

View Source
const (
	Padding byte = 0x19

	NebulasFaith = 'n'
)

const

View Source
const (
	// AddressPaddingLength the length of headpadding in byte
	AddressPaddingLength = 1
	// AddressPaddingIndex the index of headpadding bytes
	AddressPaddingIndex = 0

	// AddressTypeLength the length of address type in byte
	AddressTypeLength = 1
	// AddressTypeIndex the index of address type bytes
	AddressTypeIndex = 1

	// 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 = AddressPaddingLength + AddressTypeLength + AddressDataLength + AddressChecksumLength
	// AddressDataEnd the end of the address data
	AddressDataEnd = 22

	// AddressBase58Length length of base58(Address.address)
	AddressBase58Length = 35
	// PublicKeyDataLength length of public key
	PublicKeyDataLength = 65
)
View Source
const (

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

	// ChunkSize is the size of blocks in a chunk
	ChunkSize = 32

	// Tail Key in storage
	Tail = "blockchain_tail"

	// LIB (latest irreversible block) in storage
	LIB = "blockchain_lib"
)
View Source
const (
	// MainNetID mainnet id
	MainNetID uint32 = 1

	// TestNetID testnet id
	TestNetID uint32 = 1001
)
View Source
const (
	// LocalTransferFromContractEventRecordableHeight
	LocalTransferFromContractEventRecordableHeight uint64 = 2

	// LocalAcceptFuncAvailableHeight
	LocalAcceptFuncAvailableHeight uint64 = 2

	// LocalRandomAvailableHeight
	LocalRandomAvailableHeight uint64 = 2

	// LocalDateAvailableHeight
	LocalDateAvailableHeight uint64 = 2

	// LocalRecordCallContractResultHeight
	LocalRecordCallContractResultHeight uint64 = 2

	//LocalNvmMemoryLimitWithoutInjectHeight
	LocalNvmMemoryLimitWithoutInjectHeight uint64 = 2

	//LocalWdResetRecordDependencyHeight
	LocalWsResetRecordDependencyHeight uint64 = 2

	// LocalV8JSLibVersionControlHeight
	LocalV8JSLibVersionControlHeight uint64 = 2

	//LocalNetTransferFromContractFailureEventRecordableHeight
	LocalTransferFromContractFailureEventRecordableHeight uint64 = 2

	//LocalNetNewNvmExeTimeoutConsumeGasHeight
	LocalNewNvmExeTimeoutConsumeGasHeight uint64 = 2
)

others, e.g. local/develop

View Source
const (
	// TestNetTransferFromContractEventRecordableHeight
	TestNetTransferFromContractEventRecordableHeight uint64 = 199666

	// TestNetAcceptFuncAvailableHeight
	TestNetAcceptFuncAvailableHeight uint64 = 199666

	// TestNetRandomAvailableHeight
	TestNetRandomAvailableHeight uint64 = 199666

	// TestNetDateAvailableHeight
	TestNetDateAvailableHeight uint64 = 199666

	// TestNetRecordCallContractResultHeight
	TestNetRecordCallContractResultHeight uint64 = 199666

	//TestNetNvmMemoryLimitWithoutInjectHeight
	TestNetNvmMemoryLimitWithoutInjectHeight uint64 = 281800

	//TestNetWdResetRecordDependencyHeight
	TestNetWsResetRecordDependencyHeight uint64 = 281800

	// TestNetV8JSLibVersionControlHeight
	TestNetV8JSLibVersionControlHeight uint64 = 424400

	//TestNetTransferFromContractFailureEventRecordableHeight
	TestNetTransferFromContractFailureEventRecordableHeight uint64 = 424400

	//TestNetNewNvmExeTimeoutConsumeGasHeight
	TestNetNewNvmExeTimeoutConsumeGasHeight uint64 = 424400
)

TestNet

View Source
const (
	// MainNetTransferFromContractEventRecordableHeight
	MainNetTransferFromContractEventRecordableHeight uint64 = 225666

	// MainNetAcceptFuncAvailableHeight
	MainNetAcceptFuncAvailableHeight uint64 = 225666

	// MainNetRandomAvailableHeight
	MainNetRandomAvailableHeight uint64 = 225666

	// MainNetDateAvailableHeight
	MainNetDateAvailableHeight uint64 = 225666

	// MainNetRecordCallContractResultHeight
	MainNetRecordCallContractResultHeight uint64 = 225666

	//MainNetNvmMemoryLimitWithoutInjectHeight
	MainNetNvmMemoryLimitWithoutInjectHeight uint64 = 306800

	//MainNetWdResetRecordDependencyHeight
	MainNetWsResetRecordDependencyHeight uint64 = 306800

	// MainNetV8JSLibVersionControlHeight
	MainNetV8JSLibVersionControlHeight uint64 = 467500

	//MainNetTransferFromContractFailureEventRecordableHeight
	MainNetTransferFromContractFailureEventRecordableHeight uint64 = 467500

	//MainNetNewNvmExeTimeoutConsumeGasHeight
	MainNetNewNvmExeTimeoutConsumeGasHeight uint64 = 467500
)

MainNet

View Source
const (
	// TopicPendingTransaction the topic of pending a transaction in transaction_pool.
	TopicPendingTransaction = "chain.pendingTransaction"

	// TopicLibBlock the topic of latest irreversible block.
	TopicLibBlock = "chain.latestIrreversibleBlock"

	// TopicTransactionExecutionResult the topic of transaction execution result
	TopicTransactionExecutionResult = "chain.transactionResult"

	// TopicNewTailBlock the topic of new tail block set
	TopicNewTailBlock = "chain.newTailBlock"

	// TopicRevertBlock the topic of revert block
	TopicRevertBlock = "chain.revertBlock"

	// TopicDropTransaction drop tx (1): smaller nonce (2) expire txLifeTime
	TopicDropTransaction = "chain.dropTransaction"

	// TopicTransferFromContract transfer from contract
	TopicTransferFromContract = "chain.transferFromContract"
)
View Source
const (
	TxPayloadBinaryType = "binary"
	TxPayloadDeployType = "deploy"
	TxPayloadCallType   = "call"
)

Payload Types

View Source
const (
	SourceTypeJavaScript = "js"
	SourceTypeTypeScript = "ts"
)

Const.

View Source
const (
	// TxExecutionFailed failed status for transaction execute result.
	TxExecutionFailed = 0

	// TxExecutionSuccess success status for transaction execute result.
	TxExecutionSuccess = 1

	// TxExecutionPendding pendding status when transaction in transaction pool.
	TxExecutionPendding = 2
)
View Source
const (
	MessageTypeNewBlock                   = "newblock"
	MessageTypeParentBlockDownloadRequest = "dlblock"
	MessageTypeBlockDownloadResponse      = "dlreply"
	MessageTypeNewTx                      = "newtx"
)

MessageType

View Source
const (
	ContractAcceptFunc = "accept"
)

Const

View Source
const (
	// DefaultV8JSLibVersion default version
	DefaultV8JSLibVersion = "1.0.0"
)

********* js lib relative BEGIN *********

View Source
const (
	NoSender = ""
)

constants

View Source
const (
	// TxHashByteLength invalid tx hash length(len of []byte)
	TxHashByteLength = 32
)

Variables

View Source
var (
	// BlockHashLength define a const of the length of Hash of Block in byte.
	BlockHashLength = 32

	// ParallelNum num
	ParallelNum = 1

	// VerifyExecutionTimeout 0 means unlimited
	VerifyExecutionTimeout = 0

	// BlockReward given to coinbase
	// rule: 3% per year, 3,000,000. 1 block per 15 seconds
	// value: 10^8 * 3% / (365*24*3600/15) * 10^18 ≈ 1.42694 * 10^18
	BlockReward, _ = util.NewUint128FromString("1426940000000000000")
)
View Source
var (
	// TransferFromContractEventRecordableHeight record event 'TransferFromContractEvent' since this height
	TransferFromContractEventRecordableHeight = TestNetTransferFromContractEventRecordableHeight

	// AcceptFuncAvailableHeight 'accept' func available since this height
	AcceptFuncAvailableHeight = TestNetAcceptFuncAvailableHeight

	// RandomAvailableHeight make 'Math.random' available in contract since this height
	RandomAvailableHeight = TestNetRandomAvailableHeight

	// DateAvailableHeight make 'Date' available in contract since this height
	DateAvailableHeight = TestNetDateAvailableHeight

	// RecordCallContractResultHeight record result of call contract to event `TopicTransactionExecutionResult` since this height
	RecordCallContractResultHeight = TestNetRecordCallContractResultHeight

	// NvmMemoryLimitWithoutInjectHeight memory of nvm contract without inject code
	NvmMemoryLimitWithoutInjectHeight = TestNetNvmMemoryLimitWithoutInjectHeight

	//WsResetRecordDependencyHeight if tx execute faied, worldstate reset and need to record to address dependency
	WsResetRecordDependencyHeight = TestNetWsResetRecordDependencyHeight

	// V8JSLibVersionControlHeight enable v8 js lib version control
	V8JSLibVersionControlHeight = TestNetV8JSLibVersionControlHeight

	// V8JSLibVersionHeightSlice all version-height pairs
	V8JSLibVersionHeightSlice = TestNetV8JSLibVersionHeightSlice

	// TransferFromContractFailureEventRecordableHeight record event 'TransferFromContractEvent' since this height
	TransferFromContractFailureEventRecordableHeight = TestNetTransferFromContractFailureEventRecordableHeight

	//NewNvmExeTimeoutConsumeGasHeight
	NewNvmExeTimeoutConsumeGasHeight = TestNetNewNvmExeTimeoutConsumeGasHeight
)
View Source
var (
	GenesisHash        = make([]byte, BlockHashLength)
	GenesisTimestamp   = int64(0)
	GenesisCoinbase, _ = NewAddressFromPublicKey(make([]byte, PublicKeyDataLength))
)

Genesis Block Hash

View Source
var (
	// TransactionMaxGasPrice max gasPrice:1 * 10 ** 12
	TransactionMaxGasPrice, _ = util.NewUint128FromString("1000000000000")

	// TransactionMaxGas max gas:50 * 10 ** 9
	TransactionMaxGas, _ = util.NewUint128FromString("50000000000")

	// TransactionGasPrice default gasPrice : 10**6
	TransactionGasPrice, _ = util.NewUint128FromInt(1000000)

	// MinGasCountPerTransaction default gas for normal transaction
	MinGasCountPerTransaction, _ = util.NewUint128FromInt(20000)

	// GasCountPerByte per byte of data attached to a transaction gas cost
	GasCountPerByte, _ = util.NewUint128FromInt(1)

	// MaxDataPayLoadLength Max data length in transaction
	MaxDataPayLoadLength = 128 * 1024
	// MaxDataBinPayloadLength Max data length in binary transaction
	MaxDataBinPayloadLength = 64

	// MaxEventErrLength Max error length in event
	MaxEventErrLength = 256

	// MaxResultLength max execution result length
	MaxResultLength = 256
)
View Source
var (
	TestCompatArr = []string{"5b6a9ed8a48cfb0e6415f0df9f79cbbdac565dd139779c7972069b37c99a3913",
		"918d116f5d42b253e84497d65d2a6508fb5c4c1dbc5c1c2a1718ab718a50a509"}
	MainCompatArr = []string{"ee90d2cc5f930fe627363e9e05f1e98ea20025898201c849125659d6c0079242",
		"3db72f0d02daa26407d13ca9efc820ec618407d10d55ac15433784aaef93c659"}
)
View Source
var (
	ErrInvalidBlockOnCanonicalChain                      = errors.New("invalid block, it's not on canonical chain")
	ErrNotBlockInCanonicalChain                          = errors.New("cannot find the block in canonical chain")
	ErrInvalidBlockCannotFindParentInLocal               = errors.New("invalid block received, download its parent from others")
	ErrCannotFindBlockAtGivenHeight                      = errors.New("cannot find a block at given height which is less than tail block's height")
	ErrInvalidBlockCannotFindParentInLocalAndTryDownload = errors.New("invalid block received, download its parent from others")
	ErrInvalidBlockCannotFindParentInLocalAndTrySync     = errors.New("invalid block received, sync its parent from others")
	ErrBlockNotFound                                     = errors.New("block not found in blockchain cache nor chain")

	ErrInvalidConfigChainID          = errors.New("invalid chainID, genesis chainID not equal to chainID in config")
	ErrCannotLoadGenesisConf         = errors.New("cannot load genesis conf")
	ErrGenesisNotEqualChainIDInDB    = errors.New("Failed to check. genesis chainID not equal in db")
	ErrGenesisNotEqualDynastyInDB    = errors.New("Failed to check. genesis dynasty not equal in db")
	ErrGenesisNotEqualTokenInDB      = errors.New("Failed to check. genesis TokenDistribution not equal in db")
	ErrGenesisNotEqualDynastyLenInDB = errors.New("Failed to check. genesis dynasty length not equal in db")
	ErrGenesisNotEqualTokenLenInDB   = errors.New("Failed to check. genesis TokenDistribution length not equal in db")

	ErrLinkToWrongParentBlock = errors.New("link the block to a block who is not its parent")
	ErrMissingParentBlock     = errors.New("cannot find the block's parent block in storage")
	ErrInvalidBlockHash       = errors.New("invalid block hash")
	ErrDoubleSealBlock        = errors.New("cannot seal a block twice")
	ErrDuplicatedBlock        = errors.New("duplicated block")
	ErrDoubleBlockMinted      = errors.New("double block minted")
	ErrVRFProofFailed         = errors.New("VRF proof failed")
	ErrInvalidBlockRandom     = errors.New("invalid block random")

	ErrInvalidChainID           = errors.New("invalid transaction chainID")
	ErrInvalidTransactionSigner = errors.New("invalid transaction signer")
	ErrInvalidTransactionHash   = errors.New("invalid transaction hash")
	ErrInvalidSignature         = errors.New("invalid transaction signature")
	ErrInvalidTxPayloadType     = errors.New("invalid transaction data payload type")
	ErrInvalidGasPrice          = errors.New("invalid gas price, should be in (0, 10^12]")
	ErrInvalidGasLimit          = errors.New("invalid gas limit, should be in (0, 5*10^10]")

	ErrNoTimeToPackTransactions       = errors.New("no time left to pack transactions in a block")
	ErrTxDataPayLoadOutOfMaxLength    = errors.New("data's payload is out of max data length")
	ErrTxDataBinPayLoadOutOfMaxLength = errors.New("data's payload is out of max data length in a binary tx")
	ErrNilArgument                    = errors.New("argument(s) is nil")
	ErrInvalidArgument                = errors.New("invalid argument(s)")

	ErrInsufficientBalance                = errors.New("insufficient balance")
	ErrBelowGasPrice                      = errors.New("below the gas price")
	ErrGasCntOverflow                     = errors.New("the count of gas used is overflow")
	ErrGasFeeOverflow                     = errors.New("the fee of gas used is overflow")
	ErrInvalidTransfer                    = errors.New("transfer error: overflow or insufficient balance")
	ErrGasLimitLessOrEqualToZero          = errors.New("gas limit less or equal to 0")
	ErrOutOfGasLimit                      = errors.New("out of gas limit")
	ErrTxExecutionFailed                  = errors.New("transaction execution failed")
	ErrZeroGasPrice                       = errors.New("gas price should be greater than zero")
	ErrZeroGasLimit                       = errors.New("gas limit should be greater than zero")
	ErrContractDeployFailed               = errors.New("contract deploy failed")
	ErrContractCheckFailed                = errors.New("contract check failed")
	ErrContractTransactionAddressNotEqual = errors.New("contract transaction from-address not equal to to-address")

	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")

	ErrInvalidAddress         = errors.New("address: invalid address")
	ErrInvalidAddressFormat   = errors.New("address: invalid address format")
	ErrInvalidAddressType     = errors.New("address: invalid address type")
	ErrInvalidAddressChecksum = errors.New("address: invalid address checksum")

	ErrInvalidCandidatePayloadAction     = errors.New("invalid transaction candidate payload action")
	ErrInvalidDelegatePayloadAction      = errors.New("invalid transaction vote payload action")
	ErrInvalidDelegateToNonCandidate     = errors.New("cannot delegate to non-candidate")
	ErrInvalidUnDelegateFromNonDelegatee = errors.New("cannot un-delegate from non-delegatee")

	ErrCloneWorldState           = errors.New("Failed to clone world state")
	ErrCloneAccountState         = errors.New("Failed to clone account state")
	ErrCloneTxsState             = errors.New("Failed to clone txs state")
	ErrCloneEventsState          = errors.New("Failed to clone events state")
	ErrInvalidBlockStateRoot     = errors.New("invalid block state root hash")
	ErrInvalidBlockTxsRoot       = errors.New("invalid block txs root hash")
	ErrInvalidBlockEventsRoot    = errors.New("invalid block events root hash")
	ErrInvalidBlockConsensusRoot = errors.New("invalid block consensus root hash")
	ErrInvalidProtoToBlock       = errors.New("protobuf message cannot be converted into Block")
	ErrInvalidProtoToBlockHeader = errors.New("protobuf message cannot be converted into BlockHeader")
	ErrInvalidProtoToTransaction = errors.New("protobuf message cannot be converted into Transaction")
	ErrInvalidTransactionData    = errors.New("invalid data in tx from Proto")
	ErrInvalidDagBlock           = errors.New("block's dag is incorrect")

	ErrCannotRevertLIB        = errors.New("cannot revert latest irreversible block")
	ErrCannotLoadGenesisBlock = errors.New("cannot load genesis block from storage")
	ErrCannotLoadLIBBlock     = errors.New("cannot load tail block from storage")
	ErrCannotLoadTailBlock    = errors.New("cannot load latest irreversible block from storage")
	ErrGenesisConfNotMatch    = errors.New("Failed to load genesis from storage, different with genesis conf")

	ErrInvalidDeploySource     = errors.New("invalid source of deploy payload")
	ErrInvalidDeploySourceType = errors.New("invalid source type of deploy payload")
	ErrInvalidCallFunction     = errors.New("invalid function of call payload")

	ErrInvalidTransactionResultEvent  = errors.New("invalid transaction result event, the last event in tx's events should be result event")
	ErrNotFoundTransactionResultEvent = errors.New("transaction result event is not found ")

	// nvm error
	ErrExecutionFailed = errors.New("execution failed")
	ErrUnexpected      = errors.New("Unexpected sys error")

	// unsupported keyword error in smart contract
	ErrUnsupportedKeyword = errors.New("transaction data has unsupported keyword")
)

Error Types

View Source
var (
	DefaultPayloadGas, _ = util.NewUint128FromInt(1)

	// DefaultLimitsOfTotalMemorySize default limits of total memory size
	DefaultLimitsOfTotalMemorySize uint64 = 40 * 1000 * 1000
)

Default gas count

View Source
var (
	// ErrInvalidJSLibVersion ..
	ErrInvalidJSLibVersion = errors.New("invalid js lib version")
)
View Source
var (
	LocalV8JSLibVersionHeightSlice = heightOfVersionSlice{
		{"1.0.5", LocalV8JSLibVersionControlHeight},
	}
)

var for local/develop

View Source
var (
	MainNetV8JSLibVersionHeightSlice = heightOfVersionSlice{
		{"1.0.5", MainNetV8JSLibVersionControlHeight},
	}
)

var for MainNet

View Source
var (
	// PublicFuncNameChecker     in smart contract
	PublicFuncNameChecker = regexp.MustCompile("^[a-zA-Z$][A-Za-z0-9_$]*$")
)
View Source
var (
	TestNetV8JSLibVersionHeightSlice = heightOfVersionSlice{
		{"1.0.5", TestNetV8JSLibVersionControlHeight},
	}
)

var for TestNet

View Source
var (
	// NOTE: versions should be arranged in ascending order
	// 		map[libname][versions]
	V8JSLibs = map[string][]string{
		"execution_env.js":       {"1.0.0", "1.0.5"},
		"bignumber.js":           {"1.0.0"},
		"random.js":              {"1.0.0", "1.0.5"},
		"date.js":                {"1.0.0", "1.0.5"},
		"tsc.js":                 {"1.0.0"},
		"util.js":                {"1.0.0"},
		"esprima.js":             {"1.0.0"},
		"assert.js":              {"1.0.0"},
		"instruction_counter.js": {"1.0.0"},
		"typescriptServices.js":  {"1.0.0"},
		"blockchain.js":          {"1.0.0", "1.0.5"},
		"console.js":             {"1.0.0"},
		"event.js":               {"1.0.0"},
		"storage.js":             {"1.0.0"},
		"crypto.js":              {"1.0.5"},
		"uint.js":                {"1.0.5"},
	}
)

var ..

Functions

func AcceptTransaction added in v1.0.0

func AcceptTransaction(tx *Transaction, ws WorldState) (bool, error)

AcceptTransaction in a tx world state

func CheckContract added in v1.0.0

func CheckContract(addr *Address, ws WorldState) (state.Account, error)

CheckContract check if contract is valid

func CheckContractArgs added in v1.0.0

func CheckContractArgs(args string) error

CheckContractArgs check contract args

func CheckGenesisBlock added in v0.3.0

func CheckGenesisBlock(block *Block) bool

CheckGenesisBlock if a block is a genesis block

func CheckGenesisConfByDB added in v1.0.0

func CheckGenesisConfByDB(pGenesisDB *corepb.Genesis, pGenesis *corepb.Genesis) error

CheckGenesisConfByDB check mem and genesis.conf if equal return nil

func CheckGenesisTransaction added in v1.0.1

func CheckGenesisTransaction(tx *Transaction) bool

CheckGenesisTransaction if a tx is a genesis transaction

func CheckTransaction added in v1.0.0

func CheckTransaction(tx *Transaction, ws WorldState) (bool, error)

CheckTransaction in a tx world state

func DumpGenesis added in v1.0.0

func DumpGenesis(chain *BlockChain) (*corepb.Genesis, error)

DumpGenesis return the configuration of the genesis block in the storage

func FindLastNearestLibVersion added in v1.0.5

func FindLastNearestLibVersion(deployVersion, libname string) string

FindLastNearestLibVersion ..

func GetMaxV8JSLibVersionAtHeight added in v1.0.5

func GetMaxV8JSLibVersionAtHeight(blockHeight uint64) string

GetMaxV8JSLibVersionAtHeight ..

func HashPbBlock added in v1.0.0

func HashPbBlock(pbBlock *corepb.Block) (byteutils.Hash, error)

HashPbBlock return the hash of pb block.

func IsCompatibleStack added in v1.0.5

func IsCompatibleStack(chainID uint32, hash byteutils.Hash) bool

IsCompatibleStack return if compatible stack

func LoadGenesisConf added in v1.0.0

func LoadGenesisConf(filePath string) (*corepb.Genesis, error)

LoadGenesisConf load genesis conf for file

func SetCompatibilityOptions added in v1.0.2

func SetCompatibilityOptions(chainID uint32)

SetCompatibilityOptions set compatibility height according to chain_id

func VerifyExecution added in v1.0.0

func VerifyExecution(tx *Transaction, block *Block, ws WorldState) (bool, error)

VerifyExecution transaction and return result.

Types

type AccountManager added in v1.0.0

type AccountManager interface {
	NewAccount([]byte) (*Address, error)
	Accounts() []*Address

	Unlock(*Address, []byte, time.Duration) error
	Lock(*Address) error

	SignHash(*Address, byteutils.Hash, keystore.Algorithm) ([]byte, error)
	SignBlock(*Address, *Block) error
	GenerateRandomSeed(*Address, []byte, []byte) ([]byte, []byte, error)
	SignTransaction(*Address, *Transaction) error
	SignTransactionWithPassphrase(*Address, *Transaction, []byte) error

	Update(*Address, []byte, []byte) error
	Load([]byte, []byte) (*Address, error)
	Import([]byte, []byte) (*Address, error)
	Remove(*Address, []byte) error
}

AccountManager interface of account mananger

type Address

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

Address design of nebulas address

[Account Address] Similar to Bitcoin and Ethereum, Nebulas also adopts elliptic curve algorithm as its basic encryption algorithm for Nebulas accounts. The address is derived from **public key**, which is in turn derived from the **private key** that encrypted with user's **passphrase**. Also we have the checksum design aiming to prevent a user from sending _Nas_ to a wrong user account accidentally due to entry of several incorrect characters.

The specific calculation formula is as follows:

	Content = ripemd160( sha3_256( Public Key ) )
	CheckSum = sha3_256( 0x19 + 0x57 + Content )[0:4]
	Address = base58( 0x19 + 0x57 + Content + CheckSum )

 	0x57 is a one-byte "type code" for account address, 0x19 is a one-byte fixed "padding"

The ripemd160 digest 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. For example: The final address of Nebulas Wallet should be: n1TV3sU6jyzR4rJ1D7jCAmtVGSntJagXZHC

[Smart Contract Address] Calculating contract address differs slightly from account, passphrase of contract sender is not required but address & nonce. For more information, plz check (https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md) and [rpc.sendTransaction](https://github.com/nebulasio/wiki/blob/master/rpc.md#sendtransaction). Calculation formula is as follows:

Content = ripemd160( sha3_256( tx.from, tx.nonce ) )
CheckSum = sha3_256( 0x19 + 0x58 + Content )[0:4]
Address = base58( 0x19 + 0x58 + Content + CheckSum )

0x58 is a one-byte "type code" for smart contract address, 0x19 is a one-byte fixed "padding"

[TODO] 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:

ExtData = Utf8Bytes({Nickname or any string})
ExtHash = sha3_256(Data + ExtData)[0:2]
ExtAddress = Account 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(b []byte) (*Address, error)

AddressParseFromBytes parse address from bytes.

func NewAddressFromPublicKey

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

NewAddressFromPublicKey return new address from publickey bytes

func NewContractAddressFromData added in v1.0.0

func NewContractAddressFromData(from ContractTxFrom, nonce ContractTxNonce) (*Address, error)

NewContractAddressFromData return new contract address from bytes.

func RecoverSignerFromSignature added in v1.0.0

func RecoverSignerFromSignature(alg keystore.Algorithm, plainText []byte, cipherText []byte) (*Address, error)

RecoverSignerFromSignature return address who signs the signature

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) String added in v1.0.0

func (a *Address) String() string

String returns address string

func (*Address) Type added in v1.0.0

func (a *Address) Type() AddressType

Type return the type of address.

type AddressType added in v1.0.0

type AddressType byte

AddressType address type

const (
	AccountAddress AddressType = 0x57 + iota
	ContractAddress
)

address type enum

const UndefinedAddressType AddressType = 0x00

UndefinedAddressType undefined

type BinaryPayload added in v1.0.0

type BinaryPayload struct {
	Data []byte
}

BinaryPayload carry some data

func LoadBinaryPayload added in v1.0.0

func LoadBinaryPayload(bytes []byte) (*BinaryPayload, error)

LoadBinaryPayload from bytes

func NewBinaryPayload added in v1.0.0

func NewBinaryPayload(data []byte) *BinaryPayload

NewBinaryPayload with data

func (*BinaryPayload) BaseGasCount added in v1.0.0

func (payload *BinaryPayload) BaseGasCount() *util.Uint128

BaseGasCount returns base gas count

func (*BinaryPayload) Execute added in v1.0.0

func (payload *BinaryPayload) Execute(limitedGas *util.Uint128, tx *Transaction, block *Block, ws WorldState) (*util.Uint128, string, error)

Execute the payload in tx

func (*BinaryPayload) ToBytes added in v1.0.0

func (payload *BinaryPayload) ToBytes() ([]byte, error)

ToBytes serialize payload

type Block

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

Block structure

func LoadBlockFromStorage added in v1.0.0

func LoadBlockFromStorage(hash byteutils.Hash, chain *BlockChain) (*Block, error)

LoadBlockFromStorage return a block from storage

func MockBlock added in v1.0.5

func MockBlock(header *BlockHeader, height uint64) *Block

MockBlock nf/nvm/engine.CheckV8Run() & cmd/v8/main.go

func NewBlock

func NewBlock(chainID uint32, coinbase *Address, parent *Block) (*Block, error)

NewBlock return new block.

func NewGenesisBlock

func NewGenesisBlock(conf *corepb.Genesis, chain *BlockChain) (*Block, error)

NewGenesisBlock create genesis @Block from file.

func (*Block) Alg added in v1.0.0

func (block *Block) Alg() keystore.Algorithm

Alg return block's alg

func (*Block) Begin added in v1.0.0

func (block *Block) Begin() error

Begin a batch task

func (*Block) ChainID added in v1.0.0

func (block *Block) ChainID() uint32

ChainID returns block's chainID

func (*Block) CheckContract added in v1.0.0

func (block *Block) CheckContract(addr *Address) (state.Account, error)

CheckContract check if contract is valid

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(deadlineInMs int64)

CollectTransactions and add them to block.

func (*Block) Commit added in v1.0.0

func (block *Block) Commit()

Commit a batch task

func (*Block) ConsensusRoot added in v1.0.0

func (block *Block) ConsensusRoot() *consensuspb.ConsensusRoot

ConsensusRoot return consensus root

func (*Block) DateAvailable added in v1.0.2

func (block *Block) DateAvailable() bool

DateAvailable check if date available in contract

func (*Block) Dynasty added in v1.0.0

func (block *Block) Dynasty() ([]byteutils.Hash, error)

Dynasty return dynasty

func (*Block) EventsRoot added in v1.0.0

func (block *Block) EventsRoot() byteutils.Hash

EventsRoot return events root hash.

func (*Block) ExecuteTransaction added in v1.0.0

func (block *Block) ExecuteTransaction(tx *Transaction, ws WorldState) (bool, error)

ExecuteTransaction execute the transaction return giveback, err system error: giveback == true logic error: giveback == false, expect Bigger Nonce

func (*Block) FetchEvents added in v1.0.0

func (block *Block) FetchEvents(txHash byteutils.Hash) ([]*state.Event, error)

FetchEvents fetch events by txHash.

func (*Block) FetchExecutionResultEvent added in v1.0.0

func (block *Block) FetchExecutionResultEvent(txHash byteutils.Hash) (*state.Event, error)

FetchExecutionResultEvent fetch execution result event by txHash.

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) GetAccount added in v1.0.0

func (block *Block) GetAccount(address byteutils.Hash) (state.Account, error)

GetAccount return the account with the given address on this block.

func (*Block) GetTransaction added in v1.0.0

func (block *Block) GetTransaction(hash byteutils.Hash) (*Transaction, error)

GetTransaction from txs Trie

func (*Block) HasRandomSeed added in v1.0.2

func (block *Block) HasRandomSeed() bool

HasRandomSeed check random if exists

func (*Block) Hash

func (block *Block) Hash() byteutils.Hash

Hash return block hash.

func (*Block) Height

func (block *Block) Height() uint64

Height return height

func (*Block) LinkParentBlock

func (block *Block) LinkParentBlock(chain *BlockChain, parentBlock *Block) error

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

func (*Block) ParentHash

func (block *Block) ParentHash() byteutils.Hash

ParentHash return parent hash.

func (*Block) RandomAvailable added in v1.0.2

func (block *Block) RandomAvailable() bool

RandomAvailable check if Math.random available in contract

func (*Block) RandomProof added in v1.0.5

func (block *Block) RandomProof() string

RandomProof block random proof (VRF)

func (*Block) RandomSeed added in v1.0.2

func (block *Block) RandomSeed() string

RandomSeed block random seed (VRF)

func (*Block) ReturnTransactions added in v1.0.0

func (block *Block) ReturnTransactions()

ReturnTransactions and giveback them to tx pool if a block is reverted, we should erase all changes made by this block on storage. use refcount.

func (*Block) RollBack added in v1.0.0

func (block *Block) RollBack()

RollBack a batch task

func (*Block) Seal

func (block *Block) Seal() error

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) SetRandomSeed added in v1.0.2

func (block *Block) SetRandomSeed(vrfseed, vrfproof []byte)

SetRandomSeed set block.header.random

func (*Block) SetSignature added in v1.0.0

func (block *Block) SetSignature(alg keystore.Algorithm, sign byteutils.Hash)

SetSignature set the signature

func (*Block) SetTimestamp

func (block *Block) SetTimestamp(timestamp int64)

SetTimestamp set timestamp

func (*Block) Sign added in v1.0.0

func (block *Block) Sign(signature keystore.Signature) error

Sign sign transaction,sign algorithm is

func (*Block) Signature added in v1.0.0

func (block *Block) Signature() byteutils.Hash

Signature return block's signature

func (*Block) StateRoot

func (block *Block) StateRoot() byteutils.Hash

StateRoot return state root hash.

func (*Block) Storage added in v1.0.0

func (block *Block) Storage() storage.Storage

Storage return storage.

func (*Block) String

func (block *Block) String() string

func (*Block) Timestamp added in v1.0.0

func (block *Block) Timestamp() int64

Timestamp return timestamp

func (*Block) ToProto added in v0.2.0

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

ToProto converts domain Block into proto Block

func (*Block) Transactions added in v1.0.0

func (block *Block) Transactions() Transactions

Transactions returns block transactions

func (*Block) TxsRoot added in v0.2.0

func (block *Block) TxsRoot() byteutils.Hash

TxsRoot return txs root hash.

func (*Block) VerifyExecution added in v1.0.0

func (block *Block) VerifyExecution() error

VerifyExecution execute the block and verify the execution result.

func (*Block) VerifyIntegrity added in v1.0.0

func (block *Block) VerifyIntegrity(chainID uint32, consensus Consensus) error

VerifyIntegrity verify block's hash, txs' integrity and consensus acceptable.

func (*Block) WorldState added in v1.0.0

func (block *Block) WorldState() state.WorldState

WorldState return the world state of the block

type BlockChain

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

BlockChain the BlockChain core type.

func NewBlockChain

func NewBlockChain(neb Neblet) (*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) CheckGenesisConfig added in v1.0.0

func (bc *BlockChain) CheckGenesisConfig(neb Neblet) error

CheckGenesisConfig check if the genesis and config is valid

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) EventEmitter added in v1.0.0

func (bc *BlockChain) EventEmitter() *EventEmitter

EventEmitter return the eventEmitter.

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) GasPrice added in v1.0.0

func (bc *BlockChain) GasPrice() *util.Uint128

GasPrice returns the lowest transaction gas price.

func (*BlockChain) GenesisBlock added in v1.0.0

func (bc *BlockChain) GenesisBlock() *Block

GenesisBlock return the genesis block.

func (*BlockChain) GetBlock

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

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

func (*BlockChain) GetBlockOnCanonicalChainByHash added in v1.0.0

func (bc *BlockChain) GetBlockOnCanonicalChainByHash(blockHash byteutils.Hash) *Block

GetBlockOnCanonicalChainByHash check if a block is on canonical chain

func (*BlockChain) GetBlockOnCanonicalChainByHeight added in v1.0.0

func (bc *BlockChain) GetBlockOnCanonicalChainByHeight(height uint64) *Block

GetBlockOnCanonicalChainByHeight return block in given height

func (*BlockChain) GetContract added in v1.0.2

func (bc *BlockChain) GetContract(addr *Address) (state.Account, error)

GetContract return contract of given address

func (*BlockChain) GetInputForVRFSigner added in v1.0.2

func (bc *BlockChain) GetInputForVRFSigner(parentHash byteutils.Hash, height uint64) (ancestorHash, parentSeed []byte, err error)

GetInputForVRFSigner returns [ getBlock(block.height - 2 * dynasty.size).hash, block.parent.seed ]

func (*BlockChain) GetTransaction added in v0.3.0

func (bc *BlockChain) GetTransaction(hash byteutils.Hash) (*Transaction, error)

GetTransaction return transaction of given hash from local storage.

func (*BlockChain) IsActiveSyncing added in v1.0.5

func (bc *BlockChain) IsActiveSyncing() bool

IsActiveSyncing returns true if being syncing

func (*BlockChain) LIB added in v1.0.0

func (bc *BlockChain) LIB() *Block

LIB return the latest irrversible block

func (*BlockChain) LoadGenesisFromStorage added in v1.0.0

func (bc *BlockChain) LoadGenesisFromStorage() (*Block, error)

LoadGenesisFromStorage load genesis

func (*BlockChain) LoadLIBFromStorage added in v1.0.0

func (bc *BlockChain) LoadLIBFromStorage() (*Block, error)

LoadLIBFromStorage load LIB

func (*BlockChain) LoadTailFromStorage added in v1.0.0

func (bc *BlockChain) LoadTailFromStorage() (*Block, error)

LoadTailFromStorage load tail block

func (*BlockChain) NewBlock

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

NewBlock create new #Block instance.

func (*BlockChain) NewBlockFromParent

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

NewBlockFromParent create new block from parent block and return it.

func (*BlockChain) SetConsensusHandler

func (bc *BlockChain) SetConsensusHandler(handler Consensus)

SetConsensusHandler set consensus handler.

func (*BlockChain) SetLIB added in v1.0.0

func (bc *BlockChain) SetLIB(lib *Block)

SetLIB update the latest irrversible block

func (*BlockChain) SetSyncService added in v1.0.0

func (bc *BlockChain) SetSyncService(syncService SyncService)

SetSyncService set sync service.

func (*BlockChain) SetTailBlock

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

SetTailBlock set tail block.

func (*BlockChain) Setup added in v1.0.0

func (bc *BlockChain) Setup(neb Neblet) error

Setup the blockchain

func (*BlockChain) SimulateTransactionExecution added in v1.0.0

func (bc *BlockChain) SimulateTransactionExecution(tx *Transaction) (*SimulateResult, error)

SimulateTransactionExecution execute transaction in sandbox and rollback all changes, used to EstimateGas and Call api.

func (*BlockChain) Start added in v1.0.0

func (bc *BlockChain) Start()

Start start loop.

func (*BlockChain) StartActiveSync added in v1.0.0

func (bc *BlockChain) StartActiveSync() bool

StartActiveSync start active sync task

func (*BlockChain) Stop added in v1.0.0

func (bc *BlockChain) Stop()

Stop stop loop.

func (*BlockChain) Storage added in v0.3.0

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

Storage return the storage.

func (*BlockChain) StoreBlockToStorage added in v1.0.0

func (bc *BlockChain) StoreBlockToStorage(block *Block) error

StoreBlockToStorage store block

func (*BlockChain) StoreLIBHashToStorage added in v1.0.0

func (bc *BlockChain) StoreLIBHashToStorage(block *Block) error

StoreLIBHashToStorage store LIB block hash

func (*BlockChain) StoreTailHashToStorage added in v1.0.0

func (bc *BlockChain) StoreTailHashToStorage(block *Block) error

StoreTailHashToStorage store tail block hash

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(size int) (*BlockPool, error)

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(sender string, block *Block) error

PushAndRelay push block into block pool and relay it.

func (*BlockPool) RegisterInNetwork

func (pool *BlockPool) RegisterInNetwork(ns net.Service)

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 CallPayload added in v1.0.0

type CallPayload struct {
	Function string
	Args     string
}

CallPayload carry function call information

func LoadCallPayload added in v1.0.0

func LoadCallPayload(bytes []byte) (*CallPayload, error)

LoadCallPayload from bytes

func NewCallPayload added in v1.0.0

func NewCallPayload(function, args string) (*CallPayload, error)

NewCallPayload with function & args

func (*CallPayload) BaseGasCount added in v1.0.0

func (payload *CallPayload) BaseGasCount() *util.Uint128

BaseGasCount returns base gas count

func (*CallPayload) Execute added in v1.0.0

func (payload *CallPayload) Execute(limitedGas *util.Uint128, tx *Transaction, block *Block, ws WorldState) (*util.Uint128, string, error)

Execute the call payload in tx, call a function

func (*CallPayload) ToBytes added in v1.0.0

func (payload *CallPayload) ToBytes() ([]byte, error)

ToBytes serialize payload

type Consensus

type Consensus interface {
	Setup(Neblet) error
	Start()
	Stop()

	EnableMining(string) error
	DisableMining() error
	Enable() bool

	ResumeMining()
	SuspendMining()
	Pending() bool

	VerifyBlock(*Block) error
	ForkChoice() error
	UpdateLIB()

	NewState(*consensuspb.ConsensusRoot, storage.Storage, bool) (state.ConsensusState, error)
	GenesisConsensusState(*BlockChain, *corepb.Genesis) (state.ConsensusState, error)
	CheckTimeout(*Block) bool
	CheckDoubleMint(*Block) bool

	NumberOfBlocksInDynasty() uint64
}

Consensus interface of consensus algorithm.

type ContractTxFrom added in v1.0.0

type ContractTxFrom []byte

ContractTxFrom tx from

type ContractTxNonce added in v1.0.0

type ContractTxNonce []byte

ContractTxNonce tx nonce

type DeployPayload added in v1.0.0

type DeployPayload struct {
	SourceType string
	Source     string
	Args       string
}

DeployPayload carry contract deploy information

func LoadDeployPayload added in v1.0.0

func LoadDeployPayload(bytes []byte) (*DeployPayload, error)

LoadDeployPayload from bytes

func NewDeployPayload added in v1.0.0

func NewDeployPayload(source, sourceType, args string) (*DeployPayload, error)

NewDeployPayload with source & args

func (*DeployPayload) BaseGasCount added in v1.0.0

func (payload *DeployPayload) BaseGasCount() *util.Uint128

BaseGasCount returns base gas count

func (*DeployPayload) Execute added in v1.0.0

func (payload *DeployPayload) Execute(limitedGas *util.Uint128, tx *Transaction, block *Block, ws WorldState) (*util.Uint128, string, error)

Execute deploy payload in tx, deploy a new contract

func (*DeployPayload) ToBytes added in v1.0.0

func (payload *DeployPayload) ToBytes() ([]byte, error)

ToBytes serialize payload

type EventEmitter added in v1.0.0

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

EventEmitter provide event functionality for Nebulas.

func NewEventEmitter added in v1.0.0

func NewEventEmitter(size int) *EventEmitter

NewEventEmitter return new EventEmitter.

func (*EventEmitter) Deregister added in v1.0.0

func (emitter *EventEmitter) Deregister(subscribers ...*EventSubscriber)

Deregister deregister event chan.

func (*EventEmitter) Register added in v1.0.0

func (emitter *EventEmitter) Register(subscribers ...*EventSubscriber)

Register register event chan.

func (*EventEmitter) Start added in v1.0.0

func (emitter *EventEmitter) Start()

Start start emitter.

func (*EventEmitter) Stop added in v1.0.0

func (emitter *EventEmitter) Stop()

Stop stop emitter.

func (*EventEmitter) Trigger added in v1.0.0

func (emitter *EventEmitter) Trigger(e *state.Event)

Trigger trigger event.

type EventSubscriber added in v1.0.0

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

EventSubscriber subscriber object

func NewEventSubscriber added in v1.0.0

func NewEventSubscriber(size int, topics []string) *EventSubscriber

NewEventSubscriber returns an EventSubscriber

func (*EventSubscriber) EventChan added in v1.0.0

func (s *EventSubscriber) EventChan() chan *state.Event

EventChan returns subscriber's eventCh

type NVM added in v1.0.0

type NVM interface {
	CreateEngine(block *Block, tx *Transaction, contract state.Account, ws WorldState) (SmartContractEngine, error)
	CheckV8Run() error
}

NVM interface

type Neblet added in v1.0.0

type Neblet interface {
	Genesis() *corepb.Genesis
	SetGenesis(*corepb.Genesis)
	Config() *nebletpb.Config
	Storage() storage.Storage
	EventEmitter() *EventEmitter
	Consensus() Consensus
	BlockChain() *BlockChain
	NetService() net.Service
	IsActiveSyncing() bool
	AccountManager() AccountManager
	Nvm() NVM
	StartPprof(string) error
}

Neblet interface breaks cycle import dependency and hides unused services.

type SimulateResult added in v1.0.0

type SimulateResult struct {
	GasUsed *util.Uint128
	Msg     string
	Err     error
}

SimulateResult the result of simulating transaction execution

type SmartContractEngine added in v1.0.0

type SmartContractEngine interface {
	SetExecutionLimits(uint64, uint64) error
	DeployAndInit(source, sourceType, args string) (string, error)
	Call(source, sourceType, function, args string) (string, error)
	ExecutionInstructions() uint64
	Dispose()
}

SmartContractEngine interface

type SyncService added in v1.0.0

type SyncService interface {
	Start()
	Stop()

	StartActiveSync() bool
	StopActiveSync()
	WaitingForFinish()
	IsActiveSyncing() bool
}

SyncService interface of sync service

type Transaction

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

Transaction type is used to handle all transaction data.

func GetTransaction added in v1.0.0

func GetTransaction(hash byteutils.Hash, ws WorldState) (*Transaction, error)

GetTransaction from txs Trie

func NewTransaction

func NewTransaction(chainID uint32, from, to *Address, value *util.Uint128, nonce uint64, payloadType string, payload []byte, gasPrice *util.Uint128, gasLimit *util.Uint128) (*Transaction, error)

NewTransaction create #Transaction instance.

func (*Transaction) ChainID added in v1.0.0

func (tx *Transaction) ChainID() uint32

ChainID return chainID

func (*Transaction) Data added in v1.0.0

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

Data return tx data

func (*Transaction) DataLen added in v0.2.0

func (tx *Transaction) DataLen() int

DataLen return the length of payload

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) GasCountOfTxBase added in v1.0.0

func (tx *Transaction) GasCountOfTxBase() (*util.Uint128, error)

GasCountOfTxBase calculate the actual amount for a tx with data

func (*Transaction) GasLimit added in v1.0.0

func (tx *Transaction) GasLimit() *util.Uint128

GasLimit returns gasLimit

func (*Transaction) GasPrice added in v1.0.0

func (tx *Transaction) GasPrice() *util.Uint128

GasPrice returns gasPrice

func (*Transaction) GenerateContractAddress added in v1.0.0

func (tx *Transaction) GenerateContractAddress() (*Address, error)

GenerateContractAddress according to tx.from and tx.nonce.

func (*Transaction) Hash

func (tx *Transaction) Hash() byteutils.Hash

Hash return the hash of transaction.

func (*Transaction) JSONString added in v1.0.3

func (tx *Transaction) JSONString() string

JSONString of transaction

func (*Transaction) LoadPayload added in v1.0.0

func (tx *Transaction) LoadPayload() (TxPayload, error)

LoadPayload returns tx's payload

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) StringWithoutData added in v1.0.3

func (tx *Transaction) StringWithoutData() string

func (*Transaction) Timestamp added in v1.0.0

func (tx *Transaction) Timestamp() int64

Timestamp return timestamp

func (*Transaction) To added in v1.0.0

func (tx *Transaction) To() *Address

To return to 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) Type added in v1.0.0

func (tx *Transaction) Type() string

Type return tx type

func (*Transaction) Value added in v1.0.0

func (tx *Transaction) Value() *util.Uint128

Value return tx value

func (*Transaction) VerifyIntegrity added in v1.0.0

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

VerifyIntegrity return transaction verify result, including Hash and Signature.

type TransactionEvent added in v1.0.0

type TransactionEvent struct {
	Hash    string `json:"hash"`
	Status  int8   `json:"status"`
	GasUsed string `json:"gas_used"`
	Error   string `json:"error"`
}

TransactionEvent transaction event

type TransactionEventV2 added in v1.0.2

type TransactionEventV2 struct {
	Hash          string `json:"hash"`
	Status        int8   `json:"status"`
	GasUsed       string `json:"gas_used"`
	Error         string `json:"error"`
	ExecuteResult string `json:"execute_result"`
}

TransactionEventV2 add execution result

type TransactionPool

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

TransactionPool cache txs, is thread safe

func NewTransactionPool

func NewTransactionPool(size int) (*TransactionPool, error)

NewTransactionPool create a new TransactionPool

func (*TransactionPool) Del added in v1.0.0

func (pool *TransactionPool) Del(tx *Transaction)

Del a transaction from pool

func (*TransactionPool) Empty added in v0.2.0

func (pool *TransactionPool) Empty() bool

Empty return if the pool is empty

func (*TransactionPool) GetTransaction added in v1.0.0

func (pool *TransactionPool) GetTransaction(hash byteutils.Hash) *Transaction

GetTransaction return transaction of given hash from transaction pool.

func (*TransactionPool) Pop added in v0.2.0

func (pool *TransactionPool) Pop() *Transaction

Pop a transaction from pool

func (*TransactionPool) PopWithBlacklist added in v1.0.0

func (pool *TransactionPool) PopWithBlacklist(fromBlacklist *sync.Map, toBlacklist *sync.Map) *Transaction

PopWithBlacklist return a tx with highest gasprice and not in the blocklist

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(ns net.Service)

RegisterInNetwork register message subscriber in network.

func (*TransactionPool) SetGasConfig added in v1.0.0

func (pool *TransactionPool) SetGasConfig(gasPrice, gasLimit *util.Uint128) error

SetGasConfig config the lowest gasPrice and the maximum gasLimit.

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.

type TxPayload added in v1.0.0

type TxPayload interface {
	ToBytes() ([]byte, error)
	BaseGasCount() *util.Uint128
	Execute(limitedGas *util.Uint128, tx *Transaction, block *Block, ws WorldState) (*util.Uint128, string, error)
}

TxPayload stored in tx

type WorldState added in v1.0.0

type WorldState interface {
	GetOrCreateUserAccount(addr byteutils.Hash) (state.Account, error)
	GetContractAccount(addr byteutils.Hash) (state.Account, error)
	CreateContractAccount(owner byteutils.Hash, birthPlace byteutils.Hash, contractMeta *corepb.ContractMeta) (state.Account, error)

	GetTx(txHash byteutils.Hash) ([]byte, error)
	PutTx(txHash byteutils.Hash, txBytes []byte) error

	RecordEvent(txHash byteutils.Hash, event *state.Event)
	FetchEvents(byteutils.Hash) ([]*state.Event, error)

	Dynasty() ([]byteutils.Hash, error)
	DynastyRoot() byteutils.Hash

	RecordGas(from string, gas *util.Uint128) error

	Reset(addr byteutils.Hash) error
	GetBlockHashByHeight(height uint64) ([]byte, error)
	GetBlock(txHash byteutils.Hash) ([]byte, error)
}

WorldState needed by core

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