chain

package
v0.0.0-...-d9e9b57 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2018 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxBlockTransactions   = 100000
	MaxBlockSerializedSize = 2000000
)
View Source
const (
	MaxBlockBaseSize = 1000000
)

Variables

View Source
var ErrBlockBadMerkleRoot = errors.New("block merkle root is invalid")
View Source
var ErrBlockDuplicateTx = errors.New("block contains duplicate transaction")
View Source
var ErrBlockNoTransactions = errors.New("block does not contain any transactions")
View Source
var ErrBlockSizeTooBig = errors.New("block serialized is too big")
View Source
var ErrBlockTooManyTransactions = errors.New("block has too many transactions")
View Source
var ErrFirstTxNotCoinbase = errors.New("first transaction in block is not a coinbase")
View Source
var ErrMultipleCoinbases = errors.New("block contains second coinbase transaction")
View Source
var ErrNotVerifyTransaction = errors.New("block has not verfiy transaction")
View Source
var ErrorAlreadyExistsBlock = errors.New("already exists such block")
View Source
var ErrorBlockChainNotFount = errors.New("blockchain is not found")
View Source
var ErrorNoExistsAnyBlock = errors.New("not exists any block")
View Source
var ErrorNotFoundTransaction = errors.New("not found the transaction")

Functions

func BigToCompact

func BigToCompact(n *big.Int) uint32

BigToCompact converts a whole number N to a compact representation using an unsigned 32-bit number. The compact representation only provides 23 bits of precision, so values larger than (2^23 - 1) only encode the most significant digits of the number. See CompactToBig for details.

func CalcWork

func CalcWork(bits uint32) *big.Int

CalcWork calculates a work value from difficulty bits. Bitcoin increases the difficulty for generating a block by decreasing the value which the generated hash must be less than. This difficulty target is stored in each block header using a compact representation as described in the documentation for CompactToBig. The main chain is selected by choosing the chain that has the most proof of work (highest difficulty). Since a lower target difficulty value equates to higher actual difficulty, the work value which will be accumulated must be the inverse of the difficulty. Also, in order to avoid potential division by zero and really small floating point numbers, the result adds 1 to the denominator and multiplies the numerator by 2^256.

func CompactToBig

func CompactToBig(compact uint32) *big.Int

CompactToBig converts a compact representation of a whole number N to an unsigned 32-bit number. The representation is similar to IEEE754 floating point numbers.

Like IEEE754 floating point, there are three basic components: the sign, the exponent, and the mantissa. They are broken out as follows:

  • the most significant 8 bits represent the unsigned base 256 exponent

  • bit 23 (the 24th bit) represents the sign bit

  • the least significant 23 bits represent the mantissa

    ------------------------------------------------- | Exponent | Sign | Mantissa | ------------------------------------------------- | 8 bits [31-24] | 1 bit [23] | 23 bits [22-00] | -------------------------------------------------

The formula to calculate N is:

N = (-1^sign) * mantissa * 256^(exponent-3)

This compact form is only used in bitcoin to encode unsigned 256-bit numbers which represent difficulty targets, thus there really is not a need for a sign bit, but it is implemented here to stay consistent with bitcoind.

func DeserializeBlockIndex

func DeserializeBlockIndex(d []byte) *blockIndex

DeserializeBlockIndex deserializes a block index

func SerializeBlock

func SerializeBlock(b *Block) []byte

SerializeBlock serializes the block

func SerializeBlockIndex

func SerializeBlockIndex(b *blockIndex) []byte

SerializeBlock serializes the block

func SerializeOutputs

func SerializeOutputs(outs []TXOutput) []byte

Serialize serializes []TXOutput

func SerializeTransaction

func SerializeTransaction(tx *Transaction) []byte

SerializeTransaction serializes a transaction for []byte

Types

type Block

type Block struct {
	Timestamp     time.Time
	PrevBlockHash []byte
	MerkleRoot    []byte
	Hash          []byte
	Difficult     uint32
	Nonce         int64
	Height        int32
	Transactions  []*Transaction
}

Block represents a block in the blockchain

func DeserializeBlock

func DeserializeBlock(d []byte) *Block

DeserializeBlock deserializes a block

func NewBlock

func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int32, quit chan struct{}) (*Block, bool)

NewBlock creates and returns Block

func NewGenesisBlock

func NewGenesisBlock(address string) *Block

NewGenesisBlock creates and returns genesis Block

func (*Block) GetHash

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

func (*Block) GetPrevHash

func (b *Block) GetPrevHash() *hashx.Hash

func (*Block) HashTransactions

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

HashTransactions returns a hash of the transactions in the block

func (*Block) SetHeight

func (b *Block) SetHeight(height int32)

SetHeight sets the height of the block

func (*Block) String

func (b *Block) String() string

type Blockchain

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

Blockchain implements interactions with a DB

func CreateBlockchain

func CreateBlockchain(isGenesisNode bool, address, nodeID string) *Blockchain

CreateBlockchain creates a new blockchain with genesisBlock

func LoadBlockChain

func LoadBlockChain(nodeID string) (*Blockchain, error)

LoadBlockChain load Blockchain with nodeID from bolt

func (*Blockchain) AddBlock

func (bc *Blockchain) AddBlock(block *Block) error

AddBlock add the block into the blockchain save to bolt, update LastBlockHash

func (*Blockchain) FindTransaction

func (bc *Blockchain) FindTransaction(ID *hashx.Hash) (*Transaction, error)

FindTransaction finds a transaction by its ID

func (*Blockchain) FindUTXO

func (bc *Blockchain) FindUTXO() map[string][]TXOutput

FindUTXO finds all unspent transaction outputs and returns transactions with spent outputs removed

func (*Blockchain) GetBalance

func (bc *Blockchain) GetBalance(address string) int

GetBalance

func (*Blockchain) GetBestHeight

func (bc *Blockchain) GetBestHeight() int32

GetBestHeight returns the height of the latest block

func (*Blockchain) GetBlock

func (bc *Blockchain) GetBlock(blockHash []byte) (*Block, error)

GetBlock finds a block by its hash and returns it if not exists, return ErrorBlockNotFount

func (*Blockchain) GetBlockHashes

func (bc *Blockchain) GetBlockHashes(beginHash *hashx.Hash, stopHash hashx.Hash, maxNum int) ([]*hashx.Hash, error)

GetBlockHashes returns a list of hashes with beginHash and maxNum limit

func (*Blockchain) GetLastBlock

func (bc *Blockchain) GetLastBlock() (*Block, error)

GetLastBlock returns the latest block

func (*Blockchain) GetStorageDB

func (bc *Blockchain) GetStorageDB() *bolt.DB

GetStorageDB get storage db

func (*Blockchain) GetUTXOSet

func (bc *Blockchain) GetUTXOSet() *UTXOSet

GetUTXOSet get current bc's UTXOSet wrapper

func (*Blockchain) HaveBlock

func (bc *Blockchain) HaveBlock(blockHash *hashx.Hash) (bool, error)

HaveBlock check block hash exists

func (*Blockchain) Iterator

func (bc *Blockchain) Iterator() *BlockchainIterator

Iterator returns a BlockchainIterator

func (*Blockchain) ListBlockHashs

func (bc *Blockchain) ListBlockHashs()

ListBlockHashs list println block's Hash and PrevBlockHash

func (*Blockchain) MineBlock

func (bc *Blockchain) MineBlock(transactions []*Transaction) (*Block, bool)

MineBlock mines a new block with the provided transactions

func (*Blockchain) ProcessBlock

func (bc *Blockchain) ProcessBlock(block *Block) (bool, bool, error)

ProcessBlock handling new block into chain return value: IsMainChain, IsOrphanBlock, error

func (*Blockchain) SignTransaction

func (bc *Blockchain) SignTransaction(tx *Transaction, privKey ecdsa.PrivateKey)

SignTransaction signs inputs of a Transaction

func (*Blockchain) TerminationMine

func (bc *Blockchain) TerminationMine()

TerminationMine send termination signal to stop current mining

func (*Blockchain) ValidateBlock

func (bc *Blockchain) ValidateBlock(block *Block, powLimit *big.Int) error

ValidateBlock validate block data

func (*Blockchain) VerifyTransaction

func (bc *Blockchain) VerifyTransaction(tx *Transaction) bool

VerifyTransaction verifies transaction input signatures

type BlockchainIterator

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

BlockchainIterator implement a iterator for blockchain blocks

func (*BlockchainIterator) LocationHash

func (i *BlockchainIterator) LocationHash(locateHash []byte) error

LocationHash locate current hash

func (*BlockchainIterator) Next

func (i *BlockchainIterator) Next() *Block

Next returns next block starting from the tip

type ChainIndex

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

func (*ChainIndex) AddIndex

func (bi *ChainIndex) AddIndex(index *blockIndex)

AddIndex adds the provided index to the chain index

This function is safe for concurrent access.

func (*ChainIndex) HaveBlock

func (bi *ChainIndex) HaveBlock(hash *hashx.Hash) bool

HaveBlock returns whether or not the block index contains the provided hash.

This function is safe for concurrent access.

func (*ChainIndex) Height

func (bi *ChainIndex) Height() int32

height returns the height of the tip of the chain index. It will return -1 if there is no tip

This function is safe for concurrent access.

func (*ChainIndex) IndexByHeight

func (bi *ChainIndex) IndexByHeight(height int32) *blockIndex

IndexByHeight returns the block index at the specified height. Nil will be returned if the height does not exist.

This function is safe for concurrent access.

func (*ChainIndex) LookupNode

func (bi *ChainIndex) LookupNode(hash *hashx.Hash) *blockIndex

LookupNode returns the block node identified by the provided hash. It will return nil if there is no entry for the hash.

This function is safe for concurrent access.

func (*ChainIndex) SetTip

func (bi *ChainIndex) SetTip(node *blockIndex)

SetTip sets use the provided block index as the current tip

This function is safe for concurrent access.

func (*ChainIndex) Tip

func (bi *ChainIndex) Tip() *blockIndex

Tip returns the current tip block index for the chain index. It will return nil if there is no tip.

This function is safe for concurrent access.

type OutPoint

type OutPoint struct {
	Hash  hashx.Hash
	Index int
}

OutPoint defines a dotcoin data type that is used to track previous transaction outputs.

func NewOutPoint

func NewOutPoint(hash *hashx.Hash, index int) *OutPoint

NewOutPoint returns a new dotcoin transaction outpoint point with the provided hash and index.

func (OutPoint) String

func (o OutPoint) String() string

String returns the OutPoint in the human-readable form "hash:index".

func (OutPoint) StringHash

func (o OutPoint) StringHash() string

type TXInput

type TXInput struct {
	PreviousOutPoint OutPoint
	Signature        []byte
	PubKey           []byte
}

TXInput represents a transaction input

func NewTXInput

func NewTXInput(prevOut *OutPoint, sign, pubKey []byte) *TXInput

NewTXInput create a new TXInput

func (*TXInput) UnLock

func (in *TXInput) UnLock(pubKeyHash []byte) bool

UsesKey checks whether the address initiated the transaction

type TXOutput

type TXOutput struct {
	Value      int
	PubKeyHash []byte
}

TXOutput represents a transaction output

func DeserializeOutputs

func DeserializeOutputs(data []byte) []TXOutput

DeserializeOutputs deserializes TXOutputs

func NewTXOutput

func NewTXOutput(value int, address string) *TXOutput

NewTXOutput create a new TXOutput

func (*TXOutput) IsLockedWithKey

func (out *TXOutput) IsLockedWithKey(pubKeyHash []byte) bool

IsLockedWithKey checks if the output can be used by the owner of the pubkey

func (*TXOutput) Lock

func (out *TXOutput) Lock(address []byte)

Lock set PublicKeyHash to signs the output input must check this value to use

type Transaction

type Transaction struct {
	ID      hashx.Hash
	Inputs  []TXInput
	Outputs []TXOutput
}

Transaction a transaction with ID\input\output

func DeserializeTransaction

func DeserializeTransaction(data []byte) (*Transaction, error)

DeserializeTransaction deserializes a transaction

func NewCoinbaseTX

func NewCoinbaseTX(to, data string, reward int) *Transaction

NewCoinbaseTX creates a new coinbase transaction

func NewUTXOTransaction

func NewUTXOTransaction(fromWallet *wallet.Wallet, to string, amount int, UTXOSet *UTXOSet, txPool TxPool) (*Transaction, error)

NewUTXOTransaction creates a new transaction

func (*Transaction) CalcHash

func (tx *Transaction) CalcHash() hashx.Hash

Hash calc and return the hash of the Transaction

func (*Transaction) GetHash

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

GetHash return the hash of the transaction

func (Transaction) IsCoinBase

func (tx Transaction) IsCoinBase() bool

IsCoinBase checks whether the transaction is coinbase

func (*Transaction) Sign

func (tx *Transaction) Sign(privateKey ecdsa.PrivateKey, prevTXs map[string]Transaction)

Sign signs each input of a Transaction must match input's prev TX exists

func (Transaction) String

func (tx Transaction) String() string

String returns a human-readable representation of a transaction

func (*Transaction) StringHash

func (tx *Transaction) StringHash() string

func (Transaction) StringID

func (tx Transaction) StringID() string

func (*Transaction) TrimmedCopy

func (tx *Transaction) TrimmedCopy() Transaction

TrimmedCopy creates a trimmed copy of Transaction to be used in signing set sign & pubkey nil

func (*Transaction) Verify

func (tx *Transaction) Verify(prevTXs map[string]Transaction) bool

Verify verifies signatures of Transaction inputs use signature & rawPubKey on ecdsa.Verify

type TxPool

type TxPool interface {
	HaveTransaction(hash string) bool
	MaybeAcceptTransaction(tx *Transaction) ([]*hashx.Hash, error)
}

type UTXOSet

type UTXOSet struct {
	Blockchain *Blockchain
}

UTXOSet represents UTXO set

func (UTXOSet) CountTransactions

func (u UTXOSet) CountTransactions() int

CountTransactions returns the number of transactions in the UTXO set

func (UTXOSet) FindSpendableOutputs

func (u UTXOSet) FindSpendableOutputs(pubkeyHash []byte, amount int, txPool TxPool) (int, map[string][]int)

FindSpendableOutputs finds and returns unspent outputs to reference in inputs add check is in txmempool

func (UTXOSet) FindUTXO

func (u UTXOSet) FindUTXO(pubKeyHash []byte) []TXOutput

FindUTXO finds UTXO for a public key hash

func (UTXOSet) ListUTXO

func (u UTXOSet) ListUTXO() []TXOutput

func (UTXOSet) Rebuild

func (u UTXOSet) Rebuild()

Reindex rebuilds the UTXO set

Jump to

Keyboard shortcuts

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