chain

package
v0.0.0-...-69f1810 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2024 License: Apache-2.0 Imports: 12 Imported by: 6

Documentation

Overview

chain provides blockchain interface

Rules for the chain mechanism:

  1. blocks are proposed for a certain epoch and against a certain checkpoint prior to that epoch.
  2. the block associated to a checkpoint must be sealed, otherwise it is not a valid checkpoint. sealed blocks cannot append new actions. They are not considerer final because certain actions can be removed by the commit phase.
  3. actions for the block are temporarily validated against the state derived at the checkpoint epoch.
  4. blocks are sealed, a hash is calculated, and the hash is signed by the publisher of the block. the commit phase is done by every node
  5. blocks are commited with all transactions validated with the checkpoint of the epoch immediately before the block epoch. Actions that were approved as validated by the original checkpoint are marked as invalidated by the commit instruction.
  6. state the system can be synced to another node.

Index

Constants

View Source
const (
	BlockActionOffset = 32 + 8 + 8 + 32 + 32 + 8
)
View Source
const ForceEmptyCommitAfter = 20

Force and Empty commit after so many blocks stagnated on a given checkpoint. the Block on the following checkpoint is forced to be empty and unsigned.

View Source
const KeepLastNBlocks = 100

block chain should keep as many KeepLastNBlocks blocks in memory for fast sync jobs and for recovery purposes.

Variables

This section is empty.

Functions

func PutChecksumStatement

func PutChecksumStatement(d *ChecksumStatement, bytes *[]byte)

PutChecksumStatement serializes a ChecksumStatement to a byte slice and appends it to the provided byte slice.

Types

type ActionArray

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

Memory block is a simplified version of block containing only actions bytes stored in a sequential byte slice. The hash of an action array is the hash of the underlying byte slice.

func NewActionArray

func NewActionArray() *ActionArray

NewActionArray returns a pointer to a new empty action array.

func ParseAction

func ParseAction(data []byte, position int) (*ActionArray, int)

ParseAction parses byte array to an action array. The underlying byte array must follow the format of a util.PutActionsArray.

func (*ActionArray) Append

func (b *ActionArray) Append(data []byte)

Append appends an action to the end of the array.

func (*ActionArray) Clone

func (m *ActionArray) Clone() *ActionArray

Clone returns a deep copy of the action array.

func (*ActionArray) Get

func (b *ActionArray) Get(n int) []byte

Get returns the n-th action in the array. Returns nil if n is out of range.

func (*ActionArray) Hash

func (b *ActionArray) Hash() crypto.Hash

Hash returns the hash of the underlying byte slice.

func (*ActionArray) Len

func (b *ActionArray) Len() int

Len returns the number of actions in the array.

func (*ActionArray) Serialize

func (b *ActionArray) Serialize() []byte

Serialize serializes an action array to a byte array. The underlying byte layout follows util.PutActionsArray

type BlockBuilder

type BlockBuilder struct {
	Header    BlockHeader
	Actions   *ActionArray
	Validator *state.MutatingState
}

BLockBuilder is the primitive to mint a new block. It containes the block header, the action array and an action validator.

func (*BlockBuilder) Clone

func (b *BlockBuilder) Clone() *BlockBuilder

TODO: is this used?

func (*BlockBuilder) Hash

func (b *BlockBuilder) Hash() crypto.Hash

TODO: is this used?

func (*BlockBuilder) ImprintSeal

func (b *BlockBuilder) ImprintSeal(seal BlockSeal) *SealedBlock

Appends a provided seal to the blockbuild and returns a pointer to a SealedBlock.

func (*BlockBuilder) Seal

func (b *BlockBuilder) Seal(credentials crypto.PrivateKey) *SealedBlock

Returns a pointer to a SeledBlock properly signed by the provided credentials.

func (*BlockBuilder) Serialize

func (b *BlockBuilder) Serialize() []byte

TODO: is this used??

func (*BlockBuilder) Validate

func (b *BlockBuilder) Validate(data []byte) bool

Validates new action and appends it to the action array if valid.

type BlockCommit

type BlockCommit struct {
	Invalidated   []crypto.Hash
	FeesCollected uint64
	PublishedBy   crypto.Token
	PublishSign   crypto.Signature
}

BlockCommit is the final structure of a block. Every validating node must build a block commit structure for every consensual sealed block it receives. Blocks are commit in sequence. Sealed block for epoch t can only be committed if block for epoch t - 1 has been committed. At the commit process a node must revalidate all the proposed actions against the state at the previous block. Hashes of invalidated actions are groupéd in the block commit. The ammount of fees collected by the proposer of the block is also recalculated to exclude the fees of invalidated or previously incorporated actions. Every node must publish its own perception of the block commit structure. If the consensys algorithm is working, every node will have the same perception of reality. The swell protocol does not anticipate penalties for faulty commits.

func ParseBlockCommit

func ParseBlockCommit(data []byte) *BlockCommit

ParseBlockCommit parses a byte slice to a block commit. Return nil if the byte slice does not contain a valid block commit.

func (BlockCommit) Serialize

func (b BlockCommit) Serialize() []byte

Serialize serializes a block commit to a byte slice.

type BlockHeader

type BlockHeader struct {
	NetworkHash    crypto.Hash
	Epoch          uint64
	CheckPoint     uint64
	CheckpointHash crypto.Hash
	Proposer       crypto.Token
	ProposedAt     time.Time
	Duplicate      *bft.Duplicate       // Evidence for rule violations on the consesus pool
	Candidate      []*ChecksumStatement // Validator candidate evidence for state checksum
}

BlockHeader communicates the intention of a validator to mint a new block. It contains the network hash, the epoch, the checkpoint <= epoch - 1 against which the validator will check the validity of proposed actions, the hash of the block associated to that checkpoint, the validator's token, the UTC time as perceived by the validator at the submission of the header, optional evidence of previous infringiments from other nodes of the swell protocol, and optional checksum statments as received by the validator from cadidate validating nodes for the next checksum window.

func ParseBlockHeader

func ParseBlockHeader(data []byte) *BlockHeader

ParseBlockHeader parses a byte slice to a block header. Return nil if the byte slice does not contain a valid block header.

func (BlockHeader) Clone

func (b BlockHeader) Clone() BlockHeader

Clone returns a copy of the block header without duplicates and checksum statements.

func (BlockHeader) Serialize

func (b BlockHeader) Serialize() []byte

Serialize serializes a block header to a byte slice.

type BlockSeal

type BlockSeal struct {
	Hash          crypto.Hash
	FeesCollected uint64
	SealSignature crypto.Signature
	Consensus     []*bft.Ballot
}

Seal for a proposed block. It contains the hash of the proposed block, the fees collected by the validator, the signature of the proposer of the block, and the consensus ballots for the block. Consensus information is gathered individually by each validator by the bft rules. Anyone in possession of this can attest to the validity of the bft consensus algorithm.

func ParseBlockSeal

func ParseBlockSeal(data []byte) *BlockSeal

ParseBlockSeal parses a byte slice to a block seal. Return nil if the byte slice does not contain a valid block seal.

func (BlockSeal) Clone

func (b BlockSeal) Clone() BlockSeal

Clone returns a copy of the block seal without consensus information.

func (BlockSeal) Serialize

func (b BlockSeal) Serialize() []byte

Serialize serializes a block seal to a byte slice.

type Blockchain

type Blockchain struct {
	NetworkHash     crypto.Hash
	Credentials     crypto.PrivateKey
	LastCommitEpoch uint64
	LastCommitHash  crypto.Hash
	CommitState     *state.State
	SealedBlocks    []*SealedBlock
	RecentBlocks    []*CommitBlock
	Cloning         bool
	Checksum        *Checksum
	NextChecksum    *Checksum
	Clock           ClockSyncronization
	Punishment      map[crypto.Token]uint64
	BlockInterval   time.Duration
	ChecksumWindow  int
	// contains filtered or unexported fields
}

Blockchain is the main data structure for the breeze network. It contains the state of the system at the last commit and the sealed uncommited blocks.

func BlockchainFromChecksumState

func BlockchainFromChecksumState(c *Checksum, clock ClockSyncronization, credentials crypto.PrivateKey, networkHash crypto.Hash, interval time.Duration, checksumWindow int) *Blockchain

BlockchainFromChecksumState recreates a blockchain from a given checksum state. Checksum state typically comes from a peer node sync job.

func BlockchainFromGenesisState

func BlockchainFromGenesisState(credentials crypto.PrivateKey, walletPath string, hash crypto.Hash, interval time.Duration, cehcksumWindow int) *Blockchain

BlockchainFromGenesisState creates a new blockchain from a genesis state. It creates the genesis state and depoits the initial tokens on the credentials wallet. Credentials is also accredited as a validator for the first checksum window. hash is the network hash. interval is the block interval. checksum window is the number of epochs between checksums.

func (*Blockchain) AddSealedBlock

func (c *Blockchain) AddSealedBlock(sealed *SealedBlock)

AddSealedBlock adds a sealed block to the blockchain. If the added block can be commit it is automatically committed and subsequent sealed blocks are committed as well. The committ machanism will trigger a checksum job if any epoch matches the checksum window. If not committed the block is kept as a sealed block. Sealed block are expected to have consensus evidence. AddSealedBlock does not check for consensus evidence, or valid signature. It is the reponsability of the caller to ensure that the sealed block has all necessary and valid information within it.

func (*Blockchain) CheckForceEmptyCommit

func (c *Blockchain) CheckForceEmptyCommit() bool

CheckForceEmptyCommit forces an empty unsigned commit to the blockchain. This is allowed when MaxLag sucessive blocks have been sealed but not commited, due to a missing LastCommitEpoch + 1 block.

func (*Blockchain) CheckpointValidator

func (c *Blockchain) CheckpointValidator(header BlockHeader) *BlockBuilder

CheckpointValidator returns a block builder for a block that will validate actions proposed. It returns nil if the proposed epoch in the header is for a period prior to the last commit epoch.

func (*Blockchain) CommitBlock

func (c *Blockchain) CommitBlock(blockEpoch uint64) bool

CommitBlock commits a sealed block to the blockchain. It returns true if the block was successfully committed. It returns false if the block was not committed. It is not committed if the block epoch is not sequential to the last commit epoch, if the block epoch is already committed, or if the block epoch is not found in the sealed blocks.

func (*Blockchain) CommitChain

func (c *Blockchain) CommitChain()

CommitChain commits all sequential sealed blocks in the blockchain following a last commit epoch. If stops the commit chain if the commit epoch is a checksum commit epoch. It is the responsibility of the caller to ensure that the checksum job request is called.

func (*Blockchain) IsChecksumCommit

func (b *Blockchain) IsChecksumCommit() bool

IsChecksumEpoch returns true if the provided epoch is a checksum epoch and the checksum is not yet available. It returns false otherwise.

func (*Blockchain) MarkCheckpoint

func (c *Blockchain) MarkCheckpoint()

MarkCheckpoint marks the current state as a checkpoint. It creates a clone of the state at the last commit epoch and calculates the checksum of the state. It returns a true value on the provided channel if the clone operation was successful. Otherwise, it returns false.

func (*Blockchain) NextBlock

func (c *Blockchain) NextBlock(epoch uint64) *BlockHeader

NextBlock returns a block header for the next block to be proposed. It retrieves the checkpoint from the last commit state.

func (*Blockchain) RecentAfter

func (c *Blockchain) RecentAfter(epoch uint64) []*CommitBlock

func (*Blockchain) Recovery

func (c *Blockchain) Recovery(epoch uint64) error

Recovery rolls over the blockchain to a previous epoch before the last commit but after the last checksum epoch. It erases any sealed block or commit block and recalculates the state of the chain at the new epoch.

func (*Blockchain) Rollover

func (c *Blockchain) Rollover(epoch uint64) error

Rollover rolls over the blockchain to a previous epoch after the last commit epoch. It erases any sealed block. It returns an error if the epoch is before the last commit epoch.

func (*Blockchain) Shutdown

func (c *Blockchain) Shutdown()

func (*Blockchain) SyncBlocksServer

func (c *Blockchain) SyncBlocksServer(conn *socket.CachedConnection, epoch uint64)

SyncBlocksClient answers a request for previously minted blocks from a node from a cached connection. If it is not in possession of information that old, it will senf a MsgSyncError message and close the connection. Otherwise, it will send the requested blocks either as sealed blocks or as committed blocks. The current building block, if any, must be served by the validating node itself. If marks the connection as ready at the end of the sync job.

func (*Blockchain) SyncState

func (c *Blockchain) SyncState(conn *socket.CachedConnection)

SyncBlocksClient answers a request for the state of the system at the last recorded checksum. It sends the state of the wallets and the state of the deposits. It then requests a block sync from that epoch forward.

func (*Blockchain) Timer

func (b *Blockchain) Timer(epoch uint64) *time.Timer

Timer returns a timer that will fire at the time at which a block with the provided epoch will start. It is calculated from the last clock

func (*Blockchain) TimestampBlock

func (b *Blockchain) TimestampBlock(epoch uint64) time.Time

TimestampBlock returns the time at which a block with the provided epoch will start. It is calculated from the last clock synchronization and the block interval.

type Checksum

type Checksum struct {
	Epoch         uint64
	State         *state.State
	LastBlockHash crypto.Hash
	Hash          crypto.Hash
}

Checksum is a snapshot of the state of the system at periodic epochs. It contains the epoch, the state of the chain at that epoch, the hash of the last sealed block at that epoch and a checksum hash for the state of the system. Only validators which agree and provide evidence of the same state checksum are allowed to participate in the next checksum window.

type ChecksumStatement

type ChecksumStatement struct {
	Epoch     uint64
	Node      crypto.Token
	Address   string
	Naked     bool
	Hash      crypto.Hash
	Signature crypto.Signature
}

ChecksumStatement is a message every candidate node for validating during the next checksum window period msut send to current validator nodes. It is first sent with the checksum hash hashed with the node's token and with Naked marked as false. It is aftwards sent with Naked marked as true and the naked checksum hash. Inconsistent ChecksumStatements for the same epoch are considered illegal by the swell protocol and might be penalised depending on the p´revailing perssion rules.

func NewCheckSum

func NewCheckSum(epoch uint64, node crypto.PrivateKey, address string, naked bool, hash crypto.Hash) *ChecksumStatement

func ParseChecksumStatement

func ParseChecksumStatement(data []byte) *ChecksumStatement

ParseChecksumStatement parses a ChecksumStatement from a byte slice.

func ParseChecksumStatementPosition

func ParseChecksumStatementPosition(data []byte, position int) (*ChecksumStatement, int)

ParseChecksumStatementPosition parses a ChecksumStatement in the middle of a byte slice and returns the parsed ChecksumStatement and the position

func (*ChecksumStatement) IsDressed

func (dressed *ChecksumStatement) IsDressed(naked *ChecksumStatement) bool

IsDressed returns true if the naked ChecksumStatement is compatible with the dressed ChecksumStatement. It returns false otherwise.

func (*ChecksumStatement) Serialize

func (d *ChecksumStatement) Serialize() []byte

Serialize serializes a ChecksumStatement to a byte slice.

type ClockSyncronization

type ClockSyncronization struct {
	Epoch     uint64
	TimeStamp time.Time
}

The last perceived epoch-to-clock synchronization in possession of the node. The first synchronization is at genesis time. If there is no downtime, this synchronization remains in place. If there is downtime, the nodes

func (ClockSyncronization) Timer

type CommitBlock

type CommitBlock struct {
	Header  BlockHeader
	Actions *ActionArray
	Seal    BlockSeal
	Commit  *BlockCommit
	// contains filtered or unexported fields
}

func ParseCommitBlock

func ParseCommitBlock(data []byte) *CommitBlock

ParseCommitBlock parses a byte array into a CommitBlock. Returns nil if the byte array is not a valid CommitBlock.

func (*CommitBlock) GetValidActions

func (b *CommitBlock) GetValidActions() [][]byte

Returns byte byte array of only those actions not invalidated by the block commit structure.

func (*CommitBlock) Sealed

func (c *CommitBlock) Sealed() *SealedBlock

Returns a pointer to a SealedBlock with the same header, action array and seal as the CommitBlock.

func (*CommitBlock) Serialize

func (b *CommitBlock) Serialize() []byte

Serialize serializes a CommitBlock to a byte array.

type IncorporatedActions

type IncorporatedActions struct {
	CurrentEpoch uint64
	// contains filtered or unexported fields
}

IncorporatedActions is a data structure that keeps track of the actions incorporated in the blockchain. It is used to prevent the same action to be incorporated twice.

func NewIncorporatedActions

func NewIncorporatedActions(epoch, MaxProtocolEpoch uint64) *IncorporatedActions

func (*IncorporatedActions) Append

func (ia *IncorporatedActions) Append(hash crypto.Hash, epoch uint64)

func (*IncorporatedActions) IsNew

func (ia *IncorporatedActions) IsNew(hash crypto.Hash, epoch uint64, checkpoint uint64) bool

func (*IncorporatedActions) MoveForward

func (ia *IncorporatedActions) MoveForward()

type SealedBlock

type SealedBlock struct {
	Header    BlockHeader
	Actions   *ActionArray
	Seal      BlockSeal
	Mutations *state.Mutations
}

SealedBlock is the sealed version of a block. It should be considered final and immutable, but not yet incorporated into the block chain. It consists of a block header, an action array and a block seal with a valid signature against the block creator expressed in the block header.

func ParseSealedBlock

func ParseSealedBlock(data []byte) *SealedBlock

ParseSealedBlock parses a byte array into a SealedBlock. Returns nil if the byte array is not a valid SealedBlock.

func (*SealedBlock) Revalidate

func (c *SealedBlock) Revalidate(validator *state.MutatingState, publish crypto.PrivateKey) *CommitBlock

Revalidate checks if the actions of a sealed block remains valid according to a more recent state. Hashes of invalidated actions are added to the block commit. The block chain shoul ignore those invalidated actions in order to advance the state of the chain. Nonetheless the invalidated actions are not purged from the action array in the CommitBlock. Commit is an individual action of a node and not subject to a committe for further validation and consensus formation. Users receiving a commit block must decide if the trust the publisher or if theuy should independtly check the validity of the commit metadata.

func (*SealedBlock) Serialize

func (s *SealedBlock) Serialize() []byte

Serialize serializes a SealedBlock to a byte array.

Jump to

Keyboard shortcuts

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