blockchain

package
v0.0.0-...-c1f1bd4 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2020 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// CoinValue is the transaction amount that represents one Cumulus coin
	CoinValue uint64 = 1 << 32
	// StartingBlockReward is the mining reward that the blockchain will begin
	// with.
	StartingBlockReward uint64 = 25 * CoinValue
	// BlockRewardHalvingRate is the number of blocks that need to be mined
	// before the blockReward is halved
	BlockRewardHalvingRate int = 210000
)
View Source
const (
	// CoordLen is the length in bytes of coordinates with our ECC curve.
	CoordLen = 32
	// AddrLen is the length in bytes of addresses.
	AddrLen = 2 * CoordLen
	// ReprLen is the length in bytes of an address checksum.
	ReprLen = 40
	// SigLen is the length in bytes of signatures.
	SigLen = AddrLen
	// AddressVersion is the version of the address shortening protocol.
	AddressVersion = 0
)
View Source
const DefaultBlockSize = 1 << 18

DefaultBlockSize is the default block size, can be augmented by the user.

View Source
const (
	// HashLen is the length in bytes of a hash.
	HashLen = 32
)

Variables

View Source
var (

	// NilSig is a signature representing a failed Sign operation
	NilSig = Signature{c.Big0, c.Big0}
	// NilAddr is an address representing no address
	NilAddr = Address{c.Big0, c.Big0}
)
View Source
var (
	// NilHash represents a nil hash
	NilHash = BigIntToHash(c.Big0)
)

Functions

func HashToBigInt

func HashToBigInt(h Hash) *big.Int

HashToBigInt converts a hash to a big int pointer

func NewValidChainAndTxn

func NewValidChainAndTxn() (*BlockChain, *Transaction)

NewValidChainAndTxn creates a valid BlockChain of 3 blocks, and a Transaction that is valid with respect to the BlockChain.

func NewValidCloudBaseTestTransaction

func NewValidCloudBaseTestTransaction() (*Transaction, Address)

NewValidCloudBaseTestTransaction returns a new valid CloudBase transaction and the address of the recipient of the transaction

func NewValidTestChainAndBlock

func NewValidTestChainAndBlock() (*BlockChain, *Block)

NewValidTestChainAndBlock creates a valid BlockChain of 3 blocks, and a new block which is valid with respect to the blockchain.

Types

type Account

type Account interface {
	Public() Address
	Sign(digest Hash, random io.Reader) (Signature, error)
}

Account represents a wallet that we have the ability to sign for.

type Address

type Address struct {
	X, Y *big.Int
}

Address represents a wallet that can be a recipient in a transaction.

func (Address) Emoji

func (a Address) Emoji() string

Emoji returns the users address as a string of emojis.

func (Address) Key

func (a Address) Key() *ecdsa.PublicKey

Key returns the ECDSA public key representation of the address.

func (Address) Marshal

func (a Address) Marshal() []byte

Marshal converts an Address to a byte slice.

func (Address) Repr

func (a Address) Repr() string

Repr returns a string representation of the address. We follow ethereums protocol, replacing Keccak hash with SHA256. Where pr is the private key,

A(pr) = SHA256(ECDSAPUBLICKEY(pr))[96:255],

Resources: http://gavwood.com/paper.pdf (fig 213)

type Block

type Block struct {
	BlockHeader
	Transactions []*Transaction
}

Block represents a block in the blockchain. Contains transactions and header metadata.

func DecodeBlockJSON

func DecodeBlockJSON(blockBytes []byte) (*Block, error)

DecodeBlockJSON returns a block read from the given marshalled block, or an error if blockBytes cannot be decoded as JSON.

func Genesis

func Genesis(miner Address, target Hash, blockReward uint64, extraData []byte) *Block

Genesis creates the Genesis block and returns is.

Properties of the Genesis block:

  • BlockNumber = 0
  • LastBlock = 0
  • There is only one transaction in the block, the CloudBase transaction that awards the miner with the block reward.

func NewTestBlock

func NewTestBlock() *Block

NewTestBlock prodcues random block.

func (*Block) ContainsTransaction

func (b *Block) ContainsTransaction(t *Transaction) (bool, uint32)

ContainsTransaction returns true and the transaction itself if the Block contains the transaction.

func (*Block) GetCloudBaseTransaction

func (b *Block) GetCloudBaseTransaction() *Transaction

GetCloudBaseTransaction returns the CloudBase transaction within a block

func (*Block) GetTotalInputFrom

func (b *Block) GetTotalInputFrom(sender string, bc *BlockChain) (uint64, error)

GetTotalInputFrom returns the total input from the given sender in the given block. Returns an error if the input to one or more of the inputs to the transactions in the given block could not be found in the blockchain.

func (*Block) GetTotalOutputFor

func (b *Block) GetTotalOutputFor(recipient string) uint64

GetTotalOutputFor sums the outputs referenced to a specific recipient in the given block. recipient is an address checksum hex string.

func (*Block) GetTransactionsFrom

func (b *Block) GetTransactionsFrom(sender string) []*Transaction

GetTransactionsFrom returns all the transactions from the given sender in the given block.

func (*Block) GetTransactionsTo

func (b *Block) GetTransactionsTo(recipient string) []*Transaction

GetTransactionsTo returns all the transactions with outputs to the given recipient in the given block.

func (*Block) Len

func (b *Block) Len() int

Len returns the length in bytes of the Block.

func (Block) Marshal

func (b Block) Marshal() []byte

Marshal converts a Block to a byte slice.

type BlockChain

type BlockChain struct {
	Blocks []*Block
	Head   Hash
	// contains filtered or unexported fields
}

BlockChain represents a linked list of blocks

func Load

func Load(fileName string) (*BlockChain, error)

Load attempts to read blockchain info from the file with the given name in the current working directory in JSON format. On success this returns a pointer to a new user constructed from the information in the file. If an error occurrs it is returned.

func New

func New() *BlockChain

New returns a new blockchain

func NewTestBlockChain

func NewTestBlockChain() *BlockChain

NewTestBlockChain produces random blockchain.

func NewValidBlockChainFixture

func NewValidBlockChainFixture() (*BlockChain, map[string]*Wallet)

NewValidBlockChainFixture creates a valid blockchain of three blocks and returns the wallets involved in the transactions. The returning wallets will have balances of 3, 1, and 0 respectively.

func (*BlockChain) AppendBlock

func (bc *BlockChain) AppendBlock(b *Block)

AppendBlock adds a block to the end of the block chain.

func (*BlockChain) ContainsTransaction

func (bc *BlockChain) ContainsTransaction(t *Transaction, start, stop uint32) (bool, uint32, uint32)

ContainsTransaction returns true, the block index, and the transaction index if the BlockChain contains the transaction in a block between start and stop indexes.

func (*BlockChain) GetAllInputs

func (bc *BlockChain) GetAllInputs(t *Transaction) ([]*Transaction, error)

GetAllInputs returns all the transactions referenced by a transaction as inputs. Returns an error if any of the transactios requested could not be found.

func (*BlockChain) GetBlockByLastBlockHash

func (bc *BlockChain) GetBlockByLastBlockHash(hash Hash) (*Block, error)

GetBlockByLastBlockHash returns a copy of the block in the local chain that comes directly after the block with the given hash. Returns error if no such block is found.

func (*BlockChain) GetBlockRange

func (bc *BlockChain) GetBlockRange(t *Transaction) (uint32, uint32)

GetBlockRange returns the start and end block indexes for the inputs to a transaction.

func (*BlockChain) GetInputTransaction

func (bc *BlockChain) GetInputTransaction(t *TxHashPointer) *Transaction

GetInputTransaction returns the input Transaction referenced by TxHashPointer. If the Transaction does not exist, then GetInputTransaction returns nil.

func (*BlockChain) LastBlock

func (bc *BlockChain) LastBlock() *Block

LastBlock returns a pointer to the last block in the given blockchain, or nil if the blockchain is empty.

func (*BlockChain) Len

func (bc *BlockChain) Len() int

Len returns the length of the BlockChain when marshalled

func (*BlockChain) Lock

func (bc *BlockChain) Lock()

Lock locks the blockchain for reading

func (*BlockChain) Marshal

func (bc *BlockChain) Marshal() []byte

Marshal converts the BlockChain to a byte slice.

func (*BlockChain) RLock

func (bc *BlockChain) RLock()

RLock locks the blockchain for reading

func (*BlockChain) RUnlock

func (bc *BlockChain) RUnlock()

RUnlock locks the blockchain for reading

func (*BlockChain) RollBack

func (bc *BlockChain) RollBack() *Block

RollBack removes the last block from the blockchain. Returns the block that was removed from the end of the chain, or nil if the blockchain is empty.

func (*BlockChain) Save

func (bc *BlockChain) Save(fileName string) error

Save writes the blockchain to a file of the given same in the current working directory in JSON format. It returns an error if one occurred, or a pointer to the file that was written to on success.

func (*BlockChain) Unlock

func (bc *BlockChain) Unlock()

Unlock locks the blockchain for reading

type BlockHeader

type BlockHeader struct {
	// BlockNumber is the position of the block within the blockchain
	BlockNumber uint32
	// LastBlock is the hash of the previous block
	LastBlock Hash
	// Target is the current target
	Target Hash
	// Time is represented as the number of seconds elapsed
	// since January 1, 1970 UTC.
	Time uint32
	// Nonce starts at 0 and increments by 1 for every hash when mining
	Nonce uint64
	// ExtraData is an extra field that can be filled with arbitrary data to
	// be stored in the block
	ExtraData []byte
}

BlockHeader contains metadata about a block

func NewTestBlockHeader

func NewTestBlockHeader() BlockHeader

NewTestBlockHeader prodcues random block header.

func (*BlockHeader) Equal

func (bh *BlockHeader) Equal(otherHeader *BlockHeader) bool

Equal returns true if all the fields (other than ExtraData) in each of the BlockHeaders match, and false otherwise.

func (*BlockHeader) Len

func (bh *BlockHeader) Len() int

Len returns the length in bytes of the BlockHeader.

func (*BlockHeader) Marshal

func (bh *BlockHeader) Marshal() []byte

Marshal converts a BlockHeader to a byte slice

type Hash

type Hash [HashLen]byte

Hash represents a 256-bit hash of a block or transaction

func BigIntToHash

func BigIntToHash(x *big.Int) Hash

BigIntToHash converts a big integer to a hash. If the size of the big int is larger than the size of hash, the function will return a hash set to 0.

func HashSum

func HashSum(m Marshaller) Hash

HashSum computes the SHA256 squared hash of a Marshaller.

func NewTestHash

func NewTestHash() Hash

NewTestHash produces a hash.

func NewValidTestTarget

func NewValidTestTarget() Hash

NewValidTestTarget creates a new valid target that is a random value between the max and min difficulties

func (Hash) LessThan

func (h Hash) LessThan(h2 Hash) bool

LessThan returns true if the receiver hash is less than the hash provided, and false otherwise

func (Hash) Marshal

func (h Hash) Marshal() []byte

Marshal converts a Hash to a slice.

type Marshaller

type Marshaller interface {
	Marshal() []byte
}

Marshaller is any type that can convert itself to a byte slice

type Signature

type Signature struct {
	R *big.Int
	S *big.Int
}

Signature represents a signature of a transaction.

func (*Signature) Marshal

func (s *Signature) Marshal() []byte

Marshal converts a signature to a byte slice. Should be 64 bytes long.

type Transaction

type Transaction struct {
	TxBody
	Sig Signature
}

Transaction contains a TxBody and a signature verifying it

func NewTestTransaction

func NewTestTransaction() *Transaction

NewTestTransaction prodcues random txn.

func (*Transaction) Equal

func (t *Transaction) Equal(txnToCompare *Transaction) bool

Equal returns true if the signatures of the given transactions are equal (i.e. the transactions are the same).

func (*Transaction) GetTotalInput

func (t *Transaction) GetTotalInput(bc *BlockChain) (uint64, error)

GetTotalInput sums the input amounts from the transaction. Requires the blockchain for lookups.

func (*Transaction) GetTotalOutput

func (t *Transaction) GetTotalOutput() uint64

GetTotalOutput sums the output amounts from the transaction.

func (*Transaction) GetTotalOutputFor

func (t *Transaction) GetTotalOutputFor(recipient string) uint64

GetTotalOutputFor sums the outputs referenced to a specific recipient. recipient is an address checksum hex string.

func (*Transaction) InputIntersection

func (t *Transaction) InputIntersection(other *Transaction) set.Interface

InputIntersection returns the intersection of the inputs of t and other.

func (*Transaction) InputSet

func (t *Transaction) InputSet() *set.Set

InputSet returns the transaction inputs as a set object.

func (*Transaction) InputsEqualOutputs

func (t *Transaction) InputsEqualOutputs(other ...*Transaction) bool

InputsEqualOutputs returns true if t.Inputs == other.Outputs, as well as the difference between the two (outputs - inputs).

func (*Transaction) InputsIntersect

func (t *Transaction) InputsIntersect(other *Transaction) bool

InputsIntersect returns true if the inputs of t intersect with those of other.

func (*Transaction) InputsSpentElsewhere

func (t *Transaction) InputsSpentElsewhere(bc *BlockChain, start uint32) bool

InputsSpentElsewhere returns true if inputs purported to be only spent on transaction t have been spent elsewhere after block index `start`.

func (*Transaction) Len

func (t *Transaction) Len() int

Len returns the length in bytes of a transaction

func (*Transaction) Marshal

func (t *Transaction) Marshal() []byte

Marshal converts a Transaction to a byte slice

type TxBody

type TxBody struct {
	Sender  Address
	Inputs  []TxHashPointer
	Outputs []TxOutput
}

TxBody contains all relevant information about a transaction

func NewTestTxBody

func NewTestTxBody() TxBody

NewTestTxBody random txn body.

func (TxBody) Len

func (tb TxBody) Len() int

Len returns the length of a transaction body

func (TxBody) Marshal

func (tb TxBody) Marshal() []byte

Marshal converts a TxBody to a byte slice

func (TxBody) Sign

func (tb TxBody) Sign(w Wallet, r io.Reader) (*Transaction, error)

Sign returns a signed Transaction from a TxBody

type TxHashPointer

type TxHashPointer struct {
	BlockNumber uint32
	Hash        Hash
	Index       uint32
}

TxHashPointer is a reference to a transaction on the blockchain.

func NewTestTxHashPointer

func NewTestTxHashPointer() TxHashPointer

NewTestTxHashPointer produces transaction hash pointer.

func (TxHashPointer) Marshal

func (thp TxHashPointer) Marshal() []byte

Marshal converts a TxHashPointer to a byte slice

type TxOutput

type TxOutput struct {
	Amount    uint64
	Recipient string
}

TxOutput defines an output to a transaction

func NewTestTxOutput

func NewTestTxOutput() TxOutput

NewTestTxOutput random txn output.

func (TxOutput) Marshal

func (to TxOutput) Marshal() []byte

Marshal converts a TxOutput to a byte slice

type Wallet

type Wallet struct {
	*ecdsa.PrivateKey
	PendingTxns []*Transaction
	Balance     uint64
}

Wallet is an account that can sign and hold a balance.

func NewWallet

func NewWallet() *Wallet

NewWallet produces a new Wallet that can sign transactions and has a public Address.

func (*Wallet) DropAllPending

func (w *Wallet) DropAllPending(txns []*Transaction, bc *BlockChain) error

DropAllPending drops pending transactions if they appear in txns. Returns an error if any of the given transactions are not in the blockchain.

func (*Wallet) DropPending

func (w *Wallet) DropPending(i int)

DropPending drops a single pending transaction by index in the pending list.

func (*Wallet) GetEffectiveBalance

func (w *Wallet) GetEffectiveBalance() uint64

GetEffectiveBalance returns the wallet balance less the sum of the pending transactions in the wallet.

func (*Wallet) IsPending

func (w *Wallet) IsPending(txn *Transaction) (bool, int)

IsPending returns true if the transaction exists in the pending list. If true, it also returns the integer index of the transaction.

func (*Wallet) Public

func (w *Wallet) Public() Address

Public returns the public key as byte array, or address, of the wallet.

func (*Wallet) Refresh

func (w *Wallet) Refresh(bc *BlockChain) error

Refresh sets the wallet's balance and updates its set of pending transactions based on the transaction information in the given blockchain. Returns an error if any of the transactions in the blockchain cannot be found.

func (*Wallet) SetAllPending

func (w *Wallet) SetAllPending(txns []*Transaction)

SetAllPending appends transactions to the pending set of transactions.

func (*Wallet) SetPending

func (w *Wallet) SetPending(txn *Transaction) error

SetPending appends one transaction to the pending set of transactions if the wallet's effective balance is high enough to accomodate.

func (*Wallet) Sign

func (w *Wallet) Sign(digest Hash, random io.Reader) (Signature, error)

Sign returns a signature of the digest.

func (*Wallet) UnmarshalJSON

func (w *Wallet) UnmarshalJSON(walletBytes []byte) error

UnmarshalJSON unmarshals the given byte slice into the given wallet, and returns an error if one occurs.

func (*Wallet) Update

func (w *Wallet) Update(block *Block, bc *BlockChain) error

Update updates the wallet's balance and set of pending transactions based on the transaction information in the given block. Returns an error if any of the transactions in the given block cannot be found in the blockchain.

Source Files

  • block.go
  • blockchain.go
  • genesis.go
  • hash.go
  • test_utils.go
  • transaction.go
  • wallet.go

Jump to

Keyboard shortcuts

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