mesh_old

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2023 License: Apache-2.0, BSD-2-Clause Imports: 61 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// BlockVersion defines the Version of the block structure.
	BlockVersion uint8 = 1

	// MaxBlockSize defines the maximum size of a block.
	MaxBlockSize = 64 * 1024

	// BlockIDLength defines the length of an BlockID.
	BlockIDLength = types.IdentifierLength + 8

	// MinParentsCount defines the minimum number of parents each parents block must have.
	MinParentsCount = 1

	// MaxParentsCount defines the maximum number of parents each parents block must have.
	MaxParentsCount = 8

	// MinParentsBlocksCount defines the minimum number of parents each parents block must have.
	MinParentsBlocksCount = 1

	// MaxParentsBlocksCount defines the maximum number of parents each parents block must have.
	MaxParentsBlocksCount = 4

	// MinStrongParentsCount defines the minimum number of strong parents a block must have.
	MinStrongParentsCount = 1
)
View Source
const (
	// MaxLocalQueueSize is the maximum local (containing the block to be issued) queue size in bytes.
	MaxLocalQueueSize = 20
	// RateSettingIncrease is the global additive increase parameter.
	// In the Access Control for Distributed Ledgers in the Internet of Things: A Networking Approach paper this parameter is denoted as "A".
	RateSettingIncrease = 0.075
	// RateSettingDecrease global multiplicative decrease parameter (larger than 1).
	// In the Access Control for Distributed Ledgers in the Internet of Things: A Networking Approach paper this parameter is denoted as "β".
	RateSettingDecrease = 1.5
	// Wmax is the maximum inbox threshold for the node. This value denotes when maximum active mana holder backs off its rate.
	Wmax = 10
	// Wmin is the min inbox threshold for the node. This value denotes when nodes with the least mana back off their rate.
	Wmin = 5
)
View Source
const (
	// PrefixBlock defines the storage prefix for block.
	PrefixBlock byte = iota

	// PrefixBlockMetadata defines the storage prefix for block metadata.
	PrefixBlockMetadata

	// PrefixChildren defines the storage prefix for children.
	PrefixChildren

	// PrefixMissingBlock defines the storage prefix for missing block.
	PrefixMissingBlock

	// PrefixAttachments defines the storage prefix for attachments.
	PrefixAttachments

	// PrefixMarkerConflictIDMapping defines the storage prefix for the PrefixMarkerConflictIDMapping.
	PrefixMarkerConflictIDMapping

	// PrefixConflictVoters defines the storage prefix for the ConflictVoters.
	PrefixConflictVoters

	// PrefixLatestConflictVotes defines the storage prefix for the LatestConflictVotes.
	PrefixLatestConflictVotes

	// PrefixLatestMarkerVotes defines the storage prefix for the LatestMarkerVotes.
	PrefixLatestMarkerVotes

	// PrefixConflictWeight defines the storage prefix for the ConflictWeight.
	PrefixConflictWeight

	// PrefixMarkerBlockMapping defines the storage prefix for the MarkerBlockMapping.
	PrefixMarkerBlockMapping

	// DBSequenceNumber defines the db sequence number.
	DBSequenceNumber = "seq"
)
View Source
const ChildTypeLength = 1

ChildTypeLength contains the amount of bytes that a marshaled version of the ChildType contains.

View Source
const (
	// DefaultSyncTimeWindow is the default sync time window.
	DefaultSyncTimeWindow = 2 * time.Minute
)
View Source
const (
	// LastValidBlockType counts StrongParents, WeakParents, ShallowLikeParents.
	LastValidBlockType = ShallowLikeParentType
)
View Source
const (
	// MaxReattachmentTimeMin defines the max reattachment time.
	MaxReattachmentTimeMin = 10 * time.Minute
)
View Source
const (
	// MinMana is the minimum amount of Mana needed to issue blocks.
	// MaxBlockSize / MinMana is also the upper bound of iterations inside one schedule call, as such it should not be too small.
	MinMana float64 = 1.0
)

Variables

View Source
var (
	// ErrNoStrongParents is triggered if there no strong parents.
	ErrNoStrongParents = errors.New("missing strong blocks in first parent block")
	// ErrBlockTypeIsUnknown is triggered when the block type is unknown.
	ErrBlockTypeIsUnknown = errors.Errorf("block types must range from %d-%d", 1, LastValidBlockType)
	// ErrConflictingReferenceAcrossBlocks is triggered if there conflicting references across blocks.
	ErrConflictingReferenceAcrossBlocks = errors.New("different blocks have conflicting references")
)
View Source
var (
	// ErrNotBootstrapped is triggered when somebody tries to issue a Payload before the Mesh is fully bootstrapped.
	ErrNotBootstrapped = errors.New("mesh not bootstrapped")
	// ErrParentsInvalid is returned when one or more parents of a block is invalid.
	ErrParentsInvalid = errors.New("one or more parents is invalid")
)
View Source
var (
	// ErrInvalidPOWDifficultly is returned when the nonce of a block does not fulfill the PoW difficulty.
	ErrInvalidPOWDifficultly = errors.New("invalid PoW")

	// ErrBlockTooSmall is returned when the block does not contain enough data for the PoW.
	ErrBlockTooSmall = errors.New("block too small")

	// ErrInvalidSignature is returned when a block contains an invalid signature.
	ErrInvalidSignature = fmt.Errorf("invalid signature")

	// ErrReceivedDuplicateBytes is returned when duplicated bytes are rejected.
	ErrReceivedDuplicateBytes = fmt.Errorf("received duplicate bytes")

	// ErrInvalidBlockAndTransactionTimestamp is returned when the block its transaction timestamps are invalid.
	ErrInvalidBlockAndTransactionTimestamp = fmt.Errorf("invalid block and transaction timestamp")
)
View Source
var (
	// ErrInvalidIssuer is returned when an invalid block is passed to the rate setter.
	ErrInvalidIssuer = errors.New("block not issued by local node")
	// ErrStopped is returned when a block is passed to a stopped rate setter.
	ErrStopped = errors.New("rate setter stopped")
)
View Source
var DefaultRequesterOptions = &RequesterOptions{
	RetryInterval:       10 * time.Second,
	RetryJitter:         10 * time.Second,
	MaxRequestThreshold: 500,
}

DefaultRequesterOptions defines the default options that are used when creating Requester instances.

View Source
var ErrNotRunning = errors.New("scheduler stopped")

ErrNotRunning is returned when a block is submitted when the scheduler has been stopped.

View Source
var LatestMarkerVotesKeyPartition = objectstorage.PartitionKey(markers.SequenceID(0).Length(), identity.IDLength)

LatestMarkerVotesKeyPartition defines the partition of the storage key of the LastMarkerVotes model.

View Source
var MarkerBlockMappingPartitionKeys = objectstorage.PartitionKey(markers.SequenceID(0).Length(), markers.Index(0).Length())

MarkerBlockMappingPartitionKeys defines the "layout" of the key. This enables prefix iterations in the object storage.

View Source
var MaxDeficit = new(big.Rat).SetInt64(int64(MaxBlockSize))

MaxDeficit is the maximum cap for accumulated deficit, i.e. max bytes that can be scheduled without waiting. It must be >= MaxBlockSize.

View Source
var ParentTypeToChildType = map[ParentsType]ChildType{
	StrongParentType:      StrongChild,
	WeakParentType:        WeakChild,
	ShallowLikeParentType: ShallowLikeChild,
}

ParentTypeToChildType represents a convenient mapping between a parent type and the child type.

View Source
var ZeroWorker = WorkerFunc(func([]byte) (uint64, error) { return 0, nil })

ZeroWorker is a PoW worker that always returns 0 as the nonce.

Functions

func BlockIDToContext

func BlockIDToContext(ctx context.Context, blockID BlockID) context.Context

BlockIDToContext adds the BlockID to the given context.

func IssueAndValidateBlockApproval

func IssueAndValidateBlockApproval(t *testing.T, blockAlias string, eventMock *EventMock, testFramework *BlockTestFramework, expectedConflictWeights map[string]float64, expectedMarkerWeights map[markers.Marker]float64)

IssueAndValidateBlockApproval issues the blk by the given alias and assets the expected weights.

Types

type ActivityUpdatesCount

type ActivityUpdatesCount map[identity.ID]uint64

ActivityUpdatesCount stores the counters on how many times activity record was updated.

type ApprovalWeightManager

type ApprovalWeightManager struct {
	Events *ApprovalWeightManagerEvents
	// contains filtered or unexported fields
}

ApprovalWeightManager is a Mesh component to keep track of relative weights of conflicts and markers so that consensus can be based on the heaviest perception on the mesh as a data structure.

func NewApprovalWeightManager

func NewApprovalWeightManager(mesh *Mesh) (approvalWeightManager *ApprovalWeightManager)

NewApprovalWeightManager is the constructor for ApprovalWeightManager.

func (*ApprovalWeightManager) Setup

func (a *ApprovalWeightManager) Setup()

Setup sets up the behavior of the component by making it attach to the relevant events of other components.

func (*ApprovalWeightManager) Shutdown

func (a *ApprovalWeightManager) Shutdown()

Shutdown shuts down the ApprovalWeightManager and persists its state.

func (*ApprovalWeightManager) VotersOfConflict

func (a *ApprovalWeightManager) VotersOfConflict(conflictID utxo.TransactionID) (voters *Voters)

VotersOfConflict returns the Voters of the given conflict ledger.ConflictID.

func (*ApprovalWeightManager) WeightOfConflict

func (a *ApprovalWeightManager) WeightOfConflict(conflictID utxo.TransactionID) (weight float64)

WeightOfConflict returns the weight of the given Conflict that was added by Voters of the given epoch.

func (*ApprovalWeightManager) WeightOfMarker

func (a *ApprovalWeightManager) WeightOfMarker(marker markers.Marker, anchorTime time.Time) (weight float64)

WeightOfMarker returns the weight of the given marker based on the anchorTime.

type ApprovalWeightManagerEvents

type ApprovalWeightManagerEvents struct {
	// BlockProcessed is triggered once a block is finished being processed by the ApprovalWeightManager.
	BlockProcessed *event.Event[*BlockProcessedEvent]
	// ConflictWeightChanged is triggered when a conflict's weight changed.
	ConflictWeightChanged *event.Event[*ConflictWeightChangedEvent]
	// MarkerWeightChanged is triggered when a marker's weight changed.
	MarkerWeightChanged *event.Event[*MarkerWeightChangedEvent]
}

ApprovalWeightManagerEvents represents events happening in the ApprovalWeightManager.

type Attachment

type Attachment struct {
	model.StorableReference[Attachment, *Attachment, utxo.TransactionID, BlockID] `serix:"0"`
}

Attachment stores the information which transaction was attached by which block. We need this to be able to perform reverse lookups from transactions to their corresponding blocks that attach them.

func NewAttachment

func NewAttachment(transactionID utxo.TransactionID, blockID BlockID) *Attachment

NewAttachment creates an attachment object with the given information.

func (*Attachment) BlockID

func (a *Attachment) BlockID() BlockID

BlockID returns the blockID of this Attachment.

func (*Attachment) TransactionID

func (a *Attachment) TransactionID() utxo.TransactionID

TransactionID returns the transactionID of this Attachment.

type Block

type Block struct {
	model.Storable[BlockID, Block, *Block, BlockModel] `serix:"0"`
	// contains filtered or unexported fields
}

Block represents the core block for the base layer Mesh.

func NewBlock

func NewBlock(references ParentBlockIDs, issuingTime time.Time, issuerPublicKey ed25519.PublicKey,
	sequenceNumber uint64, blkPayload payload.Payload, nonce uint64, signature ed25519.Signature,
	latestConfirmedEpoch epoch.Index, ecRecord *epoch.ECRecord, versionOpt ...uint8,
) *Block

NewBlock creates a new block with the details provided by the issuer.

func NewBlockWithValidation

func NewBlockWithValidation(references ParentBlockIDs, issuingTime time.Time, issuerPublicKey ed25519.PublicKey,
	sequenceNumber uint64, blkPayload payload.Payload, nonce uint64, signature ed25519.Signature, latestConfirmedEpoch epoch.Index, epochCommitment *epoch.ECRecord, version ...uint8,
) (result *Block, err error)

NewBlockWithValidation creates a new block while performing ths following syntactical checks: 1. A Strong Parents Block must exist. 2. Parents Block types cannot repeat. 3. Parent count per block 1 <= x <= 8. 4. Parents unique within block. 5. Parents lexicographically sorted within block. 7. Blocks should be ordered by type in ascending order. 6. A Parent(s) repetition is only allowed when it occurs across Strong and Like parents.

func (*Block) DetermineID

func (m *Block) DetermineID() (err error)

DetermineID calculates and sets the block's BlockID.

func (*Block) ECR

func (m *Block) ECR() epoch.ECR

ECR returns the ECR of the block.

func (*Block) ECRecordEI

func (m *Block) ECRecordEI() epoch.Index

ECRecordEI returns the EI of the ECRecord a block contains.

func (*Block) ForEachParent

func (m *Block) ForEachParent(consumer func(parent Parent))

ForEachParent executes a consumer func for each parent.

func (*Block) ForEachParentByType

func (m *Block) ForEachParentByType(parentType ParentsType, consumer func(parentBlockID BlockID) bool)

ForEachParentByType executes a consumer func for each strong parent.

func (*Block) FromBytes

func (m *Block) FromBytes(bytes []byte) (err error)

FromBytes unmarshals a Block from a sequence of bytes.

func (*Block) IDBytes

func (m *Block) IDBytes() []byte

IDBytes implements Element interface in scheduler NodeQueue that returns the BlockID of the block in bytes.

func (*Block) IssuerPublicKey

func (m *Block) IssuerPublicKey() ed25519.PublicKey

IssuerPublicKey returns the public key of the block issuer.

func (*Block) IssuingTime

func (m *Block) IssuingTime() time.Time

IssuingTime returns the time when this block was created.

func (*Block) LatestConfirmedEpoch

func (m *Block) LatestConfirmedEpoch() epoch.Index

LatestConfirmedEpoch returns the LatestConfirmedEpoch of the block.

func (*Block) Nonce

func (m *Block) Nonce() uint64

Nonce returns the Nonce of the block.

func (*Block) Parents

func (m *Block) Parents() (parents []BlockID)

func (*Block) ParentsByType

func (m *Block) ParentsByType(parentType ParentsType) BlockIDs

ParentsByType returns a slice of all parents of the desired type.

func (*Block) ParentsCountByType

func (m *Block) ParentsCountByType(parentType ParentsType) uint8

ParentsCountByType returns the total parents count of this block.

func (*Block) Payload

func (m *Block) Payload() payload.Payload

Payload returns the Payload of the block.

func (*Block) PrevEC

func (m *Block) PrevEC() epoch.EC

PrevEC returns the PrevEC of the block.

func (*Block) SequenceNumber

func (m *Block) SequenceNumber() uint64

SequenceNumber returns the sequence number of this block.

func (*Block) Signature

func (m *Block) Signature() ed25519.Signature

Signature returns the Signature of the block.

func (*Block) Size

func (m *Block) Size() int

Size returns the block size in bytes.

func (*Block) String

func (m *Block) String() string

func (*Block) VerifySignature

func (m *Block) VerifySignature() (valid bool, err error)

VerifySignature verifies the Signature of the block.

func (*Block) Version

func (m *Block) Version() uint8

Version returns the block Version.

type BlockAcceptedEvent

type BlockAcceptedEvent struct {
	Block *Block
}

type BlockBookedEvent

type BlockBookedEvent struct {
	BlockID BlockID
}

type BlockConflictUpdatedEvent

type BlockConflictUpdatedEvent struct {
	BlockID    BlockID
	ConflictID utxo.TransactionID
}

type BlockConstructedEvent

type BlockConstructedEvent struct {
	Block *Block
}

type BlockDiscardedEvent

type BlockDiscardedEvent struct {
	BlockID BlockID
}

type BlockDispatchedEvent

type BlockDispatchedEvent struct {
	BlockID BlockID
}

type BlockFactory

type BlockFactory struct {
	Events *BlockFactoryEvents

	ReferenceProvider *ReferenceProvider
	// contains filtered or unexported fields
}

BlockFactory acts as a factory to create new blocks.

func NewBlockFactory

func NewBlockFactory(mesh *Mesh, selector TipSelector, referencesFunc ...ReferencesFunc) *BlockFactory

NewBlockFactory creates a new block factory.

func (*BlockFactory) EarliestAttachment

func (f *BlockFactory) EarliestAttachment(transactionIDs utxo.TransactionIDs, earliestAttachmentMustBeBooked ...bool) (earliestAttachment *Block)

func (*BlockFactory) IssuePayload

func (f *BlockFactory) IssuePayload(p payload.Payload, parentsCount ...int) (*Block, error)

IssuePayload creates a new block including sequence number and tip selection and returns it.

func (*BlockFactory) IssuePayloadWithReferences

func (f *BlockFactory) IssuePayloadWithReferences(p payload.Payload, references ParentBlockIDs, parentsCount ...int) (*Block, error)

IssuePayloadWithReferences creates a new block with the references submit.

func (*BlockFactory) LatestAttachment

func (f *BlockFactory) LatestAttachment(transactionID utxo.TransactionID) (latestAttachment *Block)

func (*BlockFactory) SetTimeout

func (f *BlockFactory) SetTimeout(timeout time.Duration)

SetTimeout sets the timeout for PoW.

func (*BlockFactory) SetWorker

func (f *BlockFactory) SetWorker(worker Worker)

SetWorker sets the PoW worker to be used for the blocks.

func (*BlockFactory) Shutdown

func (f *BlockFactory) Shutdown()

Shutdown closes the BlockFactory and persists the sequence number.

type BlockFactoryEvents

type BlockFactoryEvents struct {
	// Fired when a block is built including tips, sequence number and other metadata.
	BlockConstructed *event.Event[*BlockConstructedEvent]

	// Fired when an error occurred.
	Error *event.Event[error]
}

BlockFactoryEvents represents events happening on a block factory.

func NewBlockFactoryEvents

func NewBlockFactoryEvents() (new *BlockFactoryEvents)

NewBlockFactoryEvents returns a new BlockFactoryEvents object.

type BlockFilter

type BlockFilter interface {
	// Filter filters up on the given block and peer and calls the acceptance callback
	// if the input passes or the rejection callback if the input is rejected.
	Filter(blk *Block, peer *peer.Peer)
	// OnAccept registers the given callback as the acceptance function of the filter.
	OnAccept(callback func(blk *Block, peer *peer.Peer))
	// OnReject registers the given callback as the rejection function of the filter.
	OnReject(callback func(blk *Block, err error, peer *peer.Peer))
	// Closer closes the filter.
	io.Closer
}

BlockFilter filters based on blocks and peers.

type BlockID

type BlockID struct {
	Identifier types.Identifier `serix:"0"`
	EpochIndex epoch.Index      `serix:"1"`
}

BlockID identifies a block via its BLAKE2b-256 hash of its bytes.

var EmptyBlockID BlockID

EmptyBlockID is an empty id.

func BlockIDFromContext

func BlockIDFromContext(ctx context.Context) BlockID

BlockIDFromContext returns the BlockID from the given context.

func NewBlockID

func NewBlockID(identifier [32]byte, epochIndex epoch.Index) (new BlockID)

NewBlockID returns a new BlockID for the given data.

func (BlockID) Alias

func (b BlockID) Alias() (alias string)

Alias returns the human-readable alias of the BlockID (or the base58 encoded bytes if no alias was set).

func (BlockID) Base58

func (b BlockID) Base58() (base58Encoded string)

Base58 returns a base58 encoded version of the BlockID.

func (BlockID) Bytes

func (b BlockID) Bytes() (serialized []byte)

Bytes returns a serialized version of the BlockID.

func (BlockID) CompareTo

func (b BlockID) CompareTo(other BlockID) int

CompareTo does a lexicographical comparison to another blockID. Returns 0 if equal, -1 if smaller, or 1 if larger than other. Passing nil as other will result in a panic.

func (*BlockID) FromBase58

func (b *BlockID) FromBase58(base58EncodedString string) (err error)

FromBase58 un-serializes a BlockID from a base58 encoded string.

func (*BlockID) FromBytes

func (b *BlockID) FromBytes(serialized []byte) (consumedBytes int, err error)

FromBytes deserializes a BlockID from a byte slice.

func (*BlockID) FromRandomness

func (b *BlockID) FromRandomness(optionalEpoch ...epoch.Index) (err error)

FromRandomness generates a random BlockID.

func (BlockID) Length

func (b BlockID) Length() int

Length returns the byte length of a serialized BlockID.

func (BlockID) RegisterAlias

func (b BlockID) RegisterAlias(alias string)

RegisterAlias allows to register a human-readable alias for the BlockID which will be used as a replacement for the String method.

func (BlockID) String

func (b BlockID) String() (humanReadable string)

String returns a human-readable version of the BlockID.

func (BlockID) UnregisterAlias

func (b BlockID) UnregisterAlias()

UnregisterAlias allows to unregister a previously registered alias.

type BlockIDs

type BlockIDs map[BlockID]types.Empty

BlockIDs is a set of BlockIDs where every BlockID is stored only once.

func NewBlockIDs

func NewBlockIDs(blkIDs ...BlockID) BlockIDs

NewBlockIDs construct a new BlockID collection from the optional BlockIDs.

func (BlockIDs) Add

func (m BlockIDs) Add(blockID BlockID) BlockIDs

Add adds a BlockID to the collection and returns the collection to enable chaining.

func (BlockIDs) AddAll

func (m BlockIDs) AddAll(blockIDs BlockIDs) BlockIDs

AddAll adds all BlockIDs to the collection and returns the collection to enable chaining.

func (BlockIDs) Base58

func (m BlockIDs) Base58() (result []string)

Base58 returns a string slice of base58 BlockID.

func (BlockIDs) Clone

func (m BlockIDs) Clone() (clonedBlockIDs BlockIDs)

Clone creates a copy of the BlockIDs.

func (BlockIDs) Contains

func (m BlockIDs) Contains(target BlockID) (contains bool)

Contains checks if the given target BlockID is part of the BlockIDs.

func (BlockIDs) Empty

func (m BlockIDs) Empty() (empty bool)

Empty checks if BlockIDs is empty.

func (BlockIDs) First

func (m BlockIDs) First() BlockID

First returns the first element in BlockIDs (not ordered). This method only makes sense if there is exactly one element in the collection.

func (BlockIDs) Slice

func (m BlockIDs) Slice() []BlockID

Slice converts the set of BlockIDs into a slice of BlockIDs.

func (BlockIDs) String

func (m BlockIDs) String() string

String returns a human-readable Version of the BlockIDs.

func (BlockIDs) Subtract

func (m BlockIDs) Subtract(other BlockIDs) BlockIDs

Subtract removes all other from the collection and returns the collection to enable chaining.

type BlockInvalidEvent

type BlockInvalidEvent struct {
	BlockID BlockID
	Error   error
}

BlockInvalidEvent is struct that is passed along with triggering a blockInvalidEvent.

type BlockMetadata

type BlockMetadata struct {
	model.Storable[BlockID, BlockMetadata, *BlockMetadata, blockMetadataModel] `serix:"0"`
}

BlockMetadata defines the metadata for a block.

func NewBlockMetadata

func NewBlockMetadata(blockID BlockID) *BlockMetadata

NewBlockMetadata creates a new BlockMetadata from the specified blockID.

func (*BlockMetadata) AddConflictID

func (m *BlockMetadata) AddConflictID(conflictID utxo.TransactionID) (modified bool)

AddConflictID sets the ConflictIDs of the added Conflicts.

func (*BlockMetadata) AddedConflictIDs

func (m *BlockMetadata) AddedConflictIDs() utxo.TransactionIDs

AddedConflictIDs returns the ConflictIDs of the added Conflicts of the Block.

func (*BlockMetadata) BookedTime

func (m *BlockMetadata) BookedTime() time.Time

BookedTime returns the time when the block represented by this metadata was booked.

func (*BlockMetadata) ConfirmationState

func (m *BlockMetadata) ConfirmationState() (result confirmation.State)

ConfirmationState returns the confirmation state.

func (*BlockMetadata) ConfirmationStateTime

func (m *BlockMetadata) ConfirmationStateTime() time.Time

ConfirmationStateTime returns the time the confirmation state was set.

func (*BlockMetadata) DiscardedTime

func (m *BlockMetadata) DiscardedTime() time.Time

DiscardedTime returns when the block was discarded.

func (*BlockMetadata) IsBooked

func (m *BlockMetadata) IsBooked() (result bool)

IsBooked returns true if the block represented by this metadata is booked. False otherwise.

func (*BlockMetadata) IsObjectivelyInvalid

func (m *BlockMetadata) IsObjectivelyInvalid() (result bool)

IsObjectivelyInvalid returns true if the block represented by this metadata is objectively invalid.

func (*BlockMetadata) IsSolid

func (m *BlockMetadata) IsSolid() (result bool)

IsSolid returns true if the block represented by this metadata is solid. False otherwise.

func (*BlockMetadata) IsSubjectivelyInvalid

func (m *BlockMetadata) IsSubjectivelyInvalid() (result bool)

IsSubjectivelyInvalid returns true if the block represented by this metadata is subjectively invalid.

func (*BlockMetadata) QueuedTime

func (m *BlockMetadata) QueuedTime() time.Time

QueuedTime returns the time a block entered the scheduling queue.

func (*BlockMetadata) ReceivedTime

func (m *BlockMetadata) ReceivedTime() time.Time

ReceivedTime returns the time when the block was received.

func (*BlockMetadata) Scheduled

func (m *BlockMetadata) Scheduled() bool

Scheduled returns true if the block represented by this metadata was scheduled. False otherwise.

func (*BlockMetadata) ScheduledTime

func (m *BlockMetadata) ScheduledTime() time.Time

ScheduledTime returns the time when the block represented by this metadata was scheduled.

func (*BlockMetadata) SetAddedConflictIDs

func (m *BlockMetadata) SetAddedConflictIDs(addedConflictIDs utxo.TransactionIDs) (modified bool)

SetAddedConflictIDs sets the ConflictIDs of the added Conflicts.

func (*BlockMetadata) SetBooked

func (m *BlockMetadata) SetBooked(booked bool) (modified bool)

SetBooked sets the block associated with this metadata as booked. It returns true if the booked status is modified. False otherwise.

func (*BlockMetadata) SetConfirmationState

func (m *BlockMetadata) SetConfirmationState(confirmationState confirmation.State) (modified bool)

SetConfirmationState sets the confirmation state associated with this metadata. It returns true if the confirmation state is modified. False otherwise.

func (*BlockMetadata) SetDiscardedTime

func (m *BlockMetadata) SetDiscardedTime(discardedTime time.Time)

SetDiscardedTime add the discarded time of a block to the metadata.

func (*BlockMetadata) SetObjectivelyInvalid

func (m *BlockMetadata) SetObjectivelyInvalid(invalid bool) (modified bool)

SetObjectivelyInvalid sets the block associated with this metadata as objectively invalid - it returns true if the status was changed.

func (*BlockMetadata) SetQueuedTime

func (m *BlockMetadata) SetQueuedTime(queuedTime time.Time)

SetQueuedTime records the time the block entered the scheduler queue.

func (*BlockMetadata) SetScheduled

func (m *BlockMetadata) SetScheduled(scheduled bool) (modified bool)

SetScheduled sets the block associated with this metadata as scheduled. It returns true if the scheduled status is modified. False otherwise.

func (*BlockMetadata) SetSolid

func (m *BlockMetadata) SetSolid(solid bool) (modified bool)

SetSolid sets the block associated with this metadata as solid. It returns true if the solid status is modified. False otherwise.

func (*BlockMetadata) SetStructureDetails

func (m *BlockMetadata) SetStructureDetails(structureDetails *markers.StructureDetails) (modified bool)

SetStructureDetails sets the structureDetails of the block.

func (*BlockMetadata) SetSubjectivelyInvalid

func (m *BlockMetadata) SetSubjectivelyInvalid(invalid bool) (modified bool)

SetSubjectivelyInvalid sets the block associated with this metadata as subjectively invalid - it returns true if the status was changed.

func (*BlockMetadata) SetSubtractedConflictIDs

func (m *BlockMetadata) SetSubtractedConflictIDs(subtractedConflictIDs utxo.TransactionIDs) (modified bool)

SetSubtractedConflictIDs sets the ConflictIDs of the subtracted Conflicts.

func (*BlockMetadata) SolidificationTime

func (m *BlockMetadata) SolidificationTime() time.Time

SolidificationTime returns the time when the block was marked to be solid.

func (*BlockMetadata) StructureDetails

func (m *BlockMetadata) StructureDetails() *markers.StructureDetails

StructureDetails returns the structureDetails of the block.

func (*BlockMetadata) SubtractedConflictIDs

func (m *BlockMetadata) SubtractedConflictIDs() utxo.TransactionIDs

SubtractedConflictIDs returns the ConflictIDs of the subtracted Conflicts of the Block.

type BlockMissingEvent

type BlockMissingEvent struct {
	BlockID BlockID
}

type BlockModel

type BlockModel struct {
	// core properties (get sent over the wire)
	Version              uint8             `serix:"0"`
	Parents              ParentBlockIDs    `serix:"1"`
	IssuerPublicKey      ed25519.PublicKey `serix:"2"`
	IssuingTime          time.Time         `serix:"3"`
	SequenceNumber       uint64            `serix:"4"`
	PayloadBytes         []byte            `serix:"5,lengthPrefixType=uint32"`
	ECRecordEI           epoch.Index       `serix:"6"`
	ECR                  epoch.ECR         `serix:"7"`
	PrevEC               epoch.EC          `serix:"8"`
	LatestConfirmedEpoch epoch.Index       `serix:"9"`
	Nonce                uint64            `serix:"10"`
	Signature            ed25519.Signature `serix:"11"`
}

type BlockOption

type BlockOption func(*BlockTestFrameworkBlockOptions)

BlockOption is the type that is used for options that can be passed into the CreateBlock method to configure its behavior.

func WithColoredOutput

func WithColoredOutput(alias string, balances map[devnetvm.Color]uint64) BlockOption

WithColoredOutput returns a BlockOption that is used to define a colored Output for the Transaction in the Block.

func WithECRecord

func WithECRecord(ecRecord *epoch.ECRecord) BlockOption

WithECRecord returns a BlockOption that is used to define the ecr of the Block.

func WithInputs

func WithInputs(inputAliases ...string) BlockOption

WithInputs returns a BlockOption that is used to provide the Inputs of the Transaction.

func WithIssuer

func WithIssuer(issuer ed25519.PublicKey) BlockOption

WithIssuer returns a BlockOption that is used to define the issuer of the Block.

func WithIssuingTime

func WithIssuingTime(issuingTime time.Time) BlockOption

WithIssuingTime returns a BlockOption that is used to set issuing time of the Block.

func WithLatestConfirmedEpoch

func WithLatestConfirmedEpoch(ei epoch.Index) BlockOption

WithLatestConfirmedEpoch returns a BlockOption that is used to define the latestConfirmedEpoch of the Block.

func WithOutput

func WithOutput(alias string, balance uint64) BlockOption

WithOutput returns a BlockOption that is used to define a non-colored Output for the Transaction in the Block.

func WithReattachment

func WithReattachment(blockAlias string) BlockOption

WithReattachment returns a BlockOption that is used to select payload of which Block should be reattached.

func WithSequenceNumber

func WithSequenceNumber(sequenceNumber uint64) BlockOption

WithSequenceNumber returns a BlockOption that is used to define the sequence number of the Block.

func WithShallowLikeParents

func WithShallowLikeParents(blockAliases ...string) BlockOption

WithShallowLikeParents returns a BlockOption that is used to define the shallow like parents of the Block.

func WithStrongParents

func WithStrongParents(blockAliases ...string) BlockOption

WithStrongParents returns a BlockOption that is used to define the strong parents of the Block.

func WithWeakParents

func WithWeakParents(blockAliases ...string) BlockOption

WithWeakParents returns a BlockOption that is used to define the weak parents of the Block.

type BlockOrphanedEvent

type BlockOrphanedEvent struct {
	Block  *Block
	Reason error
}

type BlockParsedEvent

type BlockParsedEvent struct {
	// Block contains the parsed Block.
	Block *Block

	// Peer contains the node that sent this Block to the node.
	Peer *peer.Peer
}

BlockParsedEvent holds the information provided by the BlockParsed event that gets triggered when a block was fully parsed and syntactically validated.

type BlockProcessedEvent

type BlockProcessedEvent struct {
	BlockID BlockID
}

BlockProcessedEvent holds information about a processed block.

type BlockRejectedEvent

type BlockRejectedEvent struct {
	Block *Block
	Peer  *peer.Peer
	Error error
}

BlockRejectedEvent holds the information provided by the BlockRejected event that gets triggered when the Block was detected to be invalid.

type BlockRemovedEvent

type BlockRemovedEvent struct {
	BlockID BlockID
}

type BlockScheduledEvent

type BlockScheduledEvent struct {
	BlockID BlockID
}

type BlockSignatureFilter

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

BlockSignatureFilter filters blocks based on whether their signatures are valid.

func NewBlockSignatureFilter

func NewBlockSignatureFilter() *BlockSignatureFilter

NewBlockSignatureFilter creates a new block signature filter.

func (*BlockSignatureFilter) Close

func (f *BlockSignatureFilter) Close() error

Close closes the filter.

func (*BlockSignatureFilter) Filter

func (f *BlockSignatureFilter) Filter(blk *Block, peer *peer.Peer)

Filter filters up on the given bytes and peer and calls the acceptance callback if the input passes or the rejection callback if the input is rejected.

func (*BlockSignatureFilter) OnAccept

func (f *BlockSignatureFilter) OnAccept(callback func(blk *Block, peer *peer.Peer))

OnAccept registers the given callback as the acceptance function of the filter.

func (*BlockSignatureFilter) OnReject

func (f *BlockSignatureFilter) OnReject(callback func(blk *Block, err error, peer *peer.Peer))

OnReject registers the given callback as the rejection function of the filter.

type BlockSkippedEvent

type BlockSkippedEvent struct {
	BlockID BlockID
}

type BlockSolidEvent

type BlockSolidEvent struct {
	Block *Block
}

type BlockStoredEvent

type BlockStoredEvent struct {
	Block *Block
}

type BlockTestFramework

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

BlockTestFramework implements a framework for conveniently issuing blocks in a mesh as part of unit tests in a simplified way.

func NewBlockTestFramework

func NewBlockTestFramework(mesh *Mesh, options ...BlockTestFrameworkOption) (blockTestFramework *BlockTestFramework)

NewBlockTestFramework is the constructor of the BlockTestFramework.

func (*BlockTestFramework) Block

func (m *BlockTestFramework) Block(alias string) (block *Block)

Block retrieves the Blocks that is associated with the given alias.

func (*BlockTestFramework) BlockIDs

func (m *BlockTestFramework) BlockIDs(aliases ...string) (blockIDs BlockIDs)

BlockIDs retrieves the Blocks that is associated with the given alias.

func (*BlockTestFramework) BlockMetadata

func (m *BlockTestFramework) BlockMetadata(alias string) (blockMetadata *BlockMetadata)

BlockMetadata retrieves the BlockMetadata that is associated with the given alias.

func (*BlockTestFramework) Conflict

Conflict returns the conflict emerging from the transaction contained within the given block. This function thus only works on the block creating ledger.Conflict. Panics if the block's payload isn't a transaction.

func (*BlockTestFramework) ConflictID

func (m *BlockTestFramework) ConflictID(alias string) (conflictID utxo.TransactionID)

ConflictID returns the ConflictID registered with the given alias.

func (*BlockTestFramework) ConflictIDFromBlock

func (m *BlockTestFramework) ConflictIDFromBlock(blockAlias string) utxo.TransactionID

ConflictIDFromBlock returns the ConflictID of the Transaction contained in the Block associated with the given alias.

func (*BlockTestFramework) ConflictIDs

func (m *BlockTestFramework) ConflictIDs(aliases ...string) (conflictIDs utxo.TransactionIDs)

ConflictIDs returns the ConflictIDs registered with the given aliases.

func (*BlockTestFramework) CreateBlock

func (m *BlockTestFramework) CreateBlock(blockAlias string, blockOptions ...BlockOption) (block *Block)

CreateBlock creates a Block with the given alias and BlockTestFrameworkBlockOptions.

func (*BlockTestFramework) IncreaseMarkersIndexCallback

func (m *BlockTestFramework) IncreaseMarkersIndexCallback(markers.SequenceID, markers.Index) bool

IncreaseMarkersIndexCallback is the IncreaseMarkersIndexCallback that the BlockTestFramework uses to determine when to assign new Markers to blocks.

func (*BlockTestFramework) IssueBlocks

func (m *BlockTestFramework) IssueBlocks(blockAliases ...string) *BlockTestFramework

IssueBlocks stores the given Blocks in the Storage and triggers the processing by the Mesh.

func (*BlockTestFramework) LatestCommitment

func (m *BlockTestFramework) LatestCommitment() (ecRecord *epoch.ECRecord, latestConfirmedEpoch epoch.Index, err error)

LatestCommitment gets the latest commitment.

func (*BlockTestFramework) Output

func (m *BlockTestFramework) Output(alias string) (output devnetvm.Output)

Output retrieves the Output that is associated with the given alias.

func (*BlockTestFramework) OutputMetadata

func (m *BlockTestFramework) OutputMetadata(outputID utxo.OutputID) (outMeta *ledger.OutputMetadata)

OutputMetadata returns the given output metadata.

func (*BlockTestFramework) PreventNewMarkers

func (m *BlockTestFramework) PreventNewMarkers(enabled bool) *BlockTestFramework

PreventNewMarkers disables the generation of new Markers for the given Blocks.

func (*BlockTestFramework) RegisterConflictID

func (m *BlockTestFramework) RegisterConflictID(alias, blockAlias string)

RegisterConflictID registers a ConflictID from the given Blocks' transactions with the BlockTestFramework and also an alias when printing the ConflictID.

func (*BlockTestFramework) RegisterTransactionID

func (m *BlockTestFramework) RegisterTransactionID(alias, blockAlias string)

func (*BlockTestFramework) Snapshot

func (m *BlockTestFramework) Snapshot() (snapshot *ledger.Snapshot)

Snapshot returns the Snapshot of the test framework.

func (*BlockTestFramework) Transaction

func (m *BlockTestFramework) Transaction(blockAlias string) (tx utxo.Transaction)

Transaction returns the transaction contained within the given block. Panics if the block's payload isn't a transaction.

func (*BlockTestFramework) TransactionID

func (m *BlockTestFramework) TransactionID(blockAlias string) utxo.TransactionID

TransactionID returns the TransactionID of the Transaction contained in the Block associated with the given alias.

func (*BlockTestFramework) TransactionMetadata

func (m *BlockTestFramework) TransactionMetadata(blockAlias string) (txMeta *ledger.TransactionMetadata)

TransactionMetadata returns the transaction metadata of the transaction contained within the given block. Panics if the block's payload isn't a transaction.

func (*BlockTestFramework) WaitUntilAllTasksProcessed

func (m *BlockTestFramework) WaitUntilAllTasksProcessed() (self *BlockTestFramework)

type BlockTestFrameworkBlockOptions

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

BlockTestFrameworkBlockOptions is a struct that represents a collection of options that can be set when creating a Block with the BlockTestFramework.

func NewBlockTestFrameworkBlockOptions

func NewBlockTestFrameworkBlockOptions(options ...BlockOption) (blockOptions *BlockTestFrameworkBlockOptions)

NewBlockTestFrameworkBlockOptions is the constructor for the BlockTestFrameworkBlockOptions.

type BlockTestFrameworkOption

type BlockTestFrameworkOption func(*BlockTestFrameworkOptions)

BlockTestFrameworkOption is the type that is used for options that can be passed into the BlockTestFramework to configure its behavior.

func WithColoredGenesisOutput

func WithColoredGenesisOutput(alias string, balances map[devnetvm.Color]uint64) BlockTestFrameworkOption

WithColoredGenesisOutput returns a BlockTestFrameworkOption that defines a genesis Output that is loaded as part of the initial snapshot and that supports colored coins.

func WithGenesisOutput

func WithGenesisOutput(alias string, balance uint64) BlockTestFrameworkOption

WithGenesisOutput returns a BlockTestFrameworkOption that defines a genesis Output that is loaded as part of the initial snapshot.

type BlockTestFrameworkOptions

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

BlockTestFrameworkOptions is a container that holds the values of all configurable options of the BlockTestFramework.

func NewBlockTestFrameworkOptions

func NewBlockTestFrameworkOptions(options ...BlockTestFrameworkOption) (frameworkOptions *BlockTestFrameworkOptions)

NewBlockTestFrameworkOptions is the constructor for the BlockTestFrameworkOptions.

type Booker

type Booker struct {
	// Events is a dictionary for the Booker related Events.
	Events *BookerEvents

	MarkersManager *ConflictMarkersMapper
	// contains filtered or unexported fields
}

Booker is a Mesh component that takes care of booking Blocks and Transactions by assigning them to the corresponding Conflict of the ledger state.

func NewBooker

func NewBooker(mesh *Mesh) (blockBooker *Booker)

NewBooker is the constructor of a Booker.

func (*Booker) BlockConflictIDs

func (b *Booker) BlockConflictIDs(blockID BlockID) (conflictIDs *set.AdvancedSet[utxo.TransactionID], err error)

BlockConflictIDs returns the ConflictIDs of the given Block.

func (*Booker) BookBlock

func (b *Booker) BookBlock(block *Block, blockMetadata *BlockMetadata) (err error)

BookBlock tries to book the given Block (and potentially its contained Transaction) into the ledger and the Mesh. It fires a BlockBooked event if it succeeds. If the Block is invalid it fires a BlockInvalid event. Booking a block essentially means that parents are examined, the conflict of the block determined based on the conflict inheritance rules of the like switch and markers are inherited. If everything is valid, the block is marked as booked. Following, the block conflict is set, and it can continue in the dataflow to add support to the determined conflicts and markers.

func (*Booker) PayloadConflictIDs

func (b *Booker) PayloadConflictIDs(blockID BlockID) (conflictIDs *set.AdvancedSet[utxo.TransactionID], err error)

PayloadConflictIDs returns the ConflictIDs of the payload contained in the given Block.

func (*Booker) PropagateForkedConflict

func (b *Booker) PropagateForkedConflict(transactionID utxo.TransactionID, addedConflictID utxo.TransactionID, removedConflictIDs *set.AdvancedSet[utxo.TransactionID]) (err error)

PropagateForkedConflict propagates the forked ConflictID to the future cone of the attachments of the given Transaction.

func (*Booker) Setup

func (b *Booker) Setup()

Setup sets up the behavior of the component by making it attach to the relevant events of other components.

func (*Booker) Shutdown

func (b *Booker) Shutdown()

Shutdown shuts down the Booker and persists its state.

type BookerEvents

type BookerEvents struct {
	// BlockBooked is triggered when a Block was booked (it's Conflict, and it's Payload's Conflict were determined).
	BlockBooked *event.Event[*BlockBookedEvent]

	// BlockConflictUpdated is triggered when the ConflictID of a Block is changed in its BlockMetadata.
	BlockConflictUpdated *event.Event[*BlockConflictUpdatedEvent]

	// MarkerConflictAdded is triggered when a Marker is mapped to a new ConflictID.
	MarkerConflictAdded *event.Event[*MarkerConflictAddedEvent]

	// Error gets triggered when the Booker faces an unexpected error.
	Error *event.Event[error]
}

BookerEvents represents events happening in the Booker.

func NewBookerEvents

func NewBookerEvents() (new *BookerEvents)

type BootstrappedEvent

type BootstrappedEvent struct{}

BootstrappedEvent represents a bootstrapped event.

type BytesFilter

type BytesFilter interface {
	// Filter filters up on the given bytes and peer and calls the acceptance callback
	// if the input passes or the rejection callback if the input is rejected.
	Filter(bytes []byte, peer *peer.Peer)
	// OnAccept registers the given callback as the acceptance function of the filter.
	OnAccept(callback func(bytes []byte, peer *peer.Peer))
	// OnReject registers the given callback as the rejection function of the filter.
	OnReject(callback func(bytes []byte, err error, peer *peer.Peer))
}

BytesFilter filters based on byte slices and peers.

type BytesRejectedEvent

type BytesRejectedEvent struct {
	Bytes []byte
	Peer  *peer.Peer
	Error error
}

BytesRejectedEvent holds the information provided by the BytesRejected event that gets triggered when the bytes of a Block did not pass the parsing step.

type CManaWeightProvider

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

CManaWeightProvider is a WeightProvider for consensus mana. It keeps track of active nodes based on their time-based activity in relation to activeTimeThreshold.

func NewCManaWeightProvider

func NewCManaWeightProvider(manaRetrieverFunc ManaRetrieverFunc, timeRetrieverFunc TimeRetrieverFunc, confirmedEpochRetrieverFunc ConfirmedEpochRetrieverFunc, store ...kvstore.KVStore) (cManaWeightProvider *CManaWeightProvider)

NewCManaWeightProvider is the constructor for CManaWeightProvider.

func (*CManaWeightProvider) LoadActiveNodes

func (c *CManaWeightProvider) LoadActiveNodes(loadedActiveNodes epoch.SnapshotEpochActivity)

LoadActiveNodes loads the activity log to weight provider.

func (*CManaWeightProvider) Remove

func (c *CManaWeightProvider) Remove(ei epoch.Index, nodeID identity.ID, updatedActivityCount uint64) (removed bool)

Remove updates the underlying data structure by decreasing updatedActivityCount and removing node from active list if no activity left.

func (*CManaWeightProvider) Shutdown

func (c *CManaWeightProvider) Shutdown()

Shutdown shuts down the WeightProvider and persists its state.

func (*CManaWeightProvider) SnapshotEpochActivity

func (c *CManaWeightProvider) SnapshotEpochActivity(epochDiffIndex epoch.Index) (epochActivity epoch.SnapshotEpochActivity)

SnapshotEpochActivity returns the activity log for snapshotting.

func (*CManaWeightProvider) Update

func (c *CManaWeightProvider) Update(ei epoch.Index, nodeID identity.ID)

Update updates the underlying data structure and keeps track of active nodes.

func (*CManaWeightProvider) Weight

func (c *CManaWeightProvider) Weight(block *Block) (weight, totalWeight float64)

Weight returns the weight and total weight for the given block.

func (*CManaWeightProvider) WeightsOfRelevantVoters

func (c *CManaWeightProvider) WeightsOfRelevantVoters() (weights map[identity.ID]float64, totalWeight float64)

WeightsOfRelevantVoters returns all relevant weights.

type CachedLatestMarkerVotesByVoter

type CachedLatestMarkerVotesByVoter map[Voter]*objectstorage.CachedObject[*LatestMarkerVotes]

CachedLatestMarkerVotesByVoter represents a cached LatestMarkerVotesByVoter mapped by Voter.

func (CachedLatestMarkerVotesByVoter) Consume

func (c CachedLatestMarkerVotesByVoter) Consume(consumer func(latestMarkerVotes *LatestMarkerVotes), forceRelease ...bool) (consumed bool)

Consume unwraps the CachedObject and passes a type-casted version to the consumer (if the object is not empty - it exists). It automatically releases the object when the consumer finishes.

type Child

type Child struct {
	model.StorableReference[Child, *Child, childSourceModel, BlockID] `serix:"0"`
}

Child is an child of a given referenced block.

func NewChild

func NewChild(childType ChildType, referencedBlockID BlockID, childBlockID BlockID) *Child

NewChild creates a new child relation to the given approved/referenced block.

func (*Child) ChildBlockID

func (a *Child) ChildBlockID() BlockID

ChildBlockID returns the ID of the block which referenced the given approved block.

func (*Child) ReferencedBlockID

func (a *Child) ReferencedBlockID() BlockID

ReferencedBlockID returns the ID of the block which is referenced by the child.

func (*Child) Type

func (a *Child) Type() ChildType

Type returns the type of the Child reference.

type ChildType

type ChildType uint8

ChildType is a type that represents the different kind of reverse mapping that we have for references formed by strong and weak parents.

const (
	// StrongChild is the ChildType that represents references formed by strong parents.
	StrongChild ChildType = iota

	// WeakChild is the ChildType that represents references formed by weak parents.
	WeakChild

	// ShallowLikeChild is the ChildType that represents references formed by shallow like parents.
	ShallowLikeChild
)

func (ChildType) Bytes

func (a ChildType) Bytes() []byte

Bytes returns a marshaled version of the ChildType.

func (ChildType) String

func (a ChildType) String() string

String returns a human readable version of the ChildType.

type ConfirmationEvents

type ConfirmationEvents struct {
	BlockAccepted *event.Event[*BlockAcceptedEvent]
	BlockOrphaned *event.Event[*BlockAcceptedEvent]
}

ConfirmationEvents are events entailing confirmation.

func NewConfirmationEvents

func NewConfirmationEvents() (new *ConfirmationEvents)

NewConfirmationEvents returns a new ConfirmationEvents object.

type ConfirmationOracle

type ConfirmationOracle interface {
	IsMarkerConfirmed(marker markers.Marker) bool
	IsBlockConfirmed(blkID BlockID) bool
	IsConflictConfirmed(conflictID utxo.TransactionID) bool
	IsTransactionConfirmed(transactionID utxo.TransactionID) bool
	FirstUnconfirmedMarkerIndex(sequenceID markers.SequenceID) (unconfirmedMarkerIndex markers.Index)
	Events() *ConfirmationEvents
}

ConfirmationOracle answers questions about entities' confirmation.

type ConfirmedEpochRetrieverFunc

type ConfirmedEpochRetrieverFunc func() epoch.Index

ConfirmedEpochRetrieverFunc is a function type to retrieve the confirmed epoch index.

type ConflictMarkersMapper

type ConflictMarkersMapper struct {
	*markers.Manager
	// contains filtered or unexported fields
}

ConflictMarkersMapper is a Mesh component that takes care of managing the Markers which are used to infer structural information about the Mesh in an efficient way.

func NewConflictMarkersMapper

func NewConflictMarkersMapper(mesh *Mesh) (b *ConflictMarkersMapper)

NewConflictMarkersMapper is the constructor of the MarkersManager.

func (*ConflictMarkersMapper) BlockID

func (b *ConflictMarkersMapper) BlockID(marker markers.Marker) (blockID BlockID)

BlockID retrieves the BlockID of the given Marker.

func (*ConflictMarkersMapper) Ceiling

func (b *ConflictMarkersMapper) Ceiling(referenceMarker markers.Marker) (marker markers.Index, conflictIDs *set.AdvancedSet[utxo.TransactionID], exists bool)

Ceiling returns the smallest Index that is >= the given Marker, it's ConflictID and a boolean value indicating if it exists.

func (*ConflictMarkersMapper) ConflictIDs

func (b *ConflictMarkersMapper) ConflictIDs(marker markers.Marker) (conflictIDs *set.AdvancedSet[utxo.TransactionID])

ConflictIDs returns the ConflictID that is associated with the given Marker.

func (*ConflictMarkersMapper) Floor

func (b *ConflictMarkersMapper) Floor(referenceMarker markers.Marker) (marker markers.Index, conflictIDs *set.AdvancedSet[utxo.TransactionID], exists bool)

Floor returns the largest Index that is <= the given Marker, it's ConflictIDs and a boolean value indicating if it exists.

func (*ConflictMarkersMapper) ForEachConflictIDMapping

func (b *ConflictMarkersMapper) ForEachConflictIDMapping(sequenceID markers.SequenceID, thresholdIndex markers.Index, callback func(mappedMarker markers.Marker, mappedConflictIDs *set.AdvancedSet[utxo.TransactionID]))

ForEachConflictIDMapping iterates over all ConflictID mappings in the given Sequence that are bigger than the given thresholdIndex. Setting the thresholdIndex to 0 will iterate over all existing mappings.

func (*ConflictMarkersMapper) ForEachMarkerReferencingMarker

func (b *ConflictMarkersMapper) ForEachMarkerReferencingMarker(referencedMarker markers.Marker, callback func(referencingMarker markers.Marker))

ForEachMarkerReferencingMarker executes the callback function for each Marker of other Sequences that directly reference the given Marker.

func (*ConflictMarkersMapper) InheritStructureDetails

func (b *ConflictMarkersMapper) InheritStructureDetails(block *Block, structureDetails []*markers.StructureDetails) (newStructureDetails *markers.StructureDetails, newSequenceCreated bool)

InheritStructureDetails returns the structure Details of a Block that are derived from the StructureDetails of its strong and like parents.

func (*ConflictMarkersMapper) SetBlockID

func (b *ConflictMarkersMapper) SetBlockID(marker markers.Marker, blockID BlockID)

SetBlockID associates a BlockID with the given Marker.

func (*ConflictMarkersMapper) SetConflictIDs

func (b *ConflictMarkersMapper) SetConflictIDs(marker markers.Marker, conflictIDs *set.AdvancedSet[utxo.TransactionID]) (updated bool)

SetConflictIDs associates ledger.ConflictIDs with the given Marker.

type ConflictVote

type ConflictVote struct {
	model.Mutable[ConflictVote, *ConflictVote, conflictVoteModel] `serix:"0"`
}

ConflictVote represents a struct that holds information about what Opinion a certain Voter has on a Conflict.

func NewConflictVote

func NewConflictVote(voter Voter, votePower VotePower, conflictID utxo.TransactionID, opinion Opinion) (voteWithOpinion *ConflictVote)

NewConflictVote derives a vote for th.

func (*ConflictVote) ConflictID

func (v *ConflictVote) ConflictID() utxo.TransactionID

func (*ConflictVote) Opinion

func (v *ConflictVote) Opinion() Opinion

func (*ConflictVote) VotePower

func (v *ConflictVote) VotePower() VotePower

func (*ConflictVote) Voter

func (v *ConflictVote) Voter() Voter

func (*ConflictVote) WithConflictID

func (v *ConflictVote) WithConflictID(conflictID utxo.TransactionID) (rejectedVote *ConflictVote)

WithConflictID derives a vote for the given ConflictID.

func (*ConflictVote) WithOpinion

func (v *ConflictVote) WithOpinion(opinion Opinion) (voteWithOpinion *ConflictVote)

WithOpinion derives a vote for the given Opinion.

type ConflictVoters

type ConflictVoters struct {
	model.Storable[utxo.TransactionID, ConflictVoters, *ConflictVoters, Voters] `serix:"0"`
}

ConflictVoters is a data structure that tracks which nodes support a conflict.

func NewConflictVoters

func NewConflictVoters(conflictID utxo.TransactionID) (conflictVoters *ConflictVoters)

NewConflictVoters is the constructor for the ConflictVoters object.

func (*ConflictVoters) AddVoter

func (b *ConflictVoters) AddVoter(voter Voter) (added bool)

AddVoter adds a new Voter to the tracked ConflictID.

func (*ConflictVoters) AddVoters

func (b *ConflictVoters) AddVoters(voters *Voters) (added bool)

AddVoters adds the Voters set to the tracked ConflictID.

func (*ConflictVoters) ConflictID

func (b *ConflictVoters) ConflictID() (conflictID utxo.TransactionID)

ConflictID returns the ConflictID that is being tracked.

func (*ConflictVoters) DeleteVoter

func (b *ConflictVoters) DeleteVoter(voter Voter) (deleted bool)

DeleteVoter deletes a Voter from the tracked ConflictID.

func (*ConflictVoters) Has

func (b *ConflictVoters) Has(voter Voter) bool

Has returns true if the given Voter is currently supporting this Conflict.

func (*ConflictVoters) Voters

func (b *ConflictVoters) Voters() (voters *Voters)

Voters returns the set of Voters that are supporting the given ConflictID.

type ConflictWeight

type ConflictWeight struct {
	model.Storable[utxo.TransactionID, ConflictWeight, *ConflictWeight, float64] `serix:"0"`
}

ConflictWeight is a data structure that tracks the weight of a ConflictID.

func NewConflictWeight

func NewConflictWeight(conflictID utxo.TransactionID) (conflictWeight *ConflictWeight)

NewConflictWeight creates a new ConflictWeight.

func (*ConflictWeight) ConflictID

func (b *ConflictWeight) ConflictID() (conflictID utxo.TransactionID)

ConflictID returns the ConflictID that is being tracked.

func (*ConflictWeight) SetWeight

func (b *ConflictWeight) SetWeight(weight float64) bool

SetWeight sets the weight for the ConflictID and returns true if it was modified.

func (*ConflictWeight) Weight

func (b *ConflictWeight) Weight() (weight float64)

Weight returns the weight of the ConflictID.

type ConflictWeightChangedEvent

type ConflictWeightChangedEvent struct {
	ConflictID utxo.TransactionID
	Weight     float64
}

ConflictWeightChangedEvent holds information about a conflict and its updated weight.

type DBStatsResult

type DBStatsResult struct {
	StoredCount                   int
	SolidCount                    int
	BookedCount                   int
	ScheduledCount                int
	SumSolidificationReceivedTime time.Duration
	SumBookedReceivedTime         time.Duration
	SumSchedulerReceivedTime      time.Duration
	SumSchedulerBookedTime        time.Duration
	MissingBlockCount             int
}

DBStatsResult is a structure containing all the statistics retrieved by DBStats() method.

type DispatcherEvents

type DispatcherEvents struct {
	// BlockDispatched is triggered when a block is already scheduled and thus ready to be dispatched.
	BlockDispatched *event.Event[*BlockDispatchedEvent]
}

DispatcherEvents represents events happening in the Dispatcher.

type EventMock

type EventMock struct {
	mock.Mock
	// contains filtered or unexported fields
}

EventMock acts as a container for event mocks.

func NewEventMock

func NewEventMock(t *testing.T, approvalWeightManager *ApprovalWeightManager) *EventMock

NewEventMock creates a new EventMock.

func (*EventMock) AssertExpectations

func (e *EventMock) AssertExpectations(t mock.TestingT) bool

AssertExpectations asserts expectations.

func (*EventMock) BlockProcessed

func (e *EventMock) BlockProcessed(event *BlockProcessedEvent)

BlockProcessed is the mocked BlockProcessed function.

func (*EventMock) ConflictWeightChanged

func (e *EventMock) ConflictWeightChanged(event *ConflictWeightChangedEvent)

ConflictWeightChanged is the mocked ConflictWeightChanged function.

func (*EventMock) DetachAll

func (e *EventMock) DetachAll()

DetachAll detaches all event handlers.

func (*EventMock) Expect

func (e *EventMock) Expect(eventName string, arguments ...interface{})

Expect is a proxy for Mock.On() but keeping track of num of calls.

func (*EventMock) MarkerWeightChanged

func (e *EventMock) MarkerWeightChanged(event *MarkerWeightChangedEvent)

MarkerWeightChanged is the mocked MarkerWeightChanged function.

type Events

type Events struct {
	// BlockInvalid is triggered when a Block is detected to be objectively invalid.
	BlockInvalid *event.Event[*BlockInvalidEvent]

	// Error is triggered when the Mesh faces an error from which it can not recover.
	Error *event.Event[error]
}

Events represents events happening in the Mesh.

type LastBlock

type LastBlock struct {
	BlockID BlockID `serix:"0"`
	// BlockTime field is the time of the last confirmed block.
	BlockTime time.Time `serix:"1"`
	// UpdateTime field is the time when the last confirmed block was updated.
	UpdateTime time.Time
}

LastBlock is a wrapper type for the last confirmed block, consisting of BlockID, BlockTime and UpdateTime.

func (LastBlock) Bytes

func (l LastBlock) Bytes() (marshaledLastConfirmedBlock []byte)

Bytes returns a marshaled version of the LastBlock.

func (LastBlock) String

func (l LastBlock) String() string

String returns a human-readable version of the LastBlock.

type LatestConflictVotes

type LatestConflictVotes struct {
	model.Storable[Voter, LatestConflictVotes, *LatestConflictVotes, latestConflictVotesModel] `serix:"0"`
}

LatestConflictVotes represents the conflict supported from an Issuer.

func NewLatestConflictVotes

func NewLatestConflictVotes(voter Voter) (latestConflictVotes *LatestConflictVotes)

NewLatestConflictVotes creates a new LatestConflictVotes.

func (*LatestConflictVotes) Store

func (l *LatestConflictVotes) Store(vote *ConflictVote) (stored bool)

Store stores the vote for the LatestConflictVotes.

func (*LatestConflictVotes) Vote

func (l *LatestConflictVotes) Vote(conflictID utxo.TransactionID) (vote *ConflictVote, exists bool)

Vote returns the Vote for the LatestConflictVotes.

type LatestMarkerVotes

LatestMarkerVotes keeps track of the most up-to-date for a certain Voter casted on a specific Marker SequenceID. Votes can be casted on Markers (SequenceID, Index), but can arrive in any arbitrary order. Due to the nature of a Sequence, a vote casted for a certain Index clobbers votes for every lower index. Similarly, if a vote for an Index is casted and an existing vote for an higher Index exists, the operation has no effect.

func NewLatestMarkerVotes

func NewLatestMarkerVotes(sequenceID markers.SequenceID, voter Voter) (newLatestMarkerVotes *LatestMarkerVotes)

NewLatestMarkerVotes creates a new NewLatestMarkerVotes instance associated with the given details.

func (*LatestMarkerVotes) Power

func (l *LatestMarkerVotes) Power(index markers.Index) (power VotePower, exists bool)

Power returns the power of the vote for the given marker Index.

func (*LatestMarkerVotes) Store

func (l *LatestMarkerVotes) Store(index markers.Index, power VotePower) (stored bool, previousHighestIndex markers.Index)

Store stores the vote with the given marker Index and votePower. The votePower parameter is used to determine the order of the vote.

func (*LatestMarkerVotes) Voter

func (l *LatestMarkerVotes) Voter() Voter

Voter returns the Voter for the LatestMarkerVotes.

type LikedConflictMembers

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

LikedConflictMembers is a struct that holds information about which Conflict is the liked one out of a set of ConflictMembers.

type ManaRetrieverFunc

type ManaRetrieverFunc func() map[identity.ID]float64

ManaRetrieverFunc is a function type to retrieve consensus mana (e.g. via the mana plugin).

type MarkerBlockMapping

type MarkerBlockMapping struct {
	model.Storable[markers.Marker, MarkerBlockMapping, *MarkerBlockMapping, BlockID] `serix:"0"`
}

MarkerBlockMapping is a data structure that denotes a mapping from a Marker to a Block.

func NewMarkerBlockMapping

func NewMarkerBlockMapping(marker markers.Marker, blockID BlockID) *MarkerBlockMapping

NewMarkerBlockMapping is the constructor for the MarkerBlockMapping.

func (*MarkerBlockMapping) BlockID

func (m *MarkerBlockMapping) BlockID() BlockID

BlockID returns the BlockID of the Marker.

func (*MarkerBlockMapping) Marker

func (m *MarkerBlockMapping) Marker() *markers.Marker

Marker returns the Marker that is mapped to a BlockID.

type MarkerConflictAddedEvent

type MarkerConflictAddedEvent struct {
	Marker        markers.Marker
	NewConflictID utxo.TransactionID
}

type MarkerIndexConflictIDMapping

type MarkerIndexConflictIDMapping struct {
	model.Storable[markers.SequenceID, MarkerIndexConflictIDMapping, *MarkerIndexConflictIDMapping, markerIndexConflictIDMap] `serix:"0"`
}

MarkerIndexConflictIDMapping is a data structure that allows to map marker Indexes to a ConflictID.

func NewMarkerIndexConflictIDMapping

func NewMarkerIndexConflictIDMapping(sequenceID markers.SequenceID) (markerConflictMapping *MarkerIndexConflictIDMapping)

NewMarkerIndexConflictIDMapping creates a new MarkerIndexConflictIDMapping for the given SequenceID.

func (*MarkerIndexConflictIDMapping) Ceiling

func (m *MarkerIndexConflictIDMapping) Ceiling(index markers.Index) (marker markers.Index, conflictIDs utxo.TransactionIDs, exists bool)

Ceiling returns the smallest Index that is >= the given Index which has a mapped ConflictID (and a boolean value indicating if it exists).

func (*MarkerIndexConflictIDMapping) ConflictIDs

func (m *MarkerIndexConflictIDMapping) ConflictIDs(markerIndex markers.Index) (conflictIDs utxo.TransactionIDs)

ConflictIDs returns the ConflictID that is associated to the given marker Index.

func (*MarkerIndexConflictIDMapping) DeleteConflictID

func (m *MarkerIndexConflictIDMapping) DeleteConflictID(index markers.Index)

DeleteConflictID deletes a mapping between the given marker Index and the stored ConflictID.

func (*MarkerIndexConflictIDMapping) Floor

func (m *MarkerIndexConflictIDMapping) Floor(index markers.Index) (marker markers.Index, conflictIDs utxo.TransactionIDs, exists bool)

Floor returns the largest Index that is <= the given Index which has a mapped ConflictID (and a boolean value indicating if it exists).

func (*MarkerIndexConflictIDMapping) SequenceID

SequenceID returns the SequenceID that this MarkerIndexConflictIDMapping represents.

func (*MarkerIndexConflictIDMapping) SetConflictIDs

func (m *MarkerIndexConflictIDMapping) SetConflictIDs(index markers.Index, conflictIDs utxo.TransactionIDs)

SetConflictIDs creates a mapping between the given marker Index and the given ConflictID.

type MarkerWeightChangedEvent

type MarkerWeightChangedEvent struct {
	Marker markers.Marker
	Weight float64
}

MarkerWeightChangedEvent holds information about a marker and its updated weight.

type Mesh

type Mesh struct {
	Options               *Options
	Parser                *Parser
	Storage               *Storage
	Solidifier            *Solidifier
	Scheduler             *Scheduler
	RateSetter            *RateSetter
	Booker                *Booker
	ApprovalWeightManager *ApprovalWeightManager
	TimeManager           *TimeManager
	OMVConsensusManager   *OMVConsensusManager
	TipManager            *TipManager
	Requester             *Requester
	BlockFactory          *BlockFactory
	Ledger                *ledger.Ledger
	Utils                 *Utils
	WeightProvider        WeightProvider
	Events                *Events
	ConfirmationOracle    ConfirmationOracle
	OrphanageManager      *OrphanageManager
	// contains filtered or unexported fields
}

Mesh is the central data structure of the ZIPP protocol.

func New

func New(options ...Option) (mesh *Mesh)

New is the constructor for the Mesh.

func NewTestMesh

func NewTestMesh(options ...Option) *Mesh

NewTestMesh returns a Mesh instance with a testing schedulerConfig.

func (*Mesh) Bootstrapped

func (t *Mesh) Bootstrapped() bool

Bootstrapped returns a boolean value that indicates if the node has bootstrapped and the Mesh has solidified all blocks until the genesis.

func (*Mesh) Configure

func (t *Mesh) Configure(options ...Option)

Configure modifies the configuration of the Mesh.

func (*Mesh) IssuePayload

func (t *Mesh) IssuePayload(p payload.Payload, parentsCount ...int) (block *Block, err error)

IssuePayload allows to attach a payload (i.e. a Transaction) to the Mesh.

func (*Mesh) ProcessGossipBlock

func (t *Mesh) ProcessGossipBlock(blockBytes []byte, peer *peer.Peer)

ProcessGossipBlock is used to feed new Blocks from the gossip layer into the Mesh.

func (*Mesh) Prune

func (t *Mesh) Prune() (err error)

Prune resets the database and deletes all stored objects (good for testing or "node resets").

func (*Mesh) Setup

func (t *Mesh) Setup()

Setup sets up the data flow by connecting the different components (by calling their corresponding Setup method).

func (*Mesh) Shutdown

func (t *Mesh) Shutdown()

Shutdown marks the mesh as stopped, so it will not accept any new blocks (waits for all backgroundTasks to finish).

func (*Mesh) Synced

func (t *Mesh) Synced() bool

Synced returns a boolean value that indicates if the node is in sync at this moment.

type MissingBlock

type MissingBlock struct {
	model.Storable[BlockID, MissingBlock, *MissingBlock, time.Time] `serix:"0"`
}

MissingBlock represents a missing block.

func NewMissingBlock

func NewMissingBlock(blockID BlockID) *MissingBlock

NewMissingBlock creates new missing block with the specified blockID.

func (*MissingBlock) BlockID

func (m *MissingBlock) BlockID() BlockID

BlockID returns the id of the block.

func (*MissingBlock) MissingSince

func (m *MissingBlock) MissingSince() time.Time

MissingSince returns the time since when this block is missing.

type MissingBlockStoredEvent

type MissingBlockStoredEvent struct {
	BlockID BlockID
}

type MockConfirmationOracle

type MockConfirmationOracle struct {
	sync.RWMutex
}

MockConfirmationOracle is a mock of a ConfirmationOracle.

func (*MockConfirmationOracle) Events

Events mocks its interface function.

func (*MockConfirmationOracle) FirstUnconfirmedMarkerIndex

func (m *MockConfirmationOracle) FirstUnconfirmedMarkerIndex(sequenceID markers.SequenceID) (unconfirmedMarkerIndex markers.Index)

FirstUnconfirmedMarkerIndex mocks its interface function.

func (*MockConfirmationOracle) IsBlockConfirmed

func (m *MockConfirmationOracle) IsBlockConfirmed(blkID BlockID) bool

IsBlockConfirmed mocks its interface function.

func (*MockConfirmationOracle) IsConflictConfirmed

func (m *MockConfirmationOracle) IsConflictConfirmed(conflictID utxo.TransactionID) bool

IsConflictConfirmed mocks its interface function.

func (*MockConfirmationOracle) IsMarkerConfirmed

func (m *MockConfirmationOracle) IsMarkerConfirmed(markers.Marker) bool

IsMarkerConfirmed mocks its interface function.

func (*MockConfirmationOracle) IsOutputConfirmed

func (m *MockConfirmationOracle) IsOutputConfirmed(outputID utxo.OutputID) bool

IsOutputConfirmed mocks its interface function.

func (*MockConfirmationOracle) IsTransactionConfirmed

func (m *MockConfirmationOracle) IsTransactionConfirmed(transactionID utxo.TransactionID) bool

IsTransactionConfirmed mocks its interface function.

type MockWeightProvider

type MockWeightProvider struct{}

MockWeightProvider is a mock of a WeightProvider.

func (*MockWeightProvider) LoadActiveNodes

func (m *MockWeightProvider) LoadActiveNodes(loadedActiveNodes epoch.SnapshotEpochActivity)

LoadActiveNodes mocks its interface function.

func (*MockWeightProvider) Remove

func (m *MockWeightProvider) Remove(ei epoch.Index, nodeID identity.ID, count uint64) (removed bool)

Remove mocks its interface function.

func (*MockWeightProvider) Shutdown

func (m *MockWeightProvider) Shutdown()

Shutdown mocks its interface function.

func (*MockWeightProvider) SnapshotEpochActivity

func (m *MockWeightProvider) SnapshotEpochActivity(ei epoch.Index) (epochActivity epoch.SnapshotEpochActivity)

func (*MockWeightProvider) Update

func (m *MockWeightProvider) Update(ei epoch.Index, nodeID identity.ID)

Update mocks its interface function.

func (*MockWeightProvider) Weight

func (m *MockWeightProvider) Weight(block *Block) (weight, totalWeight float64)

Weight mocks its interface function.

func (*MockWeightProvider) WeightsOfRelevantVoters

func (m *MockWeightProvider) WeightsOfRelevantVoters() (weights map[identity.ID]float64, totalWeight float64)

WeightsOfRelevantVoters mocks its interface function.

type NodeBlacklistedEvent

type NodeBlacklistedEvent struct {
	NodeID identity.ID
}

type NodeIdentities

type NodeIdentities map[string]*identity.Identity

NodeIdentities defines a set of node identities mapped through an alias.

type OMVConsensusManager

type OMVConsensusManager struct {
	consensus.Mechanism
}

OMVConsensusManager is the component in charge of forming opinions about conflicts.

func NewOMVConsensusManager

func NewOMVConsensusManager(omvConsensusMechanism consensus.Mechanism) *OMVConsensusManager

NewOMVConsensusManager returns a new Mechanism.

type Opinion

type Opinion uint8

Opinion is a type that represents the Opinion of a node on a certain Conflict.

const (
	// UndefinedOpinion represents the zero value of the Opinion type.
	UndefinedOpinion Opinion = iota

	// Confirmed represents the Opinion that a given Conflict is the winning one.
	Confirmed

	// Rejected represents the Opinion that a given Conflict is the loosing one.
	Rejected
)

type Option

type Option func(*Options)

Option represents the return type of optional parameters that can be handed into the constructor of the Mesh to configure its behavior.

func ApprovalWeights

func ApprovalWeights(weightProvider WeightProvider) Option

ApprovalWeights is an Option for the Mesh that allows to define how the approval weights of Blocks is determined.

func CacheTimeProvider

func CacheTimeProvider(cacheTimeProvider *database.CacheTimeProvider) Option

CacheTimeProvider is an Option for the Mesh that allows to override hard coded cache time.

func CommitmentFunc

func CommitmentFunc(commitmentRetrieverFunc func() (*epoch.ECRecord, epoch.Index, error)) Option

CommitmentFunc is an Option for the Mesh that retrieves epoch commitments for blocks.

func GenesisNode

func GenesisNode(genesisNodeBase58 string) Option

GenesisNode is an Option for the Mesh that allows to set the GenesisNode, i.e., the node that is allowed to attach to the Genesis Block.

func GenesisTime

func GenesisTime(genesisTime time.Time) Option

GenesisTime is an Option for the Mesh that allows to set the genesis time.

func Identity

func Identity(identity *identity.LocalIdentity) Option

Identity is an Option for the Mesh that allows to specify the node identity which is used to issue Blocks.

func IncreaseMarkersIndexCallback

func IncreaseMarkersIndexCallback(callback markers.IncreaseIndexCallback) Option

IncreaseMarkersIndexCallback is an Option for the Mesh that allows to change the strategy how new Markers are assigned in the Mesh.

func RateSetterConfig

func RateSetterConfig(params RateSetterParams) Option

RateSetterConfig is an Option for the Mesh that allows to set the rate setter.

func SchedulerConfig

func SchedulerConfig(config SchedulerParams) Option

SchedulerConfig is an Option for the Mesh that allows to set the scheduler.

func StartSynced

func StartSynced(startSynced bool) Option

StartSynced is an Option for the Mesh that allows to define if the node starts as synced.

func Store

func Store(store kvstore.KVStore) Option

Store is an Option for the Mesh that allows to specify which storage layer is supposed to be used to persist data.

func SyncTimeWindow

func SyncTimeWindow(syncTimeWindow time.Duration) Option

SyncTimeWindow is an Option for the Mesh that allows to define the time window in which the node will consider itself in sync.

func TimeSinceConfirmationThreshold

func TimeSinceConfirmationThreshold(tscThreshold time.Duration) Option

TimeSinceConfirmationThreshold is an Option for the Mesh that allows to set threshold for Time Since Confirmation check.

func Width

func Width(width int) Option

Width is an Option for the Mesh that allows to change the strategy how Tips get removed.

func WithConflictDAGOptions

func WithConflictDAGOptions(conflictDAGOptions ...conflictdag.Option) Option

WithConflictDAGOptions is an Option for the Mesh that allows to set the ConflictDAG options.

type Options

type Options struct {
	Store                          kvstore.KVStore
	ConflictDAGOptions             []conflictdag.Option
	Identity                       *identity.LocalIdentity
	IncreaseMarkersIndexCallback   markers.IncreaseIndexCallback
	MeshWidth                      int
	GenesisNode                    *ed25519.PublicKey
	SchedulerParams                SchedulerParams
	RateSetterParams               RateSetterParams
	WeightProvider                 WeightProvider
	SyncTimeWindow                 time.Duration
	TimeSinceConfirmationThreshold time.Duration
	StartSynced                    bool
	CacheTimeProvider              *database.CacheTimeProvider
	CommitmentFunc                 func() (ecRecord *epoch.ECRecord, lastConfirmedEpochIndex epoch.Index, err error)
	GenesisTime                    time.Time
}

Options is a container for all configurable parameters of the Mesh.

type OrphanageManager

type OrphanageManager struct {
	Events *OrphanageManagerEvents

	sync.Mutex
	// contains filtered or unexported fields
}

OrphanageManager is a manager that tracks orphaned blocks.

func NewOrphanageManager

func NewOrphanageManager(mesh *Mesh) *OrphanageManager

NewOrphanageManager returns a new OrphanageManager.

func (*OrphanageManager) OrphanBlock

func (o *OrphanageManager) OrphanBlock(blockID BlockID, reason error)

func (*OrphanageManager) Setup

func (o *OrphanageManager) Setup()

type OrphanageManagerEvents

type OrphanageManagerEvents struct {
	BlockOrphaned       *event.Event[*BlockOrphanedEvent]
	AllChildrenOrphaned *event.Event[*Block]
}

type Parent

type Parent struct {
	ID   BlockID
	Type ParentsType
}

Parent is a parent that can be either strong or weak.

type ParentBlockIDs

type ParentBlockIDs map[ParentsType]BlockIDs

ParentBlockIDs is a map of ParentType to BlockIDs.

func NewParentBlockIDs

func NewParentBlockIDs() ParentBlockIDs

NewParentBlockIDs constructs a new ParentBlockIDs.

func (ParentBlockIDs) Add

func (p ParentBlockIDs) Add(parentType ParentsType, blockID BlockID) ParentBlockIDs

Add adds a parent to the map.

func (ParentBlockIDs) AddAll

func (p ParentBlockIDs) AddAll(parentType ParentsType, blockIDs BlockIDs) ParentBlockIDs

AddAll adds a collection of parents to the map.

func (ParentBlockIDs) AddStrong

func (p ParentBlockIDs) AddStrong(blockID BlockID) ParentBlockIDs

AddStrong adds a strong parent to the map.

func (ParentBlockIDs) Clone

func (p ParentBlockIDs) Clone() ParentBlockIDs

Clone returns a copy of map.

func (ParentBlockIDs) IsEmpty

func (p ParentBlockIDs) IsEmpty() bool

IsEmpty returns true if the ParentBlockIDs are empty.

type ParentsType

type ParentsType uint8

ParentsType is a type that defines the type of the parent.

const (
	// UndefinedParentType is the undefined parent.
	UndefinedParentType ParentsType = iota
	// StrongParentType is the ParentsType for a strong parent.
	StrongParentType
	// WeakParentType is the ParentsType for a weak parent.
	WeakParentType
	// ShallowLikeParentType is the ParentsType for the shallow like parent.
	ShallowLikeParentType
)

func (ParentsType) String

func (bp ParentsType) String() string

String returns string representation of ParentsType.

type Parser

type Parser struct {
	Events *ParserEvents
	// contains filtered or unexported fields
}

Parser parses blocks and bytes and emits corresponding events for parsed and rejected blocks.

func NewParser

func NewParser() (result *Parser)

NewParser creates a new Block parser.

func (*Parser) AddBlockFilter

func (p *Parser) AddBlockFilter(filter BlockFilter)

AddBlockFilter adds a new block filter to the parser.

func (*Parser) AddBytesFilter

func (p *Parser) AddBytesFilter(filter BytesFilter)

AddBytesFilter adds the given bytes filter to the parser.

func (*Parser) Parse

func (p *Parser) Parse(blockBytes []byte, peer *peer.Peer)

Parse parses the given block bytes.

func (*Parser) Setup

func (p *Parser) Setup()

Setup defines the flow of the parser.

func (*Parser) Shutdown

func (p *Parser) Shutdown()

Shutdown closes all the block filters.

type ParserEvents

type ParserEvents struct {
	// Fired when a block was parsed.
	BlockParsed *event.Event[*BlockParsedEvent]

	// Fired when submitted bytes are rejected by a filter.
	BytesRejected *event.Event[*BytesRejectedEvent]

	// Fired when a block got rejected by a filter.
	BlockRejected *event.Event[*BlockRejectedEvent]
}

ParserEvents represents events happening in the Parser.

type PowFilter

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

PowFilter is a block bytes filter validating the PoW nonce.

func NewPowFilter

func NewPowFilter(worker *pow.Worker, difficulty int) *PowFilter

NewPowFilter creates a new PoW bytes filter.

func (*PowFilter) Filter

func (f *PowFilter) Filter(blkBytes []byte, p *peer.Peer)

Filter checks whether the given bytes pass the PoW validation and calls the corresponding callback.

func (*PowFilter) OnAccept

func (f *PowFilter) OnAccept(callback func([]byte, *peer.Peer))

OnAccept registers the given callback as the acceptance function of the filter.

func (*PowFilter) OnReject

func (f *PowFilter) OnReject(callback func([]byte, error, *peer.Peer))

OnReject registers the given callback as the rejection function of the filter.

type PrePostStepTuple

type PrePostStepTuple struct {
	Pre  TestStep
	Post TestStep
}

PrePostStepTuple is a tuple of TestStep(s) called before and after the actual test step is called.

type QueueElement

type QueueElement struct {
	// Value represents the value of the queued element.
	Value BlockID

	// Key represents the time of the element to be used as a key.
	Key time.Time
	// contains filtered or unexported fields
}

QueueElement is an element in the TimedQueue. It

type RateSetter

type RateSetter struct {
	Events *RateSetterEvents
	// contains filtered or unexported fields
}

RateSetter is a Mesh component that takes care of congestion control of local node.

func NewRateSetter

func NewRateSetter(mesh *Mesh) *RateSetter

NewRateSetter returns a new RateSetter.

func (*RateSetter) Estimate

func (r *RateSetter) Estimate() time.Duration

Estimate estimates the issuing time of new block.

func (*RateSetter) Issue

func (r *RateSetter) Issue(block *Block) error

Issue submits a block to the local issuing queue.

func (*RateSetter) Rate

func (r *RateSetter) Rate() float64

Rate returns the rate of the rate setter.

func (*RateSetter) Setup

func (r *RateSetter) Setup()

Setup sets up the behavior of the component by making it attach to the relevant events of the other components.

func (*RateSetter) Shutdown

func (r *RateSetter) Shutdown()

Shutdown shuts down the RateSetter.

func (*RateSetter) Size

func (r *RateSetter) Size() int

Size returns the size of the issuing queue.

type RateSetterEvents

type RateSetterEvents struct {
	BlockDiscarded *event.Event[*BlockDiscardedEvent]
	BlockIssued    *event.Event[*BlockConstructedEvent]
	Error          *event.Event[error]
}

RateSetterEvents represents events happening in the rate setter.

type RateSetterParams

type RateSetterParams struct {
	Enabled          bool
	Initial          float64
	RateSettingPause time.Duration
}

RateSetterParams represents the parameters for RateSetter.

type RecentlySeenBytesFilter

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

RecentlySeenBytesFilter filters so that bytes which were recently seen don't pass the filter.

func NewRecentlySeenBytesFilter

func NewRecentlySeenBytesFilter() *RecentlySeenBytesFilter

NewRecentlySeenBytesFilter creates a new recently seen bytes filter.

func (*RecentlySeenBytesFilter) Filter

func (r *RecentlySeenBytesFilter) Filter(bytes []byte, peer *peer.Peer)

Filter filters up on the given bytes and peer and calls the acceptance callback if the input passes or the rejection callback if the input is rejected.

func (*RecentlySeenBytesFilter) OnAccept

func (r *RecentlySeenBytesFilter) OnAccept(callback func(bytes []byte, peer *peer.Peer))

OnAccept registers the given callback as the acceptance function of the filter.

func (*RecentlySeenBytesFilter) OnReject

func (r *RecentlySeenBytesFilter) OnReject(callback func(bytes []byte, err error, peer *peer.Peer))

OnReject registers the given callback as the rejection function of the filter.

type ReferenceProvider

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

ReferenceProvider is a component that takes care of creating the correct references when selecting tips.

func NewReferenceProvider

func NewReferenceProvider(mesh *Mesh) (newInstance *ReferenceProvider)

NewReferenceProvider creates a new ReferenceProvider instance.

func (*ReferenceProvider) References

func (r *ReferenceProvider) References(payload payload.Payload, strongParents BlockIDs, issuingTime time.Time) (references ParentBlockIDs, err error)

References is an implementation of ReferencesFunc.

func (*ReferenceProvider) ReferencesToMissingConflicts

func (r *ReferenceProvider) ReferencesToMissingConflicts(issuingTime time.Time, amount int) (blockIDs BlockIDs)

type ReferencesFunc

type ReferencesFunc func(payload payload.Payload, strongParents BlockIDs, issuingTime time.Time) (references ParentBlockIDs, err error)

ReferencesFunc is a function type that returns like references a given set of parents of a Block.

type RequestFailedEvent

type RequestFailedEvent struct {
	BlockID BlockID
}

type RequestIssuedEvent

type RequestIssuedEvent struct {
	BlockID BlockID
}

type RequestStartedEvent

type RequestStartedEvent struct {
	BlockID BlockID
}

type RequestStoppedEvent

type RequestStoppedEvent struct {
	BlockID BlockID
}

type Requester

type Requester struct {
	Events *RequesterEvents
	// contains filtered or unexported fields
}

Requester takes care of requesting blocks.

func NewRequester

func NewRequester(mesh *Mesh, optionalOptions ...RequesterOption) *Requester

NewRequester creates a new block requester.

func (*Requester) RequestQueueSize

func (r *Requester) RequestQueueSize() int

RequestQueueSize returns the number of scheduled block requests.

func (*Requester) Setup

func (r *Requester) Setup()

Setup sets up the behavior of the component by making it attach to the relevant events of other components.

func (*Requester) Shutdown

func (r *Requester) Shutdown()

Shutdown shuts down the Requester.

func (*Requester) StartRequest

func (r *Requester) StartRequest(id BlockID)

StartRequest initiates a regular triggering of the StartRequest event until it has been stopped using StopRequest.

func (*Requester) StopRequest

func (r *Requester) StopRequest(id BlockID)

StopRequest stops requests for the given block to further happen.

type RequesterEvents

type RequesterEvents struct {
	// RequestIssued is an event that is triggered when the requester wants to request the given Block from its
	// neighbors.
	RequestIssued *event.Event[*RequestIssuedEvent]

	// RequestStarted is an event that is triggered when a new request is started.
	RequestStarted *event.Event[*RequestStartedEvent]

	// RequestStopped is an event that is triggered when a request is stopped.
	RequestStopped *event.Event[*RequestStoppedEvent]

	// RequestFailed is an event that is triggered when a request is stopped after too many attempts.
	RequestFailed *event.Event[*RequestFailedEvent]
}

RequesterEvents represents events happening on a block requester.

type RequesterOption

type RequesterOption func(*RequesterOptions)

RequesterOption is a function which inits an option.

func MaxRequestThreshold

func MaxRequestThreshold(maxRequestThreshold int) RequesterOption

MaxRequestThreshold creates an option which defines how often the Requester should try to request blocks before canceling the request.

func RetryInterval

func RetryInterval(interval time.Duration) RequesterOption

RetryInterval creates an option which sets the retry interval to the given value.

func RetryJitter

func RetryJitter(retryJitter time.Duration) RequesterOption

RetryJitter creates an option which sets the retry jitter to the given value.

type RequesterOptions

type RequesterOptions struct {
	// RetryInterval represents an option which defines in which intervals the Requester will try to ask for missing
	// blocks.
	RetryInterval time.Duration

	// RetryJitter defines how much the RetryInterval should be randomized, so that the nodes don't always send blocks
	// at exactly the same interval.
	RetryJitter time.Duration

	// MaxRequestThreshold represents an option which defines how often the Requester should try to request blocks
	// before canceling the request
	MaxRequestThreshold int
}

RequesterOptions holds options for a block requester.

func (RequesterOptions) Apply

func (r RequesterOptions) Apply(optionalOptions ...RequesterOption) (updatedOptions RequesterOptions)

Apply applies the optional Options to the RequesterOptions.

type Scheduler

type Scheduler struct {
	Events *SchedulerEvents
	// contains filtered or unexported fields
}

Scheduler is a Mesh component that takes care of scheduling the blocks that shall be booked.

func NewScheduler

func NewScheduler(mesh *Mesh) *Scheduler

NewScheduler returns a new Scheduler.

func (*Scheduler) AccessManaCache

func (s *Scheduler) AccessManaCache() *schedulerutils.AccessManaCache

AccessManaCache returns the object which caches access mana values.

func (*Scheduler) BufferSize

func (s *Scheduler) BufferSize() int

BufferSize returns the size of the buffer.

func (*Scheduler) GetDeficit

func (s *Scheduler) GetDeficit(nodeID identity.ID) *big.Rat

func (*Scheduler) GetManaFromCache

func (s *Scheduler) GetManaFromCache(nodeID identity.ID) int64

GetManaFromCache allows you to get the cached mana for a node ID. This is exposed for analytics purposes.

func (*Scheduler) MaxBufferSize

func (s *Scheduler) MaxBufferSize() int

MaxBufferSize returns the max size of the buffer.

func (*Scheduler) NodeQueueSize

func (s *Scheduler) NodeQueueSize(nodeID identity.ID) int

NodeQueueSize returns the size of the nodeIDs queue.

func (*Scheduler) NodeQueueSizes

func (s *Scheduler) NodeQueueSizes() map[identity.ID]int

NodeQueueSizes returns the size for each node queue.

func (*Scheduler) Quanta

func (s *Scheduler) Quanta(nodeID identity.ID) *big.Rat

func (*Scheduler) Rate

func (s *Scheduler) Rate() time.Duration

Rate gets the rate of the scheduler.

func (*Scheduler) Ready

func (s *Scheduler) Ready(blockID BlockID) (err error)

Ready marks a previously submitted block as ready to be scheduled. If Ready is called without a previous Submit, it has no effect.

func (*Scheduler) ReadyBlocksCount

func (s *Scheduler) ReadyBlocksCount() int

ReadyBlocksCount returns the size buffer.

func (*Scheduler) Running

func (s *Scheduler) Running() bool

Running returns true if the scheduler has started.

func (*Scheduler) SetRate

func (s *Scheduler) SetRate(rate time.Duration)

SetRate sets the rate of the scheduler.

func (*Scheduler) Setup

func (s *Scheduler) Setup()

Setup sets up the behavior of the component by making it attach to the relevant events of the other components.

func (*Scheduler) Shutdown

func (s *Scheduler) Shutdown()

Shutdown shuts down the Scheduler. Shutdown blocks until the scheduler has been shutdown successfully.

func (*Scheduler) Start

func (s *Scheduler) Start()

Start starts the scheduler.

func (*Scheduler) Submit

func (s *Scheduler) Submit(blockID BlockID) (err error)

Submit submits a block to be considered by the scheduler. This transactions will be included in all the control metrics, but it will never be scheduled until Ready(blockID) has been called.

func (*Scheduler) SubmitAndReady

func (s *Scheduler) SubmitAndReady(block *Block) (err error)

SubmitAndReady submits the block to the scheduler and marks it ready right away.

func (*Scheduler) TotalBlocksCount

func (s *Scheduler) TotalBlocksCount() int

TotalBlocksCount returns the size buffer.

func (*Scheduler) Unsubmit

func (s *Scheduler) Unsubmit(blockID BlockID) (err error)

Unsubmit removes a block from the submitted blocks. If that block is already marked as ready, Unsubmit has no effect.

type SchedulerEvents

type SchedulerEvents struct {
	// BlockScheduled is triggered when a block is ready to be scheduled.
	BlockScheduled *event.Event[*BlockScheduledEvent]
	// BlockDiscarded is triggered when a block is removed from the longest mana-scaled queue when the buffer is full.
	BlockDiscarded *event.Event[*BlockDiscardedEvent]
	// BlockSkipped is triggered when a block is confirmed before it's scheduled, and is skipped by the scheduler.
	BlockSkipped    *event.Event[*BlockSkippedEvent]
	NodeBlacklisted *event.Event[*NodeBlacklistedEvent]
	Error           *event.Event[error]
}

SchedulerEvents represents events happening in the Scheduler.

func NewSchedulerEvents

func NewSchedulerEvents() (new *SchedulerEvents)

type SchedulerParams

type SchedulerParams struct {
	MaxBufferSize                   int
	TotalSupply                     int
	Rate                            time.Duration
	TotalAccessManaRetrieveFunc     func() float64
	AccessManaMapRetrieverFunc      func() map[identity.ID]float64
	ConfirmedBlockScheduleThreshold time.Duration
}

SchedulerParams defines the scheduler config parameters.

type SimpleMockOnMeshVoting

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

SimpleMockOnMeshVoting is mock of OMV mechanism.

func (*SimpleMockOnMeshVoting) ConflictLiked

func (o *SimpleMockOnMeshVoting) ConflictLiked(conflictID utxo.TransactionID) (conflictLiked bool)

ConflictLiked returns whether the conflict is the winner across all conflict sets (it is in the liked reality).

func (*SimpleMockOnMeshVoting) LikedConflictMember

func (o *SimpleMockOnMeshVoting) LikedConflictMember(conflictID utxo.TransactionID) (likedConflictID utxo.TransactionID, conflictMembers utxo.TransactionIDs)

LikedConflictMember returns conflicts that are liked instead of a disliked conflict as predefined.

type Solidifier

type Solidifier struct {
	// Events contains the Solidifier related events.
	Events *SolidifierEvents
	// contains filtered or unexported fields
}

Solidifier is the Mesh's component that solidifies blocks.

func NewSolidifier

func NewSolidifier(mesh *Mesh) (solidifier *Solidifier)

NewSolidifier is the constructor of the Solidifier.

func (*Solidifier) RetrieveMissingBlock

func (s *Solidifier) RetrieveMissingBlock(blockID BlockID) (blockWasMissing bool)

RetrieveMissingBlock checks if the block is missing and triggers the corresponding events to request it. It returns true if the block has been missing.

func (*Solidifier) Setup

func (s *Solidifier) Setup()

Setup sets up the behavior of the component by making it attach to the relevant events of the other components.

func (*Solidifier) Solidify

func (s *Solidifier) Solidify(blockID BlockID)

Solidify solidifies the given Block.

type SolidifierEvents

type SolidifierEvents struct {
	// BlockSolid is triggered when a block becomes solid, i.e. its past cone is known and solid.
	BlockSolid *event.Event[*BlockSolidEvent]

	// BlockMissing is triggered when a block references an unknown parent Block.
	BlockMissing *event.Event[*BlockMissingEvent]
}

SolidifierEvents represents events happening in the Solidifier.

type Storage

type Storage struct {
	Events *StorageEvents
	// contains filtered or unexported fields
}

Storage represents the storage of blocks.

func NewStorage

func NewStorage(mesh *Mesh) (storage *Storage)

NewStorage creates a new Storage.

func (*Storage) AllLatestMarkerVotes

func (s *Storage) AllLatestMarkerVotes(sequenceID markers.SequenceID) (cachedLatestMarkerVotesByVoter CachedLatestMarkerVotesByVoter)

AllLatestMarkerVotes retrieves all LatestMarkerVotes for the named Sequence.

func (*Storage) AttachmentBlockIDs

func (s *Storage) AttachmentBlockIDs(transactionID utxo.TransactionID) (blockIDs BlockIDs)

AttachmentBlockIDs returns the blockIDs of the transaction in attachmentStorage.

func (*Storage) Attachments

func (s *Storage) Attachments(transactionID utxo.TransactionID) (cachedAttachments objectstorage.CachedObjects[*Attachment])

Attachments retrieves the attachment of a transaction in attachmentStorage.

func (*Storage) Block

func (s *Storage) Block(blockID BlockID) *objectstorage.CachedObject[*Block]

Block retrieves a block from the block store.

func (*Storage) BlockMetadata

func (s *Storage) BlockMetadata(blockID BlockID, computeIfAbsentCallback ...func() *BlockMetadata) *objectstorage.CachedObject[*BlockMetadata]

BlockMetadata retrieves the BlockMetadata with the given BlockID.

func (*Storage) Children

func (s *Storage) Children(blockID BlockID, optionalChildType ...ChildType) (cachedChildren objectstorage.CachedObjects[*Child])

Children retrieves the Children of a Block from the object storage. It is possible to provide an optional ChildType to only return the corresponding Children.

func (*Storage) ConflictVoters

func (s *Storage) ConflictVoters(conflictID utxo.TransactionID, computeIfAbsentCallback ...func(conflictID utxo.TransactionID) *ConflictVoters) *objectstorage.CachedObject[*ConflictVoters]

ConflictVoters retrieves the ConflictVoters with the given ledger.ConflictID.

func (*Storage) ConflictWeight

func (s *Storage) ConflictWeight(conflictID utxo.TransactionID, computeIfAbsentCallback ...func(conflictID utxo.TransactionID) *ConflictWeight) *objectstorage.CachedObject[*ConflictWeight]

ConflictWeight retrieves the ConflictWeight with the given ConflictID.

func (*Storage) DBStats

func (s *Storage) DBStats() (res DBStatsResult)

DBStats returns the number of solid blocks and total number of blocks in the database (blockMetadataStorage, that should contain the blocks as blockStorage), the number of blocks in missingBlockStorage, furthermore the average time it takes to solidify blocks.

func (*Storage) DeleteBlock

func (s *Storage) DeleteBlock(blockID BlockID)

DeleteBlock deletes a block and its association to parents by un-marking the given block as an child.

func (*Storage) DeleteMarkerBlockMapping

func (s *Storage) DeleteMarkerBlockMapping(conflictID utxo.TransactionID, blockID BlockID)

DeleteMarkerBlockMapping deleted a MarkerBlockMapping in the underlying object storage.

func (*Storage) DeleteMissingBlock

func (s *Storage) DeleteMissingBlock(blockID BlockID)

DeleteMissingBlock deletes a block from the missingBlockStorage.

func (*Storage) IsTransactionAttachedByBlock

func (s *Storage) IsTransactionAttachedByBlock(transactionID utxo.TransactionID, blockID BlockID) (attached bool)

IsTransactionAttachedByBlock checks whether Transaction with transactionID is attached by Block with blockID.

func (*Storage) LatestConflictVotes

func (s *Storage) LatestConflictVotes(voter Voter, computeIfAbsentCallback ...func(voter Voter) *LatestConflictVotes) *objectstorage.CachedObject[*LatestConflictVotes]

LatestConflictVotes retrieves the LatestConflictVotes of the given Voter.

func (*Storage) LatestMarkerVotes

func (s *Storage) LatestMarkerVotes(sequenceID markers.SequenceID, voter Voter, computeIfAbsentCallback ...func(sequenceID markers.SequenceID, voter Voter) *LatestMarkerVotes) *objectstorage.CachedObject[*LatestMarkerVotes]

LatestMarkerVotes retrieves the LatestMarkerVotes of the given voter for the named Sequence.

func (*Storage) MarkerBlockMapping

func (s *Storage) MarkerBlockMapping(marker markers.Marker) (cachedMarkerBlockMappings *objectstorage.CachedObject[*MarkerBlockMapping])

MarkerBlockMapping retrieves the MarkerBlockMapping associated with the given details.

func (*Storage) MarkerBlockMappings

func (s *Storage) MarkerBlockMappings(sequenceID markers.SequenceID) (cachedMarkerBlockMappings objectstorage.CachedObjects[*MarkerBlockMapping])

MarkerBlockMappings retrieves the MarkerBlockMappings of a Sequence in the object storage.

func (*Storage) MarkerIndexConflictIDMapping

func (s *Storage) MarkerIndexConflictIDMapping(sequenceID markers.SequenceID, computeIfAbsentCallback ...func(sequenceID markers.SequenceID) *MarkerIndexConflictIDMapping) *objectstorage.CachedObject[*MarkerIndexConflictIDMapping]

MarkerIndexConflictIDMapping retrieves the MarkerIndexConflictIDMapping for the given SequenceID. It accepts an optional computeIfAbsent callback that can be used to dynamically create a MarkerIndexConflictIDMapping if it doesn't exist, yet.

func (*Storage) MissingBlocks

func (s *Storage) MissingBlocks() (ids []BlockID)

MissingBlocks return the ids of blocks in missingBlockStorage

func (*Storage) Prune

func (s *Storage) Prune() error

Prune resets the database and deletes all objects (good for testing or "node resets").

func (*Storage) RetrieveAllTips

func (s *Storage) RetrieveAllTips() (tips []BlockID)

RetrieveAllTips returns the tips (i.e., solid blocks that are not part of the children list). It iterates over the blockMetadataStorage, thus only use this method if necessary. TODO: improve this function.

func (*Storage) Setup

func (s *Storage) Setup()

Setup sets up the behavior of the component by making it attach to the relevant events of other components.

func (*Storage) Shutdown

func (s *Storage) Shutdown()

Shutdown marks the mesh as stopped, so it will not accept any new blocks (waits for all backgroundTasks to finish).

func (*Storage) StoreAttachment

func (s *Storage) StoreAttachment(transactionID utxo.TransactionID, blockID BlockID) (cachedAttachment *objectstorage.CachedObject[*Attachment], stored bool)

StoreAttachment stores a new attachment if not already stored.

func (*Storage) StoreBlock

func (s *Storage) StoreBlock(block *Block)

StoreBlock stores a new block to the block store.

func (*Storage) StoreMarkerBlockMapping

func (s *Storage) StoreMarkerBlockMapping(markerBlockMapping *MarkerBlockMapping)

StoreMarkerBlockMapping stores a MarkerBlockMapping in the underlying object storage.

func (*Storage) StoreMissingBlock

func (s *Storage) StoreMissingBlock(missingBlock *MissingBlock) (cachedMissingBlock *objectstorage.CachedObject[*MissingBlock], stored bool)

StoreMissingBlock stores a new MissingBlock entry in the object storage.

type StorageEvents

type StorageEvents struct {
	// Fired when a block has been stored.
	BlockStored *event.Event[*BlockStoredEvent]

	// Fired when a block was removed from storage.
	BlockRemoved *event.Event[*BlockRemovedEvent]

	// Fired when a block which was previously marked as missing was received.
	MissingBlockStored *event.Event[*MissingBlockStoredEvent]
}

StorageEvents represents events happening on the block store.

type SyncChangedEvent

type SyncChangedEvent struct {
	Synced bool
}

SyncChangedEvent represents a sync changed event.

type TestScenario

type TestScenario struct {
	Steps    []TestStep
	PostStep TestStep
	Mesh     *Mesh

	TestFramework *BlockTestFramework
	// contains filtered or unexported fields
}

TestScenario is a sequence of steps applied onto test scenario.

func ProcessBlockScenario

func ProcessBlockScenario(t *testing.T, options ...Option) *TestScenario

ProcessBlockScenario the approval weight and voter adjustments.

func ProcessBlockScenario2

func ProcessBlockScenario2(t *testing.T, options ...Option) *TestScenario

ProcessBlockScenario2 creates a scenario useful to validate strong / weak propagation paths.

func (*TestScenario) Cleanup

func (s *TestScenario) Cleanup(t *testing.T) error

Cleanup cleans up the scenario.

func (*TestScenario) HasNext

func (s *TestScenario) HasNext() bool

HasNext returns whether the scenario has a next step.

func (*TestScenario) Next

func (s *TestScenario) Next(prePostStepTuple *PrePostStepTuple)

Next returns the next step or panics if non is available.

func (*TestScenario) Setup

func (s *TestScenario) Setup(t *testing.T) error

Setup sets up the scenario.

type TestStep

type TestStep func(t *testing.T, testFramework *BlockTestFramework, testEventMock *EventMock, nodes NodeIdentities)

TestStep defines a test scenario step.

type TimeManager

type TimeManager struct {
	Events *TimeManagerEvents
	// contains filtered or unexported fields
}

TimeManager is a Mesh component that keeps track of the MeshTime. The MeshTime can be seen as a clock for the entire network as it tracks the time of the last confirmed block. Comparing the issuing time of the last confirmed block to the node's current wall clock time then yields a reasonable assessment of how much in sync the node is.

func NewTimeManager

func NewTimeManager(mesh *Mesh) *TimeManager

NewTimeManager is the constructor for TimeManager.

func (*TimeManager) ATT

func (t *TimeManager) ATT() time.Time

ATT returns the Acceptance Mesh Time, i.e., the issuing time of the last accepted block.

func (*TimeManager) ActivityTime

func (t *TimeManager) ActivityTime() time.Time

ActivityTime return the time used for defining nodes' activity window.

func (*TimeManager) Bootstrapped

func (t *TimeManager) Bootstrapped() bool

Bootstrapped returns whether the node has bootstrapped based on the difference between CTT and the current wall time which can be configured via SyncTimeWindow. When the node becomes bootstrapped and this method returns true, it can't return false after that.

func (*TimeManager) CTT

func (t *TimeManager) CTT() time.Time

CTT returns the confirmed mesh time, i.e. the issuing time of the last confirmed block. For now, it's just a stub, it actually returns ATT.

func (*TimeManager) LastAcceptedBlock

func (t *TimeManager) LastAcceptedBlock() LastBlock

LastAcceptedBlock returns the last confirmed block.

func (*TimeManager) LastConfirmedBlock

func (t *TimeManager) LastConfirmedBlock() LastBlock

LastConfirmedBlock returns the last confirmed block.

func (*TimeManager) RATT

func (t *TimeManager) RATT() time.Time

RATT return relative acceptance mesh time, i.e., ATT + time since last update of ATT.

func (*TimeManager) RCTT

func (t *TimeManager) RCTT() time.Time

RCTT return relative acceptance mesh time, i.e., CTT + time since last update of CTT. For now, it's just a stub, it actually returns RATT.

func (*TimeManager) Setup

func (t *TimeManager) Setup()

Setup sets up the behavior of the component by making it attach to the relevant events of other components.

func (*TimeManager) Shutdown

func (t *TimeManager) Shutdown()

Shutdown shuts down the TimeManager and persists its state.

func (*TimeManager) Start

func (t *TimeManager) Start()

Start starts the TimeManager.

func (*TimeManager) Synced

func (t *TimeManager) Synced() bool

Synced returns whether the node is in sync based on the difference between CTT and the current wall time which can be configured via SyncTimeWindow.

type TimeManagerEvents

type TimeManagerEvents struct {
	// Fired when the nodes sync status changes.
	SyncChanged           *event.Event[*SyncChangedEvent]
	Bootstrapped          *event.Event[*BootstrappedEvent]
	AcceptanceTimeUpdated *event.Event[*TimeUpdate]
	ConfirmedTimeUpdated  *event.Event[*TimeUpdate]
}

TimeManagerEvents represents events happening in the TimeManager.

type TimeRetrieverFunc

type TimeRetrieverFunc func() time.Time

TimeRetrieverFunc is a function type to retrieve the time.

type TimeUpdate

type TimeUpdate struct {
	// BlockID is the ID of the block that caused the time update.
	BlockID BlockID
	// ATT is the new Acceptance Mesh Time.
	ATT time.Time
	// UpdateTime is the wall clock time when the update has occurred.
	UpdateTime time.Time
}

TimeUpdate represents an update in Mesh Time.

type TimedHeap

type TimedHeap []*QueueElement

TimedHeap defines a heap based on times.

func (TimedHeap) Len

func (h TimedHeap) Len() int

Len is the number of elements in the collection.

func (TimedHeap) Less

func (h TimedHeap) Less(i, j int) bool

Less reports whether the element with index i should sort before the element with index j.

func (*TimedHeap) Pop

func (h *TimedHeap) Pop() interface{}

Pop removes and returns the last element of the heap.

func (*TimedHeap) Push

func (h *TimedHeap) Push(x interface{})

Push adds x as the last element to the heap.

func (TimedHeap) Swap

func (h TimedHeap) Swap(i, j int)

Swap swaps the elements with indexes i and j.

type TipEvent

type TipEvent struct {
	// BlockID of the added/removed tip.
	BlockID BlockID
}

TipEvent holds the information provided by the TipEvent event that gets triggered when a block gets added or removed as tip.

type TipManager

type TipManager struct {
	Events *TipManagerEvents
	// contains filtered or unexported fields
}

TipManager manages a map of tips and emits events for their removal and addition.

func NewTipManager

func NewTipManager(mesh *Mesh, tips ...BlockID) *TipManager

NewTipManager creates a new tip-selector.

func (*TipManager) AddTip

func (t *TipManager) AddTip(block *Block)

AddTip adds the block to the tip pool if its issuing time is within the tipLifeGracePeriod. Parents of a block that are currently tip lose the tip status and are removed.

func (*TipManager) AllTips

func (t *TipManager) AllTips() BlockIDs

AllTips returns a list of all tips that are stored in the TipManger.

func (*TipManager) Setup

func (t *TipManager) Setup()

Setup sets up the behavior of the component by making it attach to the relevant events of other components.

func (*TipManager) Shutdown

func (t *TipManager) Shutdown()

Shutdown stops the TipManager.

func (*TipManager) TipCount

func (t *TipManager) TipCount() int

TipCount the amount of strong tips.

func (*TipManager) Tips

func (t *TipManager) Tips(p payload.Payload, countParents int) (parents BlockIDs)

Tips returns count number of tips, maximum MaxParentsCount.

type TipManagerEvents

type TipManagerEvents struct {
	// Fired when a tip is added.
	TipAdded *event.Event[*TipEvent]

	// Fired when a tip is removed.
	TipRemoved *event.Event[*TipEvent]
}

TipManagerEvents represents events happening on the TipManager.

type TipSelector

type TipSelector interface {
	Tips(p payload.Payload, countParents int) (parents BlockIDs)
}

A TipSelector selects two tips, parent2 and parent1, for a new block to attach to.

type TipSelectorFunc

type TipSelectorFunc func(p payload.Payload, countParents int) (parents BlockIDs)

The TipSelectorFunc type is an adapter to allow the use of ordinary functions as tip selectors.

func (TipSelectorFunc) Tips

func (f TipSelectorFunc) Tips(p payload.Payload, countParents int) (parents BlockIDs)

Tips calls f().

type TipsCleaner

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

func (*TipsCleaner) Add

func (t *TipsCleaner) Add(key time.Time, value BlockID)

Add adds a new element to the heap.

func (*TipsCleaner) RemoveBefore

func (t *TipsCleaner) RemoveBefore(minAllowedTime time.Time)

RemoveBefore removes the elements with key time earlier than the given time.

type TipsConflictTracker

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

func NewTipsConflictTracker

func NewTipsConflictTracker(mesh *Mesh) *TipsConflictTracker

func (*TipsConflictTracker) AddTip

func (c *TipsConflictTracker) AddTip(blockID BlockID)

func (*TipsConflictTracker) MissingConflicts

func (c *TipsConflictTracker) MissingConflicts(amount int) (missingConflicts utxo.TransactionIDs)

func (*TipsConflictTracker) RemoveTip

func (c *TipsConflictTracker) RemoveTip(blockID BlockID)

func (*TipsConflictTracker) Setup

func (c *TipsConflictTracker) Setup()

type TransactionFilter

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

TransactionFilter filters blocks based on their timestamps and transaction timestamp.

func NewTransactionFilter

func NewTransactionFilter() *TransactionFilter

NewTransactionFilter creates a new transaction filter.

func (*TransactionFilter) Close

func (f *TransactionFilter) Close() error

Close closes the filter.

func (*TransactionFilter) Filter

func (f *TransactionFilter) Filter(blk *Block, peer *peer.Peer)

Filter compares the timestamps between the block, and it's transaction payload and calls the corresponding callback.

func (*TransactionFilter) OnAccept

func (f *TransactionFilter) OnAccept(callback func(blk *Block, peer *peer.Peer))

OnAccept registers the given callback as the acceptance function of the filter.

func (*TransactionFilter) OnReject

func (f *TransactionFilter) OnReject(callback func(blk *Block, err error, peer *peer.Peer))

OnReject registers the given callback as the rejection function of the filter.

type Utils

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

Utils is a Mesh component that bundles methods that can be used to interact with the Mesh, that do not belong into public API.

func NewUtils

func NewUtils(mesh *Mesh) (utils *Utils)

NewUtils is the constructor of the Utils component.

func (*Utils) AllConflictsLiked

func (u *Utils) AllConflictsLiked(conflictIDs *set.AdvancedSet[utxo.TransactionID]) bool

AllConflictsLiked returns true if all the passed conflicts are liked.

func (*Utils) ApprovingBlockIDs

func (u *Utils) ApprovingBlockIDs(blockID BlockID, optionalChildType ...ChildType) (approvingBlockIDs BlockIDs)

ApprovingBlockIDs returns the BlockIDs that approve a given Block. It accepts an optional ChildType to filter the Children.

func (*Utils) ComputeIfTransaction

func (u *Utils) ComputeIfTransaction(blockID BlockID, compute func(utxo.TransactionID)) (computed bool)

ComputeIfTransaction computes the given callback if the given blockID contains a transaction.

func (*Utils) ConfirmedConsumer

func (u *Utils) ConfirmedConsumer(outputID utxo.OutputID) (consumerID utxo.TransactionID)

ConfirmedConsumer returns the confirmed transactionID consuming the given outputID.

func (*Utils) FirstAttachment

func (u *Utils) FirstAttachment(transactionID utxo.TransactionID) (oldestAttachmentTime time.Time, oldestAttachmentBlockID BlockID, err error)

FirstAttachment returns the BlockID and timestamp of the first (oldest) attachment of a given transaction.

func (*Utils) WalkBlock

func (u *Utils) WalkBlock(callback func(block *Block, walker *walker.Walker[BlockID]), entryPoints BlockIDs, revisitElements ...bool)

WalkBlock is a generic Mesh walker that executes a custom callback for every visited Block, starting from the given entry points. It accepts an optional boolean parameter which can be set to true if a Block should be visited more than once following different paths. The callback receives a Walker object as the last parameter which can be used to control the behavior of the walk similar to how a "Context" is used in some parts of the stdlib.

func (*Utils) WalkBlockAndMetadata

func (u *Utils) WalkBlockAndMetadata(callback func(block *Block, blockMetadata *BlockMetadata, walker *walker.Walker[BlockID]), entryPoints BlockIDs, revisitElements ...bool)

WalkBlockAndMetadata is a generic Mesh walker that executes a custom callback for every visited Block and BlockMetadata, starting from the given entry points. It accepts an optional boolean parameter which can be set to true if a Block should be visited more than once following different paths. The callback receives a Walker object as the last parameter which can be used to control the behavior of the walk similar to how a "Context" is used in some parts of the stdlib.

func (*Utils) WalkBlockID

func (u *Utils) WalkBlockID(callback func(blockID BlockID, walker *walker.Walker[BlockID]), entryPoints BlockIDs, revisitElements ...bool)

WalkBlockID is a generic Mesh walker that executes a custom callback for every visited BlockID, starting from the given entry points. It accepts an optional boolean parameter which can be set to true if a Block should be visited more than once following different paths. The callback receives a Walker object as the last parameter which can be used to control the behavior of the walk similar to how a "Context" is used in some parts of the stdlib.

func (*Utils) WalkBlockMetadata

func (u *Utils) WalkBlockMetadata(callback func(blockMetadata *BlockMetadata, walker *walker.Walker[BlockID]), entryPoints BlockIDs, revisitElements ...bool)

WalkBlockMetadata is a generic Mesh walker that executes a custom callback for every visited BlockMetadata, starting from the given entry points. It accepts an optional boolean parameter which can be set to true if a Block should be visited more than once following different paths. The callback receives a Walker object as the last parameter which can be used to control the behavior of the walk similar to how a "Context" is used in some parts of the stdlib.

type VotePower

type VotePower = uint64

VotePower is used to establish an absolute order of votes, regardless of their arrival order. Currently, the used VotePower is the SequenceNumber embedded in the Block Layout, so that, regardless of the order in which votes are received, the same conclusion is computed. Alternatively, the objective timestamp of a Block could be used.

type Voter

type Voter = identity.ID

Voter is a type wrapper for identity.ID and defines a node that supports a conflict or marker.

type Voters

type Voters struct {
	set.Set[Voter]
}

Voters is a set of node identities that votes for a particular Conflict.

func NewVoters

func NewVoters() (voters *Voters)

NewVoters is the constructor of the Voters type.

func (*Voters) AddAll

func (v *Voters) AddAll(voters *Voters)

AddAll adds all new Voters to the Set.

func (*Voters) Clone

func (v *Voters) Clone() (clonedVoters *Voters)

Clone returns a copy of the Voters.

func (*Voters) Decode

func (v *Voters) Decode(data []byte) (bytesRead int, err error)

Decode deserializes bytes into a valid object.

func (*Voters) Intersect

func (v *Voters) Intersect(other *Voters) (intersection *Voters)

Intersect creates an intersection of two set of Voters.

func (*Voters) String

func (v *Voters) String() string

String returns a human-readable version of the Voters.

type WeightProvider

type WeightProvider interface {
	// Update updates the underlying data structure and keeps track of active nodes.
	Update(ei epoch.Index, nodeID identity.ID)

	// Remove updates the underlying data structure by removing node from active list if no activity left.
	Remove(ei epoch.Index, nodeID identity.ID, decreaseBy uint64) (removed bool)

	// Weight returns the weight and total weight for the given block.
	Weight(block *Block) (weight, totalWeight float64)

	// WeightsOfRelevantVoters returns all relevant weights.
	WeightsOfRelevantVoters() (weights map[identity.ID]float64, totalWeight float64)

	// SnapshotEpochActivity returns the activity log for snapshotting.
	SnapshotEpochActivity(epochDiffIndex epoch.Index) (epochActivity epoch.SnapshotEpochActivity)

	// LoadActiveNodes loads active nodes from the snapshot activity log.
	LoadActiveNodes(loadedActiveNodes epoch.SnapshotEpochActivity)

	// Shutdown shuts down the WeightProvider and persists its state.
	Shutdown()
}

WeightProvider is an interface that allows the ApprovalWeightManager to determine approval weights of Blocks in a flexible way, independently of a specific implementation.

type Worker

type Worker interface {
	DoPOW([]byte) (nonce uint64, err error)
}

A Worker performs the PoW for the provided block in serialized byte form.

type WorkerFunc

type WorkerFunc func([]byte) (uint64, error)

The WorkerFunc type is an adapter to allow the use of ordinary functions as a PoW performer.

func (WorkerFunc) DoPOW

func (f WorkerFunc) DoPOW(blk []byte) (uint64, error)

DoPOW calls f(blk).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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