Help us shape the future of Go! Take the 2026 Go Developer Survey

chain

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2018 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BlockMsgChBufferSize        = 1024
	EternalBlockMsgChBufferSize = 65536

	MaxTimeOffsetSeconds = 2 * 60 * 60
	MaxBlockSize         = 32000000
	CoinbaseLib          = 100

	LockTimeThreshold = 5e8 // Tue Nov 5 00:53:20 1985 UTC
	PeriodDuration    = 3600 * 24 * 100 / 5

	MaxBlocksPerSync = 1024

	BlockFilterCapacity = 100000

	Threshold = 32
)

const defines constants

View Source
const (
	// BlockTableName is the table name of db to store block chain data
	BlockTableName = "core"

	// Tail is the db key name of tail block
	Tail = "/tail"

	// Eternal is the db key name of eternal block
	Eternal = "/eternal"

	// Period is the db key name of current period
	Period = "/period/current"

	// BlockPrefix is the key prefix of database key to store block content
	// /bk/{hex encoded block hash}
	// e.g.
	// key: /bk/005973c44c4879b137c3723c96d2e341eeaf83fe58845b2975556c9f3bd640bb
	// value: block binary
	BlockPrefix = "/bk"

	// BlockHashPrefix is the key prefix of database key to store block hash of specified height
	// /bh/{hex encoded height}
	//e.g.
	// key: /bh/3e2d
	// value: block hash binary
	BlockHashPrefix = "/bh"

	// TxIndexPrefix is the key prefix of database key to store tx index
	// /ti/{hex encoded tx hash}
	// e.g.
	// key: /ti/1113b8bdad74cdc045e64e09b3e2f0502d1b7f9bd8123b28239a3360bd3a8757
	// value: 4 bytes height + 4 bytes index in txs
	TxIndexPrefix = "/ti"

	// UtxoPrefix is the key prefix of database key to store utxo content
	// /ut/{hex encoded tx hash}/{vout index}
	// e.g.
	// key: /ut/1113b8bdad74cdc045e64e09b3e2f0502d1b7f9bd8123b28239a3360bd3a8757/2
	// value: utxo wrapper
	UtxoPrefix = "/ut"

	// CandidatesPrefix is the key prefix of database key to store candidates
	CandidatesPrefix = "/candidates"
	// FilterPrefix is the key prefix of block bloom filter to store a filter bytes
	// /bf/{hex encoded block hash}
	// e.g.
	// key: /bf/1113b8bdad74cdc045e64e09b3e2f0502d1b7f9bd8123b28239a3360bd3a8757
	// value: crypto hash
	FilterPrefix = "/bf"
)

Variables

View Source
var (

	// TotalSupply is the total supply of box: 3 billion
	TotalSupply = (uint64)(3e9 * math.Pow10(core.Decimals))

	// CoinbaseMaturity coinbase only spendable after this many blocks
	CoinbaseMaturity = (uint32)(0)

	// BaseSubsidy is the starting subsidy amount for mined blocks.
	// This value is halved every SubsidyReductionInterval blocks.
	BaseSubsidy = (uint64)(50 * math.Pow10(core.Decimals))
)
View Source
var EternalKey = []byte(Eternal)

EternalKey is the db key to stoare eternal block content

View Source
var GenesisBlock = types.Block{
	Header: &types.BlockHeader{
		Version:       1,
		PrevBlockHash: crypto.HashType{},
		TxsRoot:       genesisMerkleRoot,
		TimeStamp:     time.Date(2018, 1, 31, 0, 0, 0, 0, time.UTC).Unix(),
	},
	Txs:    []*types.Transaction{&genesisCoinbaseTx},
	Height: 0,
}

GenesisBlock represents genesis block.

View Source
var GenesisHash = *(GenesisBlock.BlockHash())

GenesisHash is the hash of genesis block

View Source
var GenesisPeriod = []map[string]string{
	{
		"addr":   "b1ndoQmEd83y4Fza5PzbUQDYpT3mV772J5o",
		"peerID": "12D3KooWFQ2naj8XZUVyGhFzBTEMrMc6emiCEDKLjaJMsK7p8Cza",
	},
	{
		"addr":   "b1b8bzyci5VYUJVKRU2HRMMQiUXnoULkKAJ",
		"peerID": "12D3KooWKPRAK7vBBrVv9szEin55kBnJEEuHG4gDTQEM72ByZDpA",
	},
	{
		"addr":   "b1jh8DSdB6kB7N7RanrudV1hzzMCCcoX6L7",
		"peerID": "12D3KooWSdXLNeoRQQ2a7yiS6xLpTn3LdCr8B8fqPz94Bbi7itsi",
	},
	{
		"addr":   "b1UP5pbfJgZrF1ezoSHLdvkxvgF2BYLtGva",
		"peerID": "12D3KooWRHVAwymCVcA8jqyjpP3r3HBkCW2q5AZRTBvtaungzFSJ",
	},
	{
		"addr":   "b1ZWSdrg48g145VdcmBwMPVuDFdaxDLoktk",
		"peerID": "12D3KooWQSaxCgbWakLcU69f4gmNFMszwhyHbwx4xPAhV7erDC2P",
	},
	{
		"addr":   "b1fRtRnKF4qhQG7bSwqbgR2BMw9VfM2XpT4",
		"peerID": "12D3KooWNcJQzHaNpW5vZDQbTcoLXVCyGS755hTpendGzb5Hqtcu",
	},
}

GenesisPeriod genesis period

View Source
var PeriodKey = []byte(Period)

PeriodKey is the db key to stoare current period contex content

View Source
var TailKey = []byte(Tail)

TailKey is the db key to stoare tail block content

Functions

func BlockHashKey

func BlockHashKey(height uint32) []byte

BlockHashKey returns the db key to stoare block hash content of the height

func BlockKey

func BlockKey(h *crypto.HashType) []byte

BlockKey returns the db key to stoare block content of the hash

func CalcBlockSubsidy

func CalcBlockSubsidy(height uint32) uint64

CalcBlockSubsidy returns the subsidy amount a block at the provided height should have.

func CalcTxsHash

func CalcTxsHash(txs []*types.Transaction) *crypto.HashType

CalcTxsHash calculate txsHash in block.

func CandidatesKey

func CandidatesKey(h *crypto.HashType) []byte

CandidatesKey returns the db key to stoare candidates.

func CreateCoinbaseTx

func CreateCoinbaseTx(addr []byte, blockHeight uint32) (*types.Transaction, error)

CreateCoinbaseTx creates a coinbase give miner address and block height

func FilterKey

func FilterKey(hash crypto.HashType) []byte

FilterKey returns the db key to store bloom filter of block

func GetFilterForTransactionScript

func GetFilterForTransactionScript(block *types.Block, utxoUsed map[types.OutPoint]*types.UtxoWrap) bloom.Filter

GetFilterForTransactionScript returns the bloom filter for all the script address of the transactions in the block, it will use the pre-calculated filter if there is any

func IsCoinBase

func IsCoinBase(tx *types.Transaction) bool

IsCoinBase determines whether or not a transaction is a coinbase.

func IsTxFinalized

func IsTxFinalized(tx *types.Transaction, blockHeight uint32, blockTime int64) bool

IsTxFinalized checks if a transaction is finalized.

func MarshalTxIndex

func MarshalTxIndex(height, index uint32) (data []byte, err error)

MarshalTxIndex writes Tx height and index to bytes

func TxIndexKey

func TxIndexKey(h *crypto.HashType) []byte

TxIndexKey returns the db key to stoare tx index of the hash

func UnmarshalTxIndex

func UnmarshalTxIndex(data []byte) (height uint32, index uint32, err error)

UnmarshalTxIndex return tx index from bytes

func UtxoKey

func UtxoKey(op *types.OutPoint) []byte

UtxoKey returns the db key to stoare utxo content of the Outpoint

func ValidateTransactionPreliminary

func ValidateTransactionPreliminary(tx *types.Transaction) error

ValidateTransactionPreliminary performs some preliminary checks on a transaction to ensure it is sane. These checks are context free.

func ValidateTxInputs

func ValidateTxInputs(utxoSet *UtxoSet, tx *types.Transaction, txHeight uint32) (uint64, error)

ValidateTxInputs validates the inputs of a tx. Returns the total tx fee.

func ValidateTxScripts

func ValidateTxScripts(utxoSet *UtxoSet, tx *types.Transaction) error

ValidateTxScripts verifies unlocking script for each input to ensure it is authorized to spend the utxo Coinbase tx will not reach here

func VerifyBlockTimeOut

func VerifyBlockTimeOut(block *types.Block) error

VerifyBlockTimeOut refuse to accept a block with wrong timestamp.

Types

type BlockChain

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

BlockChain define chain struct

func NewBlockChain

func NewBlockChain(parent goprocess.Process, notifiee p2p.Net, db storage.Storage, bus eventbus.Bus) (*BlockChain, error)

NewBlockChain return a blockchain.

func NewTestBlockChain

func NewTestBlockChain() *BlockChain

NewTestBlockChain generate a chain for testing

func (*BlockChain) Bus

func (chain *BlockChain) Bus() eventbus.Bus

Bus returns the goprocess of the BlockChain

func (*BlockChain) CalcRootHashForNBlocks

func (chain *BlockChain) CalcRootHashForNBlocks(hash crypto.HashType, num uint32) (*crypto.HashType, error)

CalcRootHashForNBlocks return root hash for N blocks.

func (*BlockChain) DB

func (chain *BlockChain) DB() storage.Table

DB return chain db storage.

func (*BlockChain) DelTxIndex

func (chain *BlockChain) DelTxIndex(block *types.Block) error

DelTxIndex deletes tx index in block

func (*BlockChain) EternalBlock

func (chain *BlockChain) EternalBlock() *types.Block

EternalBlock return chain eternal block.

func (*BlockChain) FetchNBlockAfterSpecificHash

func (chain *BlockChain) FetchNBlockAfterSpecificHash(hash crypto.HashType, num uint32) ([]*types.Block, error)

FetchNBlockAfterSpecificHash get N block after specific hash.

func (*BlockChain) GetBlockHash

func (chain *BlockChain) GetBlockHash(blockHeight uint32) (*crypto.HashType, error)

GetBlockHash finds the block in target height of main chain and returns it's hash

func (*BlockChain) GetBlockHeight

func (chain *BlockChain) GetBlockHeight() uint32

GetBlockHeight returns current height of main chain

func (*BlockChain) GetTransactionsByAddr

func (chain *BlockChain) GetTransactionsByAddr(addr types.Address) ([]*types.Transaction, error)

GetTransactionsByAddr search the main chain about transaction relate to give address

func (*BlockChain) ListAllUtxos

func (chain *BlockChain) ListAllUtxos() (map[types.OutPoint]*types.UtxoWrap, error)

ListAllUtxos list all the available utxos for testing purpose

func (*BlockChain) LoadBlockByHash

func (chain *BlockChain) LoadBlockByHash(hash crypto.HashType) (*types.Block, error)

LoadBlockByHash load block by hash from db.

func (*BlockChain) LoadBlockByHeight

func (chain *BlockChain) LoadBlockByHeight(height uint32) (*types.Block, error)

LoadBlockByHeight load block by height from db.

func (*BlockChain) LoadTxByHash

func (chain *BlockChain) LoadTxByHash(hash crypto.HashType) (*types.Transaction, error)

LoadTxByHash load transaction with hash.

func (*BlockChain) LoadUtxoByAddress

func (chain *BlockChain) LoadUtxoByAddress(addr types.Address) (map[types.OutPoint]*types.UtxoWrap, error)

LoadUtxoByAddress list all the available utxos owned by an address, including token utxos

func (*BlockChain) LocateForkPointAndFetchHeaders

func (chain *BlockChain) LocateForkPointAndFetchHeaders(hashes []*crypto.HashType) ([]*crypto.HashType, error)

LocateForkPointAndFetchHeaders return block headers when get locate fork point request for sync service.

func (*BlockChain) Proc

func (chain *BlockChain) Proc() goprocess.Process

Proc returns the goprocess of the BlockChain

func (*BlockChain) ProcessBlock

func (chain *BlockChain) ProcessBlock(block *types.Block, broadcast bool, fastConfirm bool, messageFrom peer.ID) error

ProcessBlock is used to handle new blocks.

func (*BlockChain) Run

func (chain *BlockChain) Run() error

Run launch blockchain.

func (*BlockChain) SetEternal

func (chain *BlockChain) SetEternal(block *types.Block) error

SetEternal set block eternal status.

func (*BlockChain) SetTailBlock

func (chain *BlockChain) SetTailBlock(tail *types.Block) error

SetTailBlock sets chain tail block.

func (*BlockChain) Setup

func (chain *BlockChain) Setup(consensus types.Consensus, syncManager types.SyncManager)

Setup prepare blockchain.

func (*BlockChain) Stop

func (chain *BlockChain) Stop()

Stop the blockchain service

func (*BlockChain) StoreBlockToDb

func (chain *BlockChain) StoreBlockToDb(block *types.Block) error

StoreBlockToDb store block to db.

func (*BlockChain) StoreEternalBlock

func (chain *BlockChain) StoreEternalBlock(block *types.Block) error

StoreEternalBlock store eternal block to db.

func (*BlockChain) StoreTailBlock

func (chain *BlockChain) StoreTailBlock(block *types.Block) error

StoreTailBlock store tail block to db.

func (*BlockChain) TailBlock

func (chain *BlockChain) TailBlock() *types.Block

TailBlock return chain tail block.

func (*BlockChain) WriteTxIndex

func (chain *BlockChain) WriteTxIndex(block *types.Block) error

WriteTxIndex builds tx index in block

type BloomFilterHolder

type BloomFilterHolder interface {
	ResetFilters(uint32) error
	ListMatchedBlockHashes([]byte) []crypto.HashType
	AddFilter(uint32, crypto.HashType, storage.Table, func() bloom.Filter) error
}

BloomFilterHolder holds all bloom filters in main chain

func NewFilterHolder

func NewFilterHolder() BloomFilterHolder

NewFilterHolder creates an holder instance

type DummyDpos

type DummyDpos struct{}

DummyDpos dummy dpos

func (*DummyDpos) BroadcastEternalMsgToMiners

func (dpos *DummyDpos) BroadcastEternalMsgToMiners(block *types.Block) error

BroadcastEternalMsgToMiners broadcast etrnalmsg to miners

func (*DummyDpos) RecoverMint

func (dpos *DummyDpos) RecoverMint()

RecoverMint revover mint

func (*DummyDpos) Run

func (dpos *DummyDpos) Run() error

Run dummy dpos

func (*DummyDpos) Stop

func (dpos *DummyDpos) Stop()

Stop dummy dpos

func (*DummyDpos) StopMint

func (dpos *DummyDpos) StopMint()

StopMint stop mint

func (*DummyDpos) StoreCandidateContext

func (dpos *DummyDpos) StoreCandidateContext(*crypto.HashType) error

StoreCandidateContext store candidate context

func (*DummyDpos) ValidateMiner

func (dpos *DummyDpos) ValidateMiner() bool

ValidateMiner validate miner

func (*DummyDpos) VerifyMinerEpoch

func (dpos *DummyDpos) VerifyMinerEpoch(*types.Block) error

VerifyMinerEpoch verify miner epoch

func (*DummyDpos) VerifySign

func (dpos *DummyDpos) VerifySign(*types.Block) (bool, error)

VerifySign verify sign

type DummySyncManager

type DummySyncManager struct{}

DummySyncManager is only used to test

func NewDummySyncManager

func NewDummySyncManager() *DummySyncManager

NewDummySyncManager returns a new DummySyncManager

func (*DummySyncManager) ActiveLightSync

func (dm *DummySyncManager) ActiveLightSync(pid peer.ID) error

ActiveLightSync active light sync from remote peer.

func (*DummySyncManager) Run

func (dm *DummySyncManager) Run()

Run starts run

func (*DummySyncManager) StartSync

func (dm *DummySyncManager) StartSync()

StartSync starts sync

type FilterEntry

type FilterEntry struct {
	Filter    bloom.Filter
	Height    uint32
	BlockHash crypto.HashType
}

FilterEntry represents a bloom filter for the block of the given hash

type LockTime

type LockTime struct {
	Seconds     int64
	BlockHeight uint32
}

LockTime represents the relative lock-time in seconds

type MemoryBloomFilterHolder

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

MemoryBloomFilterHolder holds all bloom filters in main chain in an array format in memory

func (*MemoryBloomFilterHolder) AddFilter

func (holder *MemoryBloomFilterHolder) AddFilter(
	height uint32,
	hash crypto.HashType,
	db storage.Table,
	onCacheMiss func() bloom.Filter) error

AddFilter adds a filter of block at height. Filter is loaded from db instance if it is stored, otherwise, it's calculated using onCacheMiss function

func (*MemoryBloomFilterHolder) ListMatchedBlockHashes

func (holder *MemoryBloomFilterHolder) ListMatchedBlockHashes(word []byte) []crypto.HashType

ListMatchedBlockHashes search all blocks' bloom filter, and returns block hashes that might contain a certain word

func (*MemoryBloomFilterHolder) ResetFilters

func (holder *MemoryBloomFilterHolder) ResetFilters(height uint32) error

ResetFilters resets filterEntry array to a height

type TxWrap

type TxWrap struct {
	Tx             *types.Transaction
	AddedTimestamp int64
	Height         uint32
	FeePerKB       uint64
}

TxWrap wrap transaction

type UpdateMsg

type UpdateMsg struct {
	// block connected/disconnected from main chain
	Connected bool
	Block     *types.Block
}

UpdateMsg sent from blockchain to, e.g., mempool

type UtxoSet

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

UtxoSet contains all utxos

func GetExtendedTxUtxoSet

func GetExtendedTxUtxoSet(tx *types.Transaction, db storage.Table,
	spendableTxs *sync.Map) (*UtxoSet, error)

GetExtendedTxUtxoSet returns tx's utxo set from both db & txs in spendableTxs

func NewUtxoSet

func NewUtxoSet() *UtxoSet

NewUtxoSet new utxo set

func NewUtxoSetFromMap

func NewUtxoSetFromMap(utxoMap map[types.OutPoint]*types.UtxoWrap) *UtxoSet

NewUtxoSetFromMap returns the underlying utxos as a map

func (*UtxoSet) AddUtxo

func (u *UtxoSet) AddUtxo(tx *types.Transaction, txOutIdx uint32, blockHeight uint32) error

AddUtxo adds a tx's outputs as utxos

func (*UtxoSet) ApplyBlock

func (u *UtxoSet) ApplyBlock(block *types.Block) error

ApplyBlock updates utxos with all transactions in the passed block

func (*UtxoSet) ApplyBlockWithScriptFilter

func (u *UtxoSet) ApplyBlockWithScriptFilter(block *types.Block, targetScript []byte) error

ApplyBlockWithScriptFilter adds or remove all utxos that transactions use or generate with the specified script bytes

func (*UtxoSet) ApplyTx

func (u *UtxoSet) ApplyTx(tx *types.Transaction, blockHeight uint32) error

ApplyTx updates utxos with the passed tx: adds all utxos in outputs and delete all utxos in inputs.

func (*UtxoSet) ApplyTxWithScriptFilter

func (u *UtxoSet) ApplyTxWithScriptFilter(tx *types.Transaction, blockHeight uint32, targetScript []byte) error

ApplyTxWithScriptFilter adds or remove an utxo if the transaction uses or generates an utxo with the specified script bytes

func (*UtxoSet) FindUtxo

func (u *UtxoSet) FindUtxo(outPoint types.OutPoint) *types.UtxoWrap

FindUtxo returns information about an outpoint.

func (*UtxoSet) GetUtxos

func (u *UtxoSet) GetUtxos() map[types.OutPoint]*types.UtxoWrap

GetUtxos returns the unspent utxos

func (*UtxoSet) IsTxFunded

func (u *UtxoSet) IsTxFunded(tx *types.Transaction) bool

IsTxFunded returns if a tx is funded, i.e., if all of its spending utxos exist

func (*UtxoSet) LoadBlockUtxos

func (u *UtxoSet) LoadBlockUtxos(block *types.Block, db storage.Table) error

LoadBlockUtxos loads the unspent transaction outputs related to block

func (*UtxoSet) LoadTxUtxos

func (u *UtxoSet) LoadTxUtxos(tx *types.Transaction, db storage.Table) error

LoadTxUtxos loads the unspent transaction outputs related to tx

func (*UtxoSet) RevertBlock

func (u *UtxoSet) RevertBlock(block *types.Block) error

RevertBlock undoes utxo changes made with all the transactions in the passed block It undoes the effect of ApplyBlock on utxo set

func (*UtxoSet) RevertTx

func (u *UtxoSet) RevertTx(tx *types.Transaction, blockHeight uint32) error

RevertTx updates utxos with the passed tx: delete all utxos in outputs and add all utxos in inputs. It undoes the effect of ApplyTx on utxo set

func (*UtxoSet) SpendUtxo

func (u *UtxoSet) SpendUtxo(outPoint types.OutPoint)

SpendUtxo mark a utxo as the spent state.

func (*UtxoSet) WriteUtxoSetToDB

func (u *UtxoSet) WriteUtxoSetToDB(db storage.Table) error

WriteUtxoSetToDB store utxo set to database.

Jump to

Keyboard shortcuts

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