tangle

package
v0.8.13 Latest Latest
Warning

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

Go to latest
Published: May 6, 2022 License: Apache-2.0, BSD-2-Clause Imports: 55 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MessageVersion defines the Version of the message structure.
	MessageVersion uint8 = 1

	// MaxMessageSize defines the maximum size of a message.
	MaxMessageSize = 64 * 1024

	// MessageIDLength defines the length of an MessageID.
	MessageIDLength = 32

	// 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 message must have.
	MinStrongParentsCount = 1
)
View Source
const (
	// MaxLocalQueueSize is the maximum local (containing the message to be issued) queue size in bytes.
	MaxLocalQueueSize = 20 * MaxMessageSize
	// Backoff is the local threshold for rate setting; < MaxQueueWeight.
	Backoff = 25.0
	// RateSettingIncrease is the global additive increase parameter.
	RateSettingIncrease = 1.0
	// RateSettingDecrease global multiplicative decrease parameter (larger than 1).
	RateSettingDecrease = 1.5
	// RateSettingPause is the time to wait before next rate's update after a backoff.
	RateSettingPause = 2
)
View Source
const (
	// MaxDeficit is the maximum cap for accumulated deficit, i.e. max bytes that can be scheduled without waiting.
	// It must be >= MaxMessageSize.
	MaxDeficit = MaxMessageSize
	// MinMana is the minimum amount of Mana needed to issue messages.
	// MaxMessageSize / MinMana is also the upper bound of iterations inside one schedule call, as such it should not be too small.
	MinMana float64 = 1.0
)
View Source
const (
	// PrefixMessage defines the storage prefix for message.
	PrefixMessage byte = iota

	// PrefixMessageMetadata defines the storage prefix for message metadata.
	PrefixMessageMetadata

	// PrefixApprovers defines the storage prefix for approvers.
	PrefixApprovers

	// PrefixMissingMessage defines the storage prefix for missing message.
	PrefixMissingMessage

	// PrefixAttachments defines the storage prefix for attachments.
	PrefixAttachments

	// PrefixMarkerBranchIDMapping defines the storage prefix for the PrefixMarkerBranchIDMapping.
	PrefixMarkerBranchIDMapping

	// PrefixBranchVoters defines the storage prefix for the BranchVoters.
	PrefixBranchVoters

	// PrefixLatestBranchVotes defines the storage prefix for the LatestBranchVotes.
	PrefixLatestBranchVotes

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

	// PrefixBranchWeight defines the storage prefix for the BranchWeight.
	PrefixBranchWeight

	// PrefixMarkerMessageMapping defines the storage prefix for the MarkerMessageMapping.
	PrefixMarkerMessageMapping

	// DBSequenceNumber defines the db sequence number.
	DBSequenceNumber = "seq"
)
View Source
const (
	// DefaultGenesisTime is the default time (Unix in seconds) of the genesis, i.e., the start of the epochs at 2021-03-19 9:00:00 UTC.
	DefaultGenesisTime int64 = 1616144400
	// DefaultSyncTimeWindow is the default sync time window.
	DefaultSyncTimeWindow = 2 * time.Minute
)
View Source
const ApproverTypeLength = 1

ApproverTypeLength contains the amount of bytes that a marshaled version of the ApproverType contains.

AttachmentLength holds the length of a marshaled Attachment in bytes.

View Source
const (
	// LastValidBlockType counts StrongParents, WeakParents, ShallowLikeParents, ShallowDislikeParents.
	LastValidBlockType = ShallowDislikeParentType
)
View Source
const (
	// MaxReattachmentTimeMin defines the max reattachment time.
	MaxReattachmentTimeMin = 10 * time.Minute
)

Variables

View Source
var (
	// ErrNotSynced is triggered when somebody tries to issue a Payload before the Tangle is fully synced.
	ErrNotSynced = errors.New("tangle not synced")
	// ErrParentsInvalid is returned when one or more parents of a message is invalid.
	ErrParentsInvalid = errors.New("one or more parents is invalid")
)
View Source
var (
	// ErrNoStrongParents is triggered if there no strong parents.
	ErrNoStrongParents = errors.New("missing strong messages 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 (
	// ErrInvalidPOWDifficultly is returned when the nonce of a message does not fulfill the PoW difficulty.
	ErrInvalidPOWDifficultly = errors.New("invalid PoW")

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

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

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

	// ErrInvalidMessageAndTransactionTimestamp is returned when the message its transaction timestamps are invalid.
	ErrInvalidMessageAndTransactionTimestamp = fmt.Errorf("invalid message and transaction timestamp")
)
View Source
var (
	// ErrInvalidIssuer is returned when an invalid message is passed to the rate setter.
	ErrInvalidIssuer = errors.New("message not issued by local node")
	// ErrStopped is returned when a message 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 EmptyMessageID = MessageID{}

EmptyMessageID is an empty id.

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

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

View Source
var Initial = 20000.0

Initial is the rate in bytes per second.

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

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

View Source
var ParentTypeToApproverType = map[ParentsType]ApproverType{
	StrongParentType:         StrongApprover,
	WeakParentType:           WeakApprover,
	ShallowLikeParentType:    ShallowLikeApprover,
	ShallowDislikeParentType: ShallowDislikeApprover,
}

ParentTypeToApproverType represents a convenient mapping between a parent type and the approver 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 IssueAndValidateMessageApproval added in v0.8.0

func IssueAndValidateMessageApproval(t *testing.T, messageAlias string, eventMock *EventMock, testFramework *MessageTestFramework, expectedBranchWeights map[string]float64, expectedMarkerWeights map[markers.Marker]float64)

IssueAndValidateMessageApproval issues the msg by the given alias and assets the expected weights.

func MessageCaller added in v0.6.0

func MessageCaller(handler interface{}, params ...interface{})

MessageCaller is the caller function for events that hand over a Message.

func MessageIDCaller added in v0.5.0

func MessageIDCaller(handler interface{}, params ...interface{})

MessageIDCaller is the caller function for events that hand over a MessageID.

func MessageInvalidCaller added in v0.7.6

func MessageInvalidCaller(handler interface{}, params ...interface{})

MessageInvalidCaller is the caller function for events that had over an invalid message.

func NodeIDCaller added in v0.6.2

func NodeIDCaller(handler interface{}, params ...interface{})

NodeIDCaller is the caller function for events that hand over a NodeID.

func PrepareReferences added in v0.8.6

func PrepareReferences(strongParents MessageIDs, issuingTime time.Time, tangle *Tangle) (references ParentMessageIDs, referenceNotPossible MessageIDs, err error)

PrepareReferences is an implementation of ReferencesFunc.

func RegisterMessageIDAlias added in v0.5.7

func RegisterMessageIDAlias(messageID MessageID, alias string)

RegisterMessageIDAlias registers an alias that will modify the String() output of the MessageID to show a human readable string instead of the base58 encoded Version of itself.

func SyncChangedCaller added in v0.6.0

func SyncChangedCaller(handler interface{}, params ...interface{})

SyncChangedCaller is the caller function for sync changed event.

func UnregisterMessageIDAliases added in v0.5.7

func UnregisterMessageIDAliases()

UnregisterMessageIDAliases removes all aliases registered through the RegisterMessageIDAlias function.

Types

type ActivityLog added in v0.8.0

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

ActivityLog is a time-based log of node activity. It stores information when a node was active and provides functionality to query for certain timeframes.

func NewActivityLog added in v0.8.0

func NewActivityLog() *ActivityLog

NewActivityLog is the constructor for ActivityLog.

func (*ActivityLog) Active added in v0.8.0

func (a *ActivityLog) Active(lowerBound, upperBound time.Time) (active, empty bool)

Active returns true if the node was active between lower and upper bound. It cleans up the log on the fly, meaning that old/stale times are deleted. If the log ends up empty after cleaning up, empty is set to true.

func (*ActivityLog) Add added in v0.8.0

func (a *ActivityLog) Add(t time.Time) (added bool)

Add adds a node activity to the log.

func (*ActivityLog) Clone added in v0.8.0

func (a *ActivityLog) Clone() *ActivityLog

Clone clones the ActivityLog.

func (*ActivityLog) Decode added in v0.8.13

func (a *ActivityLog) Decode(data []byte) (bytesRead int, err error)

Decode deserializes bytes into a valid object.

func (*ActivityLog) Encode added in v0.8.13

func (a *ActivityLog) Encode() ([]byte, error)

Encode ActivityLog a serialized byte slice of the object.

func (*ActivityLog) String added in v0.8.0

func (a *ActivityLog) String() string

String returns a human-readable version of ActivityLog.

func (*ActivityLog) Times added in v0.8.0

func (a *ActivityLog) Times() (times []int64)

Times returns all times stored in this ActivityLog.

type ApprovalWeightManager added in v0.5.7

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

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

func NewApprovalWeightManager added in v0.5.7

func NewApprovalWeightManager(tangle *Tangle) (approvalWeightManager *ApprovalWeightManager)

NewApprovalWeightManager is the constructor for ApprovalWeightManager.

func (*ApprovalWeightManager) Setup added in v0.5.7

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 added in v0.5.7

func (a *ApprovalWeightManager) Shutdown()

Shutdown shuts down the ApprovalWeightManager and persists its state.

func (*ApprovalWeightManager) VotersOfBranch added in v0.8.10

func (a *ApprovalWeightManager) VotersOfBranch(branchID ledgerstate.BranchID) (voters *Voters)

VotersOfBranch returns the Voters of the given branch ledgerstate.BranchID.

func (*ApprovalWeightManager) WeightOfBranch added in v0.5.7

func (a *ApprovalWeightManager) WeightOfBranch(branchID ledgerstate.BranchID) (weight float64)

WeightOfBranch returns the weight of the given Branch that was added by Voters of the given epoch.

func (*ApprovalWeightManager) WeightOfMarker added in v0.5.7

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 added in v0.5.7

type ApprovalWeightManagerEvents struct {
	// MessageProcessed is triggered once a message is finished being processed by the ApprovalWeightManager.
	MessageProcessed *events.Event
	// BranchWeightChanged is triggered when a branch's weight changed.
	BranchWeightChanged *events.Event
	// MarkerWeightChanged is triggered when a marker's weight changed.
	MarkerWeightChanged *events.Event
}

ApprovalWeightManagerEvents represents events happening in the ApprovalWeightManager.

type Approver

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

Approver is an approver of a given referenced message.

func NewApprover

func NewApprover(approverType ApproverType, referencedMessageID MessageID, approverMessageID MessageID) *Approver

NewApprover creates a new approver relation to the given approved/referenced message.

func (*Approver) ApproverMessageID

func (a *Approver) ApproverMessageID() MessageID

ApproverMessageID returns the ID of the message which referenced the given approved message.

func (*Approver) Bytes

func (a *Approver) Bytes() []byte

Bytes returns the bytes of the approver.

func (*Approver) FromBytes added in v0.8.10

func (a *Approver) FromBytes(data []byte) (result *Approver, err error)

FromBytes parses the given bytes into an approver.

func (*Approver) FromObjectStorage added in v0.8.10

func (a *Approver) FromObjectStorage(key, _ []byte) (objectstorage.StorableObject, error)

FromObjectStorage creates an Approver from sequences of key and bytes.

func (*Approver) ObjectStorageKey

func (a *Approver) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*Approver) ObjectStorageValue

func (a *Approver) ObjectStorageValue() (result []byte)

ObjectStorageValue returns the value of the stored approver object.

func (*Approver) ReferencedMessageID

func (a *Approver) ReferencedMessageID() MessageID

ReferencedMessageID returns the ID of the message which is referenced by the approver.

func (*Approver) String

func (a *Approver) String() string

String returns the string representation of the approver.

func (*Approver) Type added in v0.3.6

func (a *Approver) Type() ApproverType

Type returns the type of the Approver reference.

type ApproverType added in v0.3.6

type ApproverType uint8

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

const (
	// StrongApprover is the ApproverType that represents references formed by strong parents.
	StrongApprover ApproverType = iota

	// WeakApprover is the ApproverType that represents references formed by weak parents.
	WeakApprover

	// ShallowLikeApprover is the ApproverType that represents references formed by shallow like parents.
	ShallowLikeApprover

	// ShallowDislikeApprover is the ApproverType that represents references formed by shallow dislike parents.
	ShallowDislikeApprover
)

func (ApproverType) Bytes added in v0.3.6

func (a ApproverType) Bytes() []byte

Bytes returns a marshaled version of the ApproverType.

func (ApproverType) String added in v0.3.6

func (a ApproverType) String() string

String returns a human readable version of the ApproverType.

type Attachment added in v0.3.6

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

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

func NewAttachment added in v0.3.6

func NewAttachment(transactionID ledgerstate.TransactionID, messageID MessageID) *Attachment

NewAttachment creates an attachment object with the given information.

func (*Attachment) Bytes added in v0.3.6

func (a *Attachment) Bytes() []byte

Bytes marshals the Attachment into a sequence of bytes.

func (*Attachment) FromBytes added in v0.8.10

func (a *Attachment) FromBytes(data []byte) (result *Attachment, err error)

FromBytes unmarshals an Attachment from a sequence of bytes - it either creates a new object or fills the optionally provided one with the parsed information.

func (*Attachment) FromObjectStorage added in v0.8.10

func (a *Attachment) FromObjectStorage(key, _ []byte) (objectstorage.StorableObject, error)

FromObjectStorage creates an Attachment from sequences of key and bytes.

func (*Attachment) MessageID added in v0.3.6

func (a *Attachment) MessageID() MessageID

MessageID returns the messageID of this Attachment.

func (*Attachment) ObjectStorageKey added in v0.3.6

func (a *Attachment) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*Attachment) ObjectStorageValue added in v0.3.6

func (a *Attachment) ObjectStorageValue() (data []byte)

ObjectStorageValue marshals the "content part" of an Attachment to a sequence of bytes. Since all of the information for this object are stored in its key, this method does nothing and is only required to conform with the interface.

func (*Attachment) String added in v0.3.6

func (a *Attachment) String() string

String returns a human readable version of the Attachment.

func (*Attachment) TransactionID added in v0.3.6

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

TransactionID returns the transactionID of this Attachment.

type Booker added in v0.3.6

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

	MarkersManager *BranchMarkersMapper
	// contains filtered or unexported fields
}

Booker is a Tangle component that takes care of booking Messages and Transactions by assigning them to the corresponding Branch of the ledger state.

func NewBooker added in v0.3.6

func NewBooker(tangle *Tangle) (messageBooker *Booker)

NewBooker is the constructor of a Booker.

func (*Booker) BookMessage added in v0.5.7

func (b *Booker) BookMessage(messageID MessageID) (err error)

BookMessage tries to book the given Message (and potentially its contained Transaction) into the LedgerState and the Tangle. It fires a MessageBooked event if it succeeds. If the Message is invalid it fires a MessageInvalid event. Booking a message essentially means that parents are examined, the branch of the message determined based on the branch inheritance rules of the like switch and markers are inherited. If everything is valid, the message is marked as booked. Following, the message branch is set, and it can continue in the dataflow to add support to the determined branches and markers.

func (*Booker) MessageBranchIDs added in v0.8.6

func (b *Booker) MessageBranchIDs(messageID MessageID) (branchIDs ledgerstate.BranchIDs, err error)

MessageBranchIDs returns the BranchIDs of the given Message.

func (*Booker) PayloadBranchIDs added in v0.8.6

func (b *Booker) PayloadBranchIDs(messageID MessageID) (branchIDs ledgerstate.BranchIDs, err error)

PayloadBranchIDs returns the BranchIDs of the payload contained in the given Message.

func (*Booker) PropagateForkedBranch added in v0.8.6

func (b *Booker) PropagateForkedBranch(transactionID ledgerstate.TransactionID, forkedBranchID ledgerstate.BranchID) (err error)

PropagateForkedBranch propagates the forked BranchID to the future cone of the attachments of the given Transaction.

func (*Booker) Setup added in v0.4.0

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 added in v0.3.6

func (b *Booker) Shutdown()

Shutdown shuts down the Booker and persists its state.

type BookerEvents added in v0.3.6

type BookerEvents struct {
	// MessageBooked is triggered when a Message was booked (it's Branch, and it's Payload's Branch were determined).
	MessageBooked *events.Event

	// MessageBranchUpdated is triggered when the BranchID of a Message is changed in its MessageMetadata.
	MessageBranchUpdated *events.Event

	// MarkerBranchAdded is triggered when a Marker is mapped to a new BranchID.
	MarkerBranchAdded *events.Event

	// Error gets triggered when the Booker faces an unexpected error.
	Error *events.Event
}

BookerEvents represents events happening in the Booker.

type BranchMarkersMapper added in v0.8.6

type BranchMarkersMapper struct {
	*markers.Manager

	Events *BranchMarkersMapperEvents
	// contains filtered or unexported fields
}

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

func NewBranchMarkersMapper added in v0.8.6

func NewBranchMarkersMapper(tangle *Tangle) (b *BranchMarkersMapper)

NewBranchMarkersMapper is the constructor of the MarkersManager.

func (*BranchMarkersMapper) Ceiling added in v0.8.6

func (b *BranchMarkersMapper) Ceiling(referenceMarker *markers.Marker) (marker markers.Index, branchIDs ledgerstate.BranchIDs, exists bool)

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

func (*BranchMarkersMapper) Floor added in v0.8.6

func (b *BranchMarkersMapper) Floor(referenceMarker *markers.Marker) (marker markers.Index, branchIDs ledgerstate.BranchIDs, exists bool)

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

func (*BranchMarkersMapper) ForEachBranchIDMapping added in v0.8.6

func (b *BranchMarkersMapper) ForEachBranchIDMapping(sequenceID markers.SequenceID, thresholdIndex markers.Index, callback func(mappedMarker *markers.Marker, mappedBranchIDs ledgerstate.BranchIDs))

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

func (*BranchMarkersMapper) ForEachMarkerReferencingMarker added in v0.8.6

func (b *BranchMarkersMapper) 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 (*BranchMarkersMapper) InheritStructureDetails added in v0.8.6

func (b *BranchMarkersMapper) InheritStructureDetails(message *Message, structureDetails []*markers.StructureDetails) (newStructureDetails *markers.StructureDetails, newSequenceCreated bool)

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

func (*BranchMarkersMapper) MessageID added in v0.8.6

func (b *BranchMarkersMapper) MessageID(marker *markers.Marker) (messageID MessageID)

MessageID retrieves the MessageID of the given Marker.

func (*BranchMarkersMapper) PendingBranchIDs added in v0.8.10

func (b *BranchMarkersMapper) PendingBranchIDs(marker *markers.Marker) (branchIDs ledgerstate.BranchIDs, err error)

PendingBranchIDs returns the pending BranchIDs that are associated with the given Marker.

func (*BranchMarkersMapper) SetBranchIDs added in v0.8.10

func (b *BranchMarkersMapper) SetBranchIDs(marker *markers.Marker, branchIDs ledgerstate.BranchIDs) (updated bool)

SetBranchIDs associates ledgerstate.BranchIDs with the given Marker.

func (*BranchMarkersMapper) SetMessageID added in v0.8.6

func (b *BranchMarkersMapper) SetMessageID(marker *markers.Marker, messageID MessageID)

SetMessageID associates a MessageID with the given Marker.

type BranchMarkersMapperEvents added in v0.8.6

type BranchMarkersMapperEvents struct {
	// FutureMarkerUpdated is triggered when a message's future marker is updated.
	FutureMarkerUpdated *events.Event
}

BranchMarkersMapperEvents represents events happening in the BranchMarkersMapper.

type BranchVote added in v0.8.6

type BranchVote struct {
	Voter     Voter                `serix:"0"`
	BranchID  ledgerstate.BranchID `serix:"1"`
	Opinion   Opinion              `serix:"2"`
	VotePower VotePower            `serix:"3"`
}

BranchVote represents a struct that holds information about what Opinion a certain Voter has on a Branch.

func (*BranchVote) String added in v0.8.6

func (v *BranchVote) String() string

String returns a human-readable version of the Vote.

func (*BranchVote) WithBranchID added in v0.8.6

func (v *BranchVote) WithBranchID(branchID ledgerstate.BranchID) (rejectedVote *BranchVote)

WithBranchID derives a vote for the given BranchID.

func (*BranchVote) WithOpinion added in v0.8.6

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

WithOpinion derives a vote for the given Opinion.

type BranchVoters added in v0.8.6

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

BranchVoters is a data structure that tracks which nodes support a branch.

func NewBranchVoters added in v0.8.6

func NewBranchVoters(branchID ledgerstate.BranchID) (branchVoters *BranchVoters)

NewBranchVoters is the constructor for the BranchVoters object.

func (*BranchVoters) AddVoter added in v0.8.6

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

AddVoter adds a new Voter to the tracked BranchID.

func (*BranchVoters) AddVoters added in v0.8.6

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

AddVoters adds the Voters set to the tracked BranchID.

func (*BranchVoters) BranchID added in v0.8.6

func (b *BranchVoters) BranchID() (branchID ledgerstate.BranchID)

BranchID returns the BranchID that is being tracked.

func (*BranchVoters) Bytes added in v0.8.6

func (b *BranchVoters) Bytes() (marshaledBranchVoters []byte)

Bytes returns a marshaled version of the BranchVoters.

func (*BranchVoters) DeleteVoter added in v0.8.6

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

DeleteVoter deletes a Voter from the tracked BranchID.

func (*BranchVoters) FromBytes added in v0.8.10

func (b *BranchVoters) FromBytes(data []byte) (branchVoters *BranchVoters, err error)

FromBytes unmarshals a BranchVoters object from a sequence of bytes.

func (*BranchVoters) FromObjectStorage added in v0.8.10

func (b *BranchVoters) FromObjectStorage(key, value []byte) (objectstorage.StorableObject, error)

FromObjectStorage creates an BranchVoters from sequences of key and bytes.

func (*BranchVoters) Has added in v0.8.6

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

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

func (*BranchVoters) ObjectStorageKey added in v0.8.6

func (b *BranchVoters) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*BranchVoters) ObjectStorageValue added in v0.8.6

func (b *BranchVoters) ObjectStorageValue() []byte

ObjectStorageValue marshals the BranchVoters into a sequence of bytes. The ID is not serialized here as it is only used as a key in the ObjectStorage.

func (*BranchVoters) String added in v0.8.6

func (b *BranchVoters) String() string

String returns a human-readable version of the BranchVoters.

func (*BranchVoters) Voters added in v0.8.6

func (b *BranchVoters) Voters() (voters *Voters)

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

type BranchWeight added in v0.5.7

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

BranchWeight is a data structure that tracks the weight of a BranchID.

func NewBranchWeight added in v0.5.7

func NewBranchWeight(branchID ledgerstate.BranchID) (branchWeight *BranchWeight)

NewBranchWeight creates a new BranchWeight.

func (*BranchWeight) BranchID added in v0.5.7

func (b *BranchWeight) BranchID() (branchID ledgerstate.BranchID)

BranchID returns the BranchID that is being tracked.

func (*BranchWeight) Bytes added in v0.5.7

func (b *BranchWeight) Bytes() (marshaledBranchWeight []byte)

Bytes returns a marshaled version of the BranchWeight.

func (*BranchWeight) FromBytes added in v0.8.10

func (b *BranchWeight) FromBytes(data []byte) (branchWeight *BranchWeight, err error)

FromBytes unmarshals a BranchWeight object from a sequence of bytes.

func (*BranchWeight) FromObjectStorage added in v0.8.10

func (b *BranchWeight) FromObjectStorage(key, value []byte) (objectstorage.StorableObject, error)

FromObjectStorage creates an BranchWeight from sequences of key and bytes.

func (*BranchWeight) ObjectStorageKey added in v0.5.7

func (b *BranchWeight) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*BranchWeight) ObjectStorageValue added in v0.5.7

func (b *BranchWeight) ObjectStorageValue() []byte

ObjectStorageValue marshals the BranchWeight into a sequence of bytes. The ID is not serialized here as it is only used as a key in the ObjectStorage.

func (*BranchWeight) SetWeight added in v0.5.7

func (b *BranchWeight) SetWeight(weight float64) (modified bool)

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

func (*BranchWeight) String added in v0.5.7

func (b *BranchWeight) String() string

String returns a human-readable version of the BranchWeight.

func (*BranchWeight) Weight added in v0.5.7

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

Weight returns the weight of the BranchID.

type BranchWeightChangedEvent added in v0.8.0

type BranchWeightChangedEvent struct {
	BranchID ledgerstate.BranchID
	Weight   float64
}

BranchWeightChangedEvent holds information about a branch and its updated weight.

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
}

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

type CManaWeightProvider added in v0.5.8

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 added in v0.5.8

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

NewCManaWeightProvider is the constructor for CManaWeightProvider.

func (*CManaWeightProvider) ActiveNodes added in v0.5.8

func (c *CManaWeightProvider) ActiveNodes() (activeNodes NodesActivityLog)

ActiveNodes returns the map of the active nodes.

func (*CManaWeightProvider) Shutdown added in v0.5.8

func (c *CManaWeightProvider) Shutdown()

Shutdown shuts down the WeightProvider and persists its state.

func (*CManaWeightProvider) Update added in v0.5.8

func (c *CManaWeightProvider) Update(t time.Time, nodeID identity.ID)

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

func (*CManaWeightProvider) Weight added in v0.5.8

func (c *CManaWeightProvider) Weight(message *Message) (weight, totalWeight float64)

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

func (*CManaWeightProvider) WeightsOfRelevantVoters added in v0.8.6

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

WeightsOfRelevantVoters returns all relevant weights.

type CachedLatestMarkerVotesByVoter added in v0.8.6

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

CachedLatestMarkerVotesByVoter represents a cached LatestMarkerVotesByVoter mapped by Voter.

func (CachedLatestMarkerVotesByVoter) Consume added in v0.8.6

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 ConfirmationEvents added in v0.8.0

type ConfirmationEvents struct {
	MessageConfirmed      *events.Event
	BranchConfirmed       *events.Event
	TransactionConfirmed  *events.Event
	TransactionGoFChanged *events.Event
	BranchGoFChanged      *events.Event
}

ConfirmationEvents are events entailing confirmation.

type ConfirmationOracle added in v0.8.0

type ConfirmationOracle interface {
	IsMarkerConfirmed(marker *markers.Marker) bool
	IsMessageConfirmed(msgID MessageID) bool
	IsBranchConfirmed(branchID ledgerstate.BranchID) bool
	IsTransactionConfirmed(transactionID ledgerstate.TransactionID) bool
	IsOutputConfirmed(outputID ledgerstate.OutputID) bool
	FirstUnconfirmedMarkerIndex(sequenceID markers.SequenceID) (unconfirmedMarkerIndex markers.Index)
	Events() *ConfirmationEvents
}

ConfirmationOracle answers questions about entities' confirmation.

type DBStatsResult added in v0.8.4

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

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

type Dispatcher added in v0.8.4

type Dispatcher struct {
	Events *DispatcherEvents
	// contains filtered or unexported fields
}

Dispatcher is a Tangle component that dispatches messages after being scheduled.

func NewDispatcher added in v0.8.4

func NewDispatcher(tangle *Tangle) (dispatcher *Dispatcher)

NewDispatcher is the constructor for the Dispatcher.

func (*Dispatcher) Setup added in v0.8.4

func (d *Dispatcher) Setup()

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

func (*Dispatcher) Shutdown added in v0.8.4

func (d *Dispatcher) Shutdown()

Shutdown shuts down the Dispatcher.

type DispatcherEvents added in v0.8.4

type DispatcherEvents struct {
	// MessageDispatched is triggered when a message is already scheduled and thus ready to be dispatched.
	MessageDispatched *events.Event
}

DispatcherEvents represents events happening in the Dispatcher.

type EventMock added in v0.8.0

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

EventMock acts as a container for event mocks.

func NewEventMock added in v0.8.0

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

NewEventMock creates a new EventMock.

func (*EventMock) AssertExpectations added in v0.8.0

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

AssertExpectations asserts expectations.

func (*EventMock) BranchWeightChanged added in v0.8.0

func (e *EventMock) BranchWeightChanged(event *BranchWeightChangedEvent)

BranchWeightChanged is the mocked BranchWeightChanged function.

func (*EventMock) DetachAll added in v0.8.0

func (e *EventMock) DetachAll()

DetachAll detaches all event handlers.

func (*EventMock) Expect added in v0.8.0

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 added in v0.8.0

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

MarkerWeightChanged is the mocked MarkerWeightChanged function.

func (*EventMock) MessageProcessed added in v0.8.0

func (e *EventMock) MessageProcessed(messageID MessageID)

MessageProcessed is the mocked MessageProcessed function.

type Events

type Events struct {
	// MessageInvalid is triggered when a Message is detected to be objectively invalid.
	MessageInvalid *events.Event

	// Error is triggered when the Tangle faces an error from which it can not recover.
	Error *events.Event
}

Events represents events happening in the Tangle.

type FutureMarkerUpdate added in v0.8.6

type FutureMarkerUpdate struct {
	ID           MessageID
	FutureMarker MessageID
}

FutureMarkerUpdate contains the messageID of the future marker of a message.

type LastConfirmedMessage added in v0.5.8

type LastConfirmedMessage struct {
	MessageID MessageID `serix:"0"`
	Time      time.Time `serix:"1"`
}

LastConfirmedMessage is a wrapper type for the last confirmed message, consisting of MessageID and time.

func (LastConfirmedMessage) Bytes added in v0.5.8

func (l LastConfirmedMessage) Bytes() (marshaledLastConfirmedMessage []byte)

Bytes returns a marshaled version of the LastConfirmedMessage.

func (LastConfirmedMessage) String added in v0.5.8

func (l LastConfirmedMessage) String() string

String returns a human readable version of the LastConfirmedMessage.

type LatestBranchVotes added in v0.8.6

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

LatestBranchVotes represents the branch supported from an Issuer.

func NewLatestBranchVotes added in v0.8.6

func NewLatestBranchVotes(voter Voter) (latestBranchVotes *LatestBranchVotes)

NewLatestBranchVotes creates a new LatestBranchVotes.

func (*LatestBranchVotes) Bytes added in v0.8.6

func (l *LatestBranchVotes) Bytes() []byte

Bytes returns a marshaled version of the LatestBranchVotes.

func (*LatestBranchVotes) FromBytes added in v0.8.10

func (l *LatestBranchVotes) FromBytes(data []byte) (latestBranchVotes *LatestBranchVotes, err error)

FromBytes unmarshals a LatestBranchVotes object from a sequence of bytes.

func (*LatestBranchVotes) FromObjectStorage added in v0.8.10

func (l *LatestBranchVotes) FromObjectStorage(key, value []byte) (objectstorage.StorableObject, error)

FromObjectStorage creates an LatestBranchVotes from sequences of key and bytes.

func (*LatestBranchVotes) ObjectStorageKey added in v0.8.6

func (l *LatestBranchVotes) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*LatestBranchVotes) ObjectStorageValue added in v0.8.6

func (l *LatestBranchVotes) ObjectStorageValue() []byte

ObjectStorageValue marshals the LatestBranchVotes into a sequence of bytes. The ID is not serialized here as it is only used as a key in the ObjectStorage.

func (*LatestBranchVotes) Store added in v0.8.6

func (l *LatestBranchVotes) Store(vote *BranchVote) (stored bool)

Store stores the vote for the LatestBranchVotes.

func (*LatestBranchVotes) String added in v0.8.6

func (l *LatestBranchVotes) String() string

String returns a human-readable version of the LatestBranchVotes.

func (*LatestBranchVotes) Vote added in v0.8.6

func (l *LatestBranchVotes) Vote(branchID ledgerstate.BranchID) (vote *BranchVote, exists bool)

Vote returns the Vote for the LatestBranchVotes.

type LatestMarkerVotes added in v0.8.6

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

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 added in v0.8.6

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

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

func (*LatestMarkerVotes) Bytes added in v0.8.6

func (l *LatestMarkerVotes) Bytes() []byte

Bytes returns a marshaled version of the LatestMarkerVotes.

func (*LatestMarkerVotes) FromBytes added in v0.8.10

func (l *LatestMarkerVotes) FromBytes(data []byte) (latestMarkerVotes *LatestMarkerVotes, err error)

FromBytes unmarshals a LatestMarkerVotes from a sequence of bytes.

func (*LatestMarkerVotes) FromObjectStorage added in v0.8.10

func (l *LatestMarkerVotes) FromObjectStorage(key, value []byte) (objectstorage.StorableObject, error)

FromObjectStorage creates an LatestMarkerVotes from sequences of key and bytes.

func (*LatestMarkerVotes) ObjectStorageKey added in v0.8.6

func (l *LatestMarkerVotes) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*LatestMarkerVotes) ObjectStorageValue added in v0.8.6

func (l *LatestMarkerVotes) ObjectStorageValue() []byte

ObjectStorageValue marshals the LatestMarkerVotes into a sequence of bytes. The ID is not serialized here as it is only used as a key in the ObjectStorage.

func (*LatestMarkerVotes) Power added in v0.8.6

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 added in v0.8.6

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) String added in v0.8.6

func (l *LatestMarkerVotes) String() string

String returns a human-readable version of the LatestMarkerVotes.

func (*LatestMarkerVotes) Voter added in v0.8.6

func (l *LatestMarkerVotes) Voter() Voter

Voter returns the Voter for the LatestMarkerVotes.

type LedgerState added in v0.3.6

type LedgerState struct {
	*ledgerstate.Ledgerstate
	// contains filtered or unexported fields
}

LedgerState is a Tangle component that wraps the components of the ledgerstate package and makes them available at a "single point of contact".

func NewLedgerState added in v0.3.6

func NewLedgerState(tangle *Tangle) (ledgerState *LedgerState)

NewLedgerState is the constructor of the LedgerState component.

func (*LedgerState) BookTransaction added in v0.3.6

func (l *LedgerState) BookTransaction(transaction *ledgerstate.Transaction, messageID MessageID) (targetBranches ledgerstate.BranchIDs, err error)

BookTransaction books the given Transaction into the underlying LedgerState and returns the target Branch and an eventual error.

func (*LedgerState) BranchIDs added in v0.8.10

func (l *LedgerState) BranchIDs(transactionID ledgerstate.TransactionID) (branchIDs ledgerstate.BranchIDs)

BranchIDs returns the branchIDs of the given transactionID.

func (*LedgerState) CachedOutput added in v0.6.2

CachedOutput returns the Output with the given ID.

func (*LedgerState) CachedOutputMetadata added in v0.6.2

CachedOutputMetadata returns the OutputMetadata with the given ID.

func (*LedgerState) CachedOutputsOnAddress added in v0.6.2

func (l *LedgerState) CachedOutputsOnAddress(address ledgerstate.Address) (cachedOutputs objectstorage.CachedObjects[ledgerstate.Output])

CachedOutputsOnAddress retrieves all the Outputs that are associated with an address.

func (*LedgerState) CachedTransactionMetadata added in v0.8.0

func (l *LedgerState) CachedTransactionMetadata(transactionID ledgerstate.TransactionID) *objectstorage.CachedObject[*ledgerstate.TransactionMetadata]

CachedTransactionMetadata returns the TransactionMetadata with the given ID.

func (*LedgerState) CheckTransaction added in v0.4.0

func (l *LedgerState) CheckTransaction(transaction *ledgerstate.Transaction) (err error)

CheckTransaction contains fast checks that have to be performed before booking a Transaction.

func (*LedgerState) ConfirmedConsumer added in v0.8.0

func (l *LedgerState) ConfirmedConsumer(outputID ledgerstate.OutputID) (consumerID ledgerstate.TransactionID)

ConfirmedConsumer returns the confirmed transactionID consuming the given outputID.

func (*LedgerState) ConflictSet added in v0.3.6

func (l *LedgerState) ConflictSet(transactionID ledgerstate.TransactionID) (conflictSet ledgerstate.TransactionIDs)

ConflictSet returns the list of transactionIDs conflicting with the given transactionID.

func (*LedgerState) ConsumedOutputs added in v0.4.1

func (l *LedgerState) ConsumedOutputs(transaction *ledgerstate.Transaction) (cachedInputs objectstorage.CachedObjects[ledgerstate.Output])

ConsumedOutputs returns the consumed (cached)Outputs of the given Transaction.

func (*LedgerState) Consumers added in v0.5.3

func (l *LedgerState) Consumers(outputID ledgerstate.OutputID) (cachedTransactions objectstorage.CachedObjects[*ledgerstate.Consumer])

Consumers returns the (cached) consumers of the given outputID.

func (*LedgerState) LoadSnapshot added in v0.3.6

func (l *LedgerState) LoadSnapshot(snapshot *ledgerstate.Snapshot) (err error)

LoadSnapshot creates a set of outputs in the UTXO-DAG, that are forming the genesis for future transactions.

func (*LedgerState) ReturnTransaction added in v0.6.2

func (l *LedgerState) ReturnTransaction(transactionID ledgerstate.TransactionID) (transaction *ledgerstate.Transaction)

ReturnTransaction returns a specific transaction.

func (*LedgerState) Setup added in v0.8.6

func (l *LedgerState) Setup()

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

func (*LedgerState) Shutdown added in v0.3.6

func (l *LedgerState) Shutdown()

Shutdown shuts down the LedgerState and persists its state.

func (*LedgerState) SnapshotUTXO added in v0.6.2

func (l *LedgerState) SnapshotUTXO() (snapshot *ledgerstate.Snapshot)

SnapshotUTXO returns the UTXO snapshot, which is a list of transactions with unspent outputs.

func (*LedgerState) TotalSupply added in v0.6.0

func (l *LedgerState) TotalSupply() (totalSupply uint64)

TotalSupply returns the total supply.

func (*LedgerState) Transaction added in v0.4.0

Transaction retrieves the Transaction with the given TransactionID from the object storage.

func (*LedgerState) TransactionConflicting added in v0.3.6

func (l *LedgerState) TransactionConflicting(transactionID ledgerstate.TransactionID) bool

TransactionConflicting returns whether the given transaction is part of a conflict.

func (*LedgerState) TransactionMetadata added in v0.3.6

func (l *LedgerState) TransactionMetadata(transactionID ledgerstate.TransactionID) (cachedTransactionMetadata *objectstorage.CachedObject[*ledgerstate.TransactionMetadata])

TransactionMetadata retrieves the TransactionMetadata with the given TransactionID from the object storage.

func (*LedgerState) TransactionValid added in v0.3.6

func (l *LedgerState) TransactionValid(transaction *ledgerstate.Transaction, messageID MessageID) (err error)

TransactionValid performs some fast checks of the Transaction and triggers a MessageInvalid event if the checks do not pass.

func (*LedgerState) Transactions added in v0.6.2

func (l *LedgerState) Transactions() (transactions map[ledgerstate.TransactionID]*ledgerstate.Transaction)

Transactions returns all the transactions.

type LikedConflictMembers added in v0.8.6

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

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

type ManaRetrieverFunc added in v0.5.8

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

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

type MarkerIndexBranchIDMapping added in v0.3.6

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

MarkerIndexBranchIDMapping is a data structure that allows to map marker Indexes to a BranchID.

func NewMarkerIndexBranchIDMapping added in v0.3.6

func NewMarkerIndexBranchIDMapping(sequenceID markers.SequenceID) (markerBranchMapping *MarkerIndexBranchIDMapping)

NewMarkerIndexBranchIDMapping creates a new MarkerIndexBranchIDMapping for the given SequenceID.

func (*MarkerIndexBranchIDMapping) BranchIDs added in v0.8.10

func (m *MarkerIndexBranchIDMapping) BranchIDs(markerIndex markers.Index) (branchIDs ledgerstate.BranchIDs)

BranchIDs returns the BranchID that is associated to the given marker Index.

func (*MarkerIndexBranchIDMapping) Bytes added in v0.3.6

func (m *MarkerIndexBranchIDMapping) Bytes() []byte

Bytes returns a marshaled version of the MarkerIndexBranchIDMapping.

func (*MarkerIndexBranchIDMapping) Ceiling added in v0.5.7

func (m *MarkerIndexBranchIDMapping) Ceiling(index markers.Index) (marker markers.Index, branchIDs ledgerstate.BranchIDs, exists bool)

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

func (*MarkerIndexBranchIDMapping) DeleteBranchID added in v0.8.0

func (m *MarkerIndexBranchIDMapping) DeleteBranchID(index markers.Index)

DeleteBranchID deletes a mapping between the given marker Index and the stored BranchID.

func (*MarkerIndexBranchIDMapping) Floor added in v0.5.7

func (m *MarkerIndexBranchIDMapping) Floor(index markers.Index) (marker markers.Index, branchIDs ledgerstate.BranchIDs, exists bool)

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

func (*MarkerIndexBranchIDMapping) FromBytes added in v0.8.10

func (m *MarkerIndexBranchIDMapping) FromBytes(data []byte) (markerIndexBranchIDMapping objectstorage.StorableObject, err error)

FromBytes unmarshals a MarkerIndexBranchIDMapping from a sequence of bytes.

func (*MarkerIndexBranchIDMapping) FromObjectStorage added in v0.8.10

func (m *MarkerIndexBranchIDMapping) FromObjectStorage(key, value []byte) (objectstorage.StorableObject, error)

FromObjectStorage creates an MarkerIndexBranchIDMapping from sequences of key and bytes.

func (*MarkerIndexBranchIDMapping) ObjectStorageKey added in v0.3.6

func (m *MarkerIndexBranchIDMapping) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*MarkerIndexBranchIDMapping) ObjectStorageValue added in v0.3.6

func (m *MarkerIndexBranchIDMapping) ObjectStorageValue() []byte

ObjectStorageValue marshals the MarkerIndexBranchIDMapping into a sequence of bytes. The ID is not serialized here as it is only used as a key in the ObjectStorage.

func (*MarkerIndexBranchIDMapping) SequenceID added in v0.3.6

SequenceID returns the SequenceID that this MarkerIndexBranchIDMapping represents.

func (*MarkerIndexBranchIDMapping) SetBranchIDs added in v0.8.10

func (m *MarkerIndexBranchIDMapping) SetBranchIDs(index markers.Index, branchIDs ledgerstate.BranchIDs)

SetBranchIDs creates a mapping between the given marker Index and the given BranchID.

func (*MarkerIndexBranchIDMapping) String added in v0.3.6

func (m *MarkerIndexBranchIDMapping) String() string

String returns a human-readable version of the MarkerIndexBranchIDMapping.

type MarkerMessageMapping added in v0.5.7

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

MarkerMessageMapping is a data structure that denotes a mapping from a Marker to a Message.

func NewMarkerMessageMapping added in v0.5.7

func NewMarkerMessageMapping(marker *markers.Marker, messageID MessageID) *MarkerMessageMapping

NewMarkerMessageMapping is the constructor for the MarkerMessageMapping.

func (*MarkerMessageMapping) Bytes added in v0.5.7

func (m *MarkerMessageMapping) Bytes() []byte

Bytes returns a marshaled version of the MarkerMessageMapping.

func (*MarkerMessageMapping) FromBytes added in v0.8.10

func (m *MarkerMessageMapping) FromBytes(data []byte) (individuallyMappedMessage objectstorage.StorableObject, err error)

FromBytes unmarshals an MarkerMessageMapping from a sequence of bytes.

func (*MarkerMessageMapping) FromObjectStorage added in v0.8.10

func (m *MarkerMessageMapping) FromObjectStorage(key, value []byte) (objectstorage.StorableObject, error)

FromObjectStorage creates an MarkerMessageMapping from sequences of key and bytes.

func (*MarkerMessageMapping) Marker added in v0.5.7

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

Marker returns the Marker that is mapped to a MessageID.

func (*MarkerMessageMapping) MessageID added in v0.5.7

func (m *MarkerMessageMapping) MessageID() MessageID

MessageID returns the MessageID of the Marker.

func (*MarkerMessageMapping) ObjectStorageKey added in v0.5.7

func (m *MarkerMessageMapping) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*MarkerMessageMapping) ObjectStorageValue added in v0.5.7

func (m *MarkerMessageMapping) ObjectStorageValue() []byte

ObjectStorageValue marshals the Output into a sequence of bytes. The ID is not serialized here as it is only used as a key in the ObjectStorage.

func (*MarkerMessageMapping) String added in v0.5.7

func (m *MarkerMessageMapping) String() string

String returns a human-readable version of the MarkerMessageMapping.

type MarkerWeightChangedEvent added in v0.8.0

type MarkerWeightChangedEvent struct {
	Marker *markers.Marker
	Weight float64
}

MarkerWeightChangedEvent holds information about a marker and its updated weight.

type Message

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

Message represents the core message for the base layer Tangle.

func NewMessage

func NewMessage(references ParentMessageIDs, issuingTime time.Time, issuerPublicKey ed25519.PublicKey,
	sequenceNumber uint64, msgPayload payload.Payload, nonce uint64, signature ed25519.Signature, versionOpt ...uint8) (*Message, error)

NewMessage creates a new message with the details provided by the issuer.

func (*Message) Bytes

func (m *Message) Bytes() []byte

Bytes returns a marshaled version of the Transaction.

func (*Message) ForEachParent added in v0.3.1

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

ForEachParent executes a consumer func for each parent.

func (*Message) ForEachParentByType added in v0.8.0

func (m *Message) ForEachParentByType(parentType ParentsType, consumer func(parentMessageID MessageID) bool)

ForEachParentByType executes a consumer func for each strong parent.

func (*Message) FromBytes added in v0.8.10

func (m *Message) FromBytes(data []byte) (*Message, error)

FromBytes unmarshals a Transaction from a sequence of bytes.

func (*Message) FromObjectStorage added in v0.8.10

func (m *Message) FromObjectStorage(key, value []byte) (result objectstorage.StorableObject, err error)

FromObjectStorage creates a Message from sequences of key and bytes.

func (*Message) ID

func (m *Message) ID() (result MessageID)

ID returns the id of the message which is made up of the content id and parent1/parent2 ids. This id can be used for merkle proofs.

func (*Message) IDBytes added in v0.6.2

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

IDBytes implements Element interface in scheduler NodeQueue that returns the MessageID of the message in bytes.

func (*Message) IssuerPublicKey

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

IssuerPublicKey returns the public key of the message issuer.

func (*Message) IssuingTime

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

IssuingTime returns the time when this message was created.

func (*Message) Nonce

func (m *Message) Nonce() uint64

Nonce returns the Nonce of the message.

func (*Message) ObjectStorageKey

func (m *Message) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*Message) ObjectStorageValue

func (m *Message) ObjectStorageValue() []byte

ObjectStorageValue marshals the Output into a sequence of bytes. The ID is not serialized here as it is only used as a key in the ObjectStorage.

func (*Message) ParentsByType added in v0.8.0

func (m *Message) ParentsByType(parentType ParentsType) MessageIDs

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

func (*Message) ParentsCountByType added in v0.8.0

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

ParentsCountByType returns the total parents count of this message.

func (*Message) Payload

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

Payload returns the Payload of the message.

func (*Message) SequenceNumber

func (m *Message) SequenceNumber() uint64

SequenceNumber returns the sequence number of this message.

func (*Message) Signature

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

Signature returns the Signature of the message.

func (*Message) Size added in v0.6.2

func (m *Message) Size() int

Size returns the message size in bytes.

func (*Message) String

func (m *Message) String() string

func (*Message) VerifySignature

func (m *Message) VerifySignature() bool

VerifySignature verifies the Signature of the message.

func (*Message) Version added in v0.3.1

func (m *Message) Version() uint8

Version returns the message Version.

type MessageFactory

type MessageFactory struct {
	Events *MessageFactoryEvents
	// contains filtered or unexported fields
}

MessageFactory acts as a factory to create new messages.

func NewMessageFactory

func NewMessageFactory(tangle *Tangle, selector TipSelector, referencesFunc ReferencesFunc) *MessageFactory

NewMessageFactory creates a new message factory.

func (*MessageFactory) IssuePayload

func (f *MessageFactory) IssuePayload(p payload.Payload, parentsCount ...int) (*Message, error)

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

func (*MessageFactory) IssuePayloadWithReferences added in v0.8.10

func (f *MessageFactory) IssuePayloadWithReferences(p payload.Payload, references ParentMessageIDs) (*Message, error)

IssuePayloadWithReferences creates a new message with the references submit.

func (*MessageFactory) SetTimeout added in v0.6.2

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

SetTimeout sets the timeout for PoW.

func (*MessageFactory) SetWorker

func (f *MessageFactory) SetWorker(worker Worker)

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

func (*MessageFactory) Shutdown

func (f *MessageFactory) Shutdown()

Shutdown closes the MessageFactory and persists the sequence number.

type MessageFactoryEvents

type MessageFactoryEvents struct {
	// Fired when a message is built including tips, sequence number and other metadata.
	MessageConstructed *events.Event

	// MessageReferenceImpossible is fired when references for a message can't be constructed and the message can never become a parent.
	MessageReferenceImpossible *events.Event

	// Fired when an error occurred.
	Error *events.Event
}

MessageFactoryEvents represents events happening on a message factory.

type MessageFilter

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

MessageFilter filters based on messages and peers.

type MessageID

type MessageID [MessageIDLength]byte

MessageID identifies a message via its BLAKE2b-256 hash of its bytes.

func MessageIDFromBytes

func MessageIDFromBytes(data []byte) (result MessageID, consumedBytes int, err error)

MessageIDFromBytes unmarshals a message id from a sequence of bytes.

func NewMessageID

func NewMessageID(base58EncodedString string) (result MessageID, err error)

NewMessageID creates a new message id.

func ReferenceFromMarshalUtil added in v0.8.0

func ReferenceFromMarshalUtil(marshalUtil *marshalutil.MarshalUtil) (MessageID, error)

ReferenceFromMarshalUtil is a wrapper for simplified unmarshaling in a byte stream using the marshalUtil package.

func (MessageID) Base58 added in v0.5.7

func (id MessageID) Base58() string

Base58 returns a base58 encoded Version of the MessageID.

func (MessageID) Bytes

func (id MessageID) Bytes() []byte

Bytes returns the bytes of the MessageID.

func (MessageID) CompareTo added in v0.8.0

func (id MessageID) CompareTo(other MessageID) int

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

func (*MessageID) MarshalBinary

func (id *MessageID) MarshalBinary() (result []byte, err error)

MarshalBinary marshals the MessageID into bytes.

func (MessageID) String

func (id MessageID) String() string

String returns a human readable representation of the MessageID.

func (*MessageID) UnmarshalBinary

func (id *MessageID) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary unmarshals the bytes into an MessageID.

type MessageIDs added in v0.3.1

type MessageIDs map[MessageID]types.Empty

MessageIDs is a set of MessageIDs where every MessageID is stored only once.

func NewMessageIDs added in v0.8.6

func NewMessageIDs(msgIDs ...MessageID) MessageIDs

NewMessageIDs construct a new MessageID collection from the optional MessageIDs.

func (MessageIDs) Add added in v0.8.6

func (m MessageIDs) Add(messageID MessageID) MessageIDs

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

func (MessageIDs) AddAll added in v0.8.6

func (m MessageIDs) AddAll(messageIDs MessageIDs) MessageIDs

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

func (MessageIDs) Base58 added in v0.8.10

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

Base58 returns a string slice of base58 MessageID.

func (MessageIDs) Clone added in v0.8.6

func (m MessageIDs) Clone() (clonedMessageIDs MessageIDs)

Clone creates a copy of the MessageIDs.

func (MessageIDs) Contains added in v0.8.10

func (m MessageIDs) Contains(target MessageID) (contains bool)

Contains checks if the given target MessageID is part of the MessageIDs.

func (MessageIDs) Empty added in v0.8.11

func (m MessageIDs) Empty() (empty bool)

Empty checks if MessageIDs is empty.

func (MessageIDs) First added in v0.8.10

func (m MessageIDs) First() MessageID

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

func (MessageIDs) Slice added in v0.8.6

func (m MessageIDs) Slice() []MessageID

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

func (MessageIDs) String added in v0.8.10

func (m MessageIDs) String() string

String returns a human-readable Version of the MessageIDs.

func (MessageIDs) Subtract added in v0.8.11

func (m MessageIDs) Subtract(other MessageIDs) MessageIDs

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

type MessageInvalidEvent added in v0.7.6

type MessageInvalidEvent struct {
	MessageID MessageID
	Error     error
}

MessageInvalidEvent is struct that is passed along with triggering a messageInvalidEvent.

type MessageMetadata

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

MessageMetadata defines the metadata for a message.

func NewMessageMetadata

func NewMessageMetadata(messageID MessageID) *MessageMetadata

NewMessageMetadata creates a new MessageMetadata from the specified messageID.

func (*MessageMetadata) AddBranchID added in v0.8.10

func (m *MessageMetadata) AddBranchID(branchID ledgerstate.BranchID) (modified bool)

AddBranchID sets the BranchIDs of the added Branches.

func (*MessageMetadata) AddedBranchIDs added in v0.8.6

func (m *MessageMetadata) AddedBranchIDs() ledgerstate.BranchIDs

AddedBranchIDs returns the BranchIDs of the added Branches of the Message.

func (*MessageMetadata) BookedTime added in v0.5.3

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

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

func (*MessageMetadata) Bytes

func (m *MessageMetadata) Bytes() []byte

Bytes returns a marshaled Version of the whole MessageMetadata object.

func (*MessageMetadata) DiscardedTime added in v0.8.4

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

DiscardedTime returns when the message was discarded.

func (*MessageMetadata) FromBytes added in v0.8.10

func (m *MessageMetadata) FromBytes(data []byte) (result *MessageMetadata, err error)

FromBytes unmarshals the given bytes into a MessageMetadata.

func (*MessageMetadata) FromObjectStorage added in v0.8.10

func (m *MessageMetadata) FromObjectStorage(key, value []byte) (objectstorage.StorableObject, error)

FromObjectStorage creates an MessageMetadata from sequences of key and bytes.

func (*MessageMetadata) GradeOfFinality added in v0.8.0

func (m *MessageMetadata) GradeOfFinality() (result gof.GradeOfFinality)

GradeOfFinality returns the grade of finality.

func (*MessageMetadata) GradeOfFinalityTime added in v0.8.0

func (m *MessageMetadata) GradeOfFinalityTime() time.Time

GradeOfFinalityTime returns the time the grade of finality was set.

func (*MessageMetadata) ID added in v0.3.6

func (m *MessageMetadata) ID() MessageID

ID returns the MessageID of the Message that this MessageMetadata object belongs to.

func (*MessageMetadata) IsBooked added in v0.3.6

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

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

func (*MessageMetadata) IsObjectivelyInvalid added in v0.8.6

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

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

func (*MessageMetadata) IsSolid

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

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

func (*MessageMetadata) IsSubjectivelyInvalid added in v0.8.6

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

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

func (*MessageMetadata) ObjectStorageKey

func (m *MessageMetadata) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*MessageMetadata) ObjectStorageValue

func (m *MessageMetadata) ObjectStorageValue() []byte

ObjectStorageValue marshals the MessageMetadata into a sequence of bytes. The ID is not serialized here as it is only used as a key in the ObjectStorage.

func (*MessageMetadata) QueuedTime added in v0.8.4

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

QueuedTime returns the time a message entered the scheduling queue.

func (*MessageMetadata) ReceivedTime

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

ReceivedTime returns the time when the message was received.

func (*MessageMetadata) Scheduled added in v0.4.0

func (m *MessageMetadata) Scheduled() (result bool)

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

func (*MessageMetadata) ScheduledTime added in v0.5.3

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

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

func (*MessageMetadata) SetAddedBranchIDs added in v0.8.6

func (m *MessageMetadata) SetAddedBranchIDs(addedBranchIDs ledgerstate.BranchIDs) (modified bool)

SetAddedBranchIDs sets the BranchIDs of the added Branches.

func (*MessageMetadata) SetBooked added in v0.3.6

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

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

func (*MessageMetadata) SetDiscardedTime added in v0.8.4

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

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

func (*MessageMetadata) SetGradeOfFinality added in v0.8.0

func (m *MessageMetadata) SetGradeOfFinality(gradeOfFinality gof.GradeOfFinality) (modified bool)

SetGradeOfFinality sets the grade of finality associated with this metadata. It returns true if the grade of finality is modified. False otherwise.

func (*MessageMetadata) SetObjectivelyInvalid added in v0.8.6

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

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

func (*MessageMetadata) SetQueuedTime added in v0.8.4

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

SetQueuedTime records the time the message entered the scheduler queue.

func (*MessageMetadata) SetScheduled added in v0.4.0

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

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

func (*MessageMetadata) SetSolid

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

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

func (*MessageMetadata) SetStructureDetails added in v0.3.6

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

SetStructureDetails sets the structureDetails of the message.

func (*MessageMetadata) SetSubjectivelyInvalid added in v0.8.6

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

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

func (*MessageMetadata) SetSubtractedBranchIDs added in v0.8.6

func (m *MessageMetadata) SetSubtractedBranchIDs(subtractedBranchIDs ledgerstate.BranchIDs) (modified bool)

SetSubtractedBranchIDs sets the BranchIDs of the subtracted Branches.

func (*MessageMetadata) SolidificationTime

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

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

func (*MessageMetadata) String added in v0.4.0

func (m *MessageMetadata) String() string

String returns a human-readable Version of the MessageMetadata.

func (*MessageMetadata) StructureDetails added in v0.3.6

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

StructureDetails returns the structureDetails of the message.

func (*MessageMetadata) SubtractedBranchIDs added in v0.8.6

func (m *MessageMetadata) SubtractedBranchIDs() ledgerstate.BranchIDs

SubtractedBranchIDs returns the BranchIDs of the subtracted Branches of the Message.

type MessageOption added in v0.5.3

type MessageOption func(*MessageTestFrameworkMessageOptions)

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

func WithColoredOutput added in v0.5.3

func WithColoredOutput(alias string, balances map[ledgerstate.Color]uint64) MessageOption

WithColoredOutput returns a MessageOption that is used to define a colored Output for the Transaction in the Message.

func WithInputs added in v0.5.3

func WithInputs(inputAliases ...string) MessageOption

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

func WithIssuer added in v0.5.7

func WithIssuer(issuer ed25519.PublicKey) MessageOption

WithIssuer returns a MessageOption that is used to define the issuer of the Message.

func WithIssuingTime added in v0.8.0

func WithIssuingTime(issuingTime time.Time) MessageOption

WithIssuingTime returns a MessageOption that is used to set issuing time of the Message.

func WithOutput added in v0.5.3

func WithOutput(alias string, balance uint64) MessageOption

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

func WithReattachment added in v0.8.0

func WithReattachment(messageAlias string) MessageOption

WithReattachment returns a MessageOption that is used to select payload of which Message should be reattached.

func WithSequenceNumber added in v0.8.6

func WithSequenceNumber(sequenceNumber uint64) MessageOption

WithSequenceNumber returns a MessageOption that is used to define the sequence number of the Message.

func WithShallowDislikeParents added in v0.8.6

func WithShallowDislikeParents(messageAliases ...string) MessageOption

WithShallowDislikeParents returns a MessageOption that is used to define the shallow dislike parents of the Message.

func WithShallowLikeParents added in v0.8.6

func WithShallowLikeParents(messageAliases ...string) MessageOption

WithShallowLikeParents returns a MessageOption that is used to define the shallow like parents of the Message.

func WithStrongParents added in v0.5.3

func WithStrongParents(messageAliases ...string) MessageOption

WithStrongParents returns a MessageOption that is used to define the strong parents of the Message.

func WithWeakParents added in v0.5.3

func WithWeakParents(messageAliases ...string) MessageOption

WithWeakParents returns a MessageOption that is used to define the weak parents of the Message.

type MessageParsedEvent

type MessageParsedEvent struct {
	// Message contains the parsed Message.
	Message *Message

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

MessageParsedEvent holds the information provided by the MessageParsed event that gets triggered when a message was fully parsed and syntactically validated.

type MessageRejectedEvent

type MessageRejectedEvent struct {
	Message *Message
	Peer    *peer.Peer
}

MessageRejectedEvent holds the information provided by the MessageRejected event that gets triggered when the Message was detected to be invalid.

type MessageSignatureFilter

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

MessageSignatureFilter filters messages based on whether their signatures are valid.

func NewMessageSignatureFilter

func NewMessageSignatureFilter() *MessageSignatureFilter

NewMessageSignatureFilter creates a new message signature filter.

func (*MessageSignatureFilter) Close added in v0.7.6

func (f *MessageSignatureFilter) Close() error

Close closes the filter.

func (*MessageSignatureFilter) Filter

func (f *MessageSignatureFilter) Filter(msg *Message, 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 (*MessageSignatureFilter) OnAccept

func (f *MessageSignatureFilter) OnAccept(callback func(msg *Message, peer *peer.Peer))

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

func (*MessageSignatureFilter) OnReject

func (f *MessageSignatureFilter) OnReject(callback func(msg *Message, err error, peer *peer.Peer))

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

type MessageTestFramework added in v0.5.3

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

MessageTestFramework implements a framework for conveniently issuing messages in a tangle as part of unit tests in a simplified way.

func NewMessageTestFramework added in v0.5.3

func NewMessageTestFramework(tangle *Tangle, options ...MessageTestFrameworkOption) (messageTestFramework *MessageTestFramework)

NewMessageTestFramework is the constructor of the MessageTestFramework.

func (*MessageTestFramework) Branch added in v0.8.0

func (m *MessageTestFramework) Branch(messageAlias string) (b *ledgerstate.Branch)

Branch returns the branch emerging from the transaction contained within the given message. This function thus only works on the message creating ledgerstate.Branch. Panics if the message's payload isn't a transaction.

func (*MessageTestFramework) BranchID added in v0.5.7

func (m *MessageTestFramework) BranchID(alias string) (branchID ledgerstate.BranchID)

BranchID returns the BranchID registered with the given alias.

func (*MessageTestFramework) BranchIDFromMessage added in v0.8.0

func (m *MessageTestFramework) BranchIDFromMessage(messageAlias string) ledgerstate.BranchID

BranchIDFromMessage returns the BranchID of the Transaction contained in the Message associated with the given alias.

func (*MessageTestFramework) BranchIDs added in v0.8.6

func (m *MessageTestFramework) BranchIDs(aliases ...string) (branchIDs ledgerstate.BranchIDs)

BranchIDs returns the BranchIDs registered with the given aliases.

func (*MessageTestFramework) CreateMessage added in v0.5.3

func (m *MessageTestFramework) CreateMessage(messageAlias string, messageOptions ...MessageOption) (message *Message)

CreateMessage creates a Message with the given alias and MessageTestFrameworkMessageOptions.

func (*MessageTestFramework) IncreaseMarkersIndexCallback added in v0.5.7

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

IncreaseMarkersIndexCallback is the IncreaseMarkersIndexCallback that the MessageTestFramework uses to determine when to assign new Markers to messages.

func (*MessageTestFramework) IssueMessages added in v0.5.3

func (m *MessageTestFramework) IssueMessages(messageAliases ...string) *MessageTestFramework

IssueMessages stores the given Messages in the Storage and triggers the processing by the Tangle.

func (*MessageTestFramework) Message added in v0.5.3

func (m *MessageTestFramework) Message(alias string) (message *Message)

Message retrieves the Messages that is associated with the given alias.

func (*MessageTestFramework) MessageMetadata added in v0.5.7

func (m *MessageTestFramework) MessageMetadata(alias string) (messageMetadata *MessageMetadata)

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

func (*MessageTestFramework) OutputMetadata added in v0.8.0

func (m *MessageTestFramework) OutputMetadata(outputID ledgerstate.OutputID) (outMeta *ledgerstate.OutputMetadata)

OutputMetadata returns the given output metadata.

func (*MessageTestFramework) PreventNewMarkers added in v0.5.7

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

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

func (*MessageTestFramework) RegisterBranchID added in v0.8.0

func (m *MessageTestFramework) RegisterBranchID(alias, messageAlias string)

RegisterBranchID registers a BranchID from the given Messages' transactions with the MessageTestFramework and also an alias when printing the BranchID.

func (*MessageTestFramework) Transaction added in v0.8.0

func (m *MessageTestFramework) Transaction(messageAlias string) (tx *ledgerstate.Transaction)

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

func (*MessageTestFramework) TransactionID added in v0.5.7

func (m *MessageTestFramework) TransactionID(messageAlias string) ledgerstate.TransactionID

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

func (*MessageTestFramework) TransactionMetadata added in v0.8.0

func (m *MessageTestFramework) TransactionMetadata(messageAlias string) (txMeta *ledgerstate.TransactionMetadata)

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

func (*MessageTestFramework) WaitApprovalWeightProcessed added in v0.5.7

func (m *MessageTestFramework) WaitApprovalWeightProcessed() *MessageTestFramework

WaitApprovalWeightProcessed waits for all Messages to be processed by the ApprovalWeightManager.

func (*MessageTestFramework) WaitMessagesBooked added in v0.5.3

func (m *MessageTestFramework) WaitMessagesBooked() *MessageTestFramework

WaitMessagesBooked waits for all Messages to be processed by the Booker.

type MessageTestFrameworkMessageOptions added in v0.5.3

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

MessageTestFrameworkMessageOptions is a struct that represents a collection of options that can be set when creating a Message with the MessageTestFramework.

func NewMessageTestFrameworkMessageOptions added in v0.5.3

func NewMessageTestFrameworkMessageOptions(options ...MessageOption) (messageOptions *MessageTestFrameworkMessageOptions)

NewMessageTestFrameworkMessageOptions is the constructor for the MessageTestFrameworkMessageOptions.

type MessageTestFrameworkOption added in v0.5.3

type MessageTestFrameworkOption func(*MessageTestFrameworkOptions)

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

func WithColoredGenesisOutput added in v0.5.3

func WithColoredGenesisOutput(alias string, balances map[ledgerstate.Color]uint64) MessageTestFrameworkOption

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

func WithGenesisOutput added in v0.5.3

func WithGenesisOutput(alias string, balance uint64) MessageTestFrameworkOption

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

type MessageTestFrameworkOptions added in v0.5.3

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

MessageTestFrameworkOptions is a container that holds the values of all configurable options of the MessageTestFramework.

func NewMessageTestFrameworkOptions added in v0.5.3

func NewMessageTestFrameworkOptions(options ...MessageTestFrameworkOption) (frameworkOptions *MessageTestFrameworkOptions)

NewMessageTestFrameworkOptions is the constructor for the MessageTestFrameworkOptions.

type MissingMessage

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

MissingMessage represents a missing message.

func NewMissingMessage

func NewMissingMessage(messageID MessageID) *MissingMessage

NewMissingMessage creates new missing message with the specified messageID.

func (*MissingMessage) Bytes

func (m *MissingMessage) Bytes() []byte

Bytes returns a marshaled version of this MissingMessage.

func (*MissingMessage) FromBytes added in v0.8.10

func (m *MissingMessage) FromBytes(data []byte) (result *MissingMessage, err error)

FromBytes parses the given bytes into a MissingMessage.

func (*MissingMessage) FromObjectStorage added in v0.8.10

func (m *MissingMessage) FromObjectStorage(key, value []byte) (objectstorage.StorableObject, error)

FromObjectStorage creates an MissingMessage from sequences of key and bytes.

func (*MissingMessage) MessageID

func (m *MissingMessage) MessageID() MessageID

MessageID returns the id of the message.

func (*MissingMessage) MissingSince

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

MissingSince returns the time since when this message is missing.

func (*MissingMessage) ObjectStorageKey

func (m *MissingMessage) ObjectStorageKey() []byte

ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the StorableObject interface.

func (*MissingMessage) ObjectStorageValue

func (m *MissingMessage) ObjectStorageValue() []byte

ObjectStorageValue marshals the MissingMessage into a sequence of bytes. The ID is not serialized here as it is only used as a key in the ObjectStorage.

type MockConfirmationOracle added in v0.8.0

type MockConfirmationOracle struct{}

MockConfirmationOracle is a mock of a ConfirmationOracle.

func (*MockConfirmationOracle) Events added in v0.8.0

Events mocks its interface function.

func (*MockConfirmationOracle) FirstUnconfirmedMarkerIndex added in v0.8.6

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

FirstUnconfirmedMarkerIndex mocks its interface function.

func (*MockConfirmationOracle) IsBranchConfirmed added in v0.8.0

func (m *MockConfirmationOracle) IsBranchConfirmed(branchID ledgerstate.BranchID) bool

IsBranchConfirmed mocks its interface function.

func (*MockConfirmationOracle) IsMarkerConfirmed added in v0.8.0

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

IsMarkerConfirmed mocks its interface function.

func (*MockConfirmationOracle) IsMessageConfirmed added in v0.8.0

func (m *MockConfirmationOracle) IsMessageConfirmed(msgID MessageID) bool

IsMessageConfirmed mocks its interface function.

func (*MockConfirmationOracle) IsOutputConfirmed added in v0.8.0

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

IsOutputConfirmed mocks its interface function.

func (*MockConfirmationOracle) IsTransactionConfirmed added in v0.8.0

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

IsTransactionConfirmed mocks its interface function.

type MockWeightProvider added in v0.8.0

type MockWeightProvider struct{}

MockWeightProvider is a mock of a WeightProvider.

func (*MockWeightProvider) Shutdown added in v0.8.0

func (m *MockWeightProvider) Shutdown()

Shutdown mocks its interface function.

func (*MockWeightProvider) Update added in v0.8.0

func (m *MockWeightProvider) Update(t time.Time, nodeID identity.ID)

Update mocks its interface function.

func (*MockWeightProvider) Weight added in v0.8.0

func (m *MockWeightProvider) Weight(message *Message) (weight, totalWeight float64)

Weight mocks its interface function.

func (*MockWeightProvider) WeightsOfRelevantVoters added in v0.8.6

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

WeightsOfRelevantVoters mocks its interface function.

type NodeIdentities added in v0.8.0

type NodeIdentities map[string]*identity.Identity

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

type NodesActivityLog added in v0.8.13

type NodesActivityLog map[identity.ID]*ActivityLog

type OTVConsensusManager added in v0.8.0

type OTVConsensusManager struct {
	consensus.Mechanism
}

OTVConsensusManager is the component in charge of forming opinions about branches.

func NewOTVConsensusManager added in v0.8.0

func NewOTVConsensusManager(otvConsensusMechanism consensus.Mechanism) *OTVConsensusManager

NewOTVConsensusManager returns a new Mechanism.

type Opinion added in v0.3.6

type Opinion uint8

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

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

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

	// Rejected represents the Opinion that a given Branch 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 Tangle to configure its behavior.

func ApprovalWeights added in v0.5.7

func ApprovalWeights(weightProvider WeightProvider) Option

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

func CacheTimeProvider added in v0.7.3

func CacheTimeProvider(cacheTimeProvider *database.CacheTimeProvider) Option

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

func GenesisNode added in v0.5.2

func GenesisNode(genesisNodeBase58 string) Option

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

func Identity added in v0.3.6

func Identity(identity *identity.LocalIdentity) Option

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

func IncreaseMarkersIndexCallback added in v0.4.0

func IncreaseMarkersIndexCallback(callback markers.IncreaseIndexCallback) Option

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

func MergeBranches added in v0.8.6

func MergeBranches(mergeBranches bool) Option

MergeBranches is an Option for the Tangle that prevents the LedgerState from merging Branches.

func RateSetterConfig added in v0.6.2

func RateSetterConfig(params RateSetterParams) Option

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

func SchedulerConfig added in v0.6.2

func SchedulerConfig(config SchedulerParams) Option

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

func StartSynced added in v0.5.9

func StartSynced(startSynced bool) Option

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

func Store added in v0.3.6

func Store(store kvstore.KVStore) Option

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

func SyncTimeWindow added in v0.5.8

func SyncTimeWindow(syncTimeWindow time.Duration) Option

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

func TimeSinceConfirmationThreshold added in v0.8.10

func TimeSinceConfirmationThreshold(tscThreshold time.Duration) Option

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

func Width added in v0.5.2

func Width(width int) Option

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

type Options

type Options struct {
	Store                          kvstore.KVStore
	Identity                       *identity.LocalIdentity
	IncreaseMarkersIndexCallback   markers.IncreaseIndexCallback
	TangleWidth                    int
	GenesisNode                    *ed25519.PublicKey
	SchedulerParams                SchedulerParams
	RateSetterParams               RateSetterParams
	WeightProvider                 WeightProvider
	SyncTimeWindow                 time.Duration
	TimeSinceConfirmationThreshold time.Duration
	StartSynced                    bool
	CacheTimeProvider              *database.CacheTimeProvider
	LedgerState                    struct{ MergeBranches bool }
}

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

type Parent added in v0.3.1

type Parent struct {
	ID   MessageID
	Type ParentsType
}

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

type ParentMessageIDs added in v0.8.6

type ParentMessageIDs map[ParentsType]MessageIDs

ParentMessageIDs is a map of ParentType to MessageIDs.

func NewParentMessageIDs added in v0.8.6

func NewParentMessageIDs() ParentMessageIDs

NewParentMessageIDs constructs a new ParentMessageIDs.

func (ParentMessageIDs) Add added in v0.8.6

func (p ParentMessageIDs) Add(parentType ParentsType, messageID MessageID) ParentMessageIDs

Add adds a parent to the map.

func (ParentMessageIDs) AddAll added in v0.8.6

func (p ParentMessageIDs) AddAll(parentType ParentsType, messageIDs MessageIDs) ParentMessageIDs

AddAll adds a collection of parents to the map.

func (ParentMessageIDs) AddStrong added in v0.8.6

func (p ParentMessageIDs) AddStrong(messageID MessageID) ParentMessageIDs

AddStrong adds a strong parent to the map.

func (ParentMessageIDs) Clone added in v0.8.6

Clone returns a copy of map.

type ParentsType added in v0.8.0

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
	// ShallowDislikeParentType is the ParentsType for a shallow dislike parent.
	ShallowDislikeParentType
)

func (ParentsType) String added in v0.8.0

func (bp ParentsType) String() string

String returns string representation of ParentsType.

type Parser added in v0.3.6

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

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

func NewParser added in v0.3.6

func NewParser() (result *Parser)

NewParser creates a new Message parser.

func (*Parser) AddBytesFilter added in v0.3.6

func (p *Parser) AddBytesFilter(filter BytesFilter)

AddBytesFilter adds the given bytes filter to the parser.

func (*Parser) AddMessageFilter added in v0.3.6

func (p *Parser) AddMessageFilter(filter MessageFilter)

AddMessageFilter adds a new message filter to the parser.

func (*Parser) Parse added in v0.3.6

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

Parse parses the given message bytes.

func (*Parser) Setup added in v0.3.6

func (p *Parser) Setup()

Setup defines the flow of the parser.

func (*Parser) Shutdown added in v0.7.6

func (p *Parser) Shutdown()

Shutdown closes all the message filters.

type ParserEvents added in v0.3.6

type ParserEvents struct {
	// Fired when a message was parsed.
	MessageParsed *events.Event

	// Fired when submitted bytes are rejected by a filter.
	BytesRejected *events.Event

	// Fired when a message got rejected by a filter.
	MessageRejected *events.Event
}

ParserEvents represents events happening in the Parser.

type PowFilter

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

PowFilter is a message 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(msgBytes []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 added in v0.8.0

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 RateSetter added in v0.6.2

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

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

func NewRateSetter added in v0.6.2

func NewRateSetter(tangle *Tangle) *RateSetter

NewRateSetter returns a new RateSetter.

func (*RateSetter) Issue added in v0.6.2

func (r *RateSetter) Issue(message *Message) error

Issue submits a message to the local issuing queue.

func (*RateSetter) Rate added in v0.6.2

func (r *RateSetter) Rate() float64

Rate returns the rate of the rate setter.

func (*RateSetter) Setup added in v0.6.2

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 added in v0.6.2

func (r *RateSetter) Shutdown()

Shutdown shuts down the RateSetter.

func (*RateSetter) Size added in v0.6.2

func (r *RateSetter) Size() int

Size returns the size of the issuing queue.

type RateSetterEvents added in v0.6.2

type RateSetterEvents struct {
	MessageDiscarded *events.Event
}

RateSetterEvents represents events happening in the rate setter.

type RateSetterParams added in v0.6.2

type RateSetterParams struct {
	Initial *float64
}

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 ReferencesFunc added in v0.8.6

type ReferencesFunc func(strongParents MessageIDs, issuingTime time.Time, tangle *Tangle) (references ParentMessageIDs, referenceNotPossible MessageIDs, err error)

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

type Requester added in v0.3.6

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

Requester takes care of requesting messages.

func NewRequester added in v0.3.6

func NewRequester(tangle *Tangle, optionalOptions ...RequesterOption) *Requester

NewRequester creates a new message requester.

func (*Requester) RequestQueueSize added in v0.3.6

func (r *Requester) RequestQueueSize() int

RequestQueueSize returns the number of scheduled message requests.

func (*Requester) Setup added in v0.3.6

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 added in v0.8.1

func (r *Requester) Shutdown()

Shutdown shuts down the Requester.

func (*Requester) StartRequest added in v0.3.6

func (r *Requester) StartRequest(id MessageID)

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

func (*Requester) StopRequest added in v0.3.6

func (r *Requester) StopRequest(id MessageID)

StopRequest stops requests for the given message to further happen.

type RequesterEvents added in v0.8.1

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

	// RequestStarted is an event that is triggered when a new request is started.
	RequestStarted *events.Event

	// RequestStopped is an event that is triggered when a request is stopped.
	RequestStopped *events.Event

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

RequesterEvents represents events happening on a message requester.

type RequesterOption added in v0.3.6

type RequesterOption func(*RequesterOptions)

RequesterOption is a function which inits an option.

func MaxRequestThreshold added in v0.8.1

func MaxRequestThreshold(maxRequestThreshold int) RequesterOption

MaxRequestThreshold creates an option which defines how often the Requester should try to request messages 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 added in v0.8.1

func RetryJitter(retryJitter time.Duration) RequesterOption

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

type RequesterOptions added in v0.3.6

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

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

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

RequesterOptions holds options for a message requester.

func (RequesterOptions) Apply added in v0.8.1

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

Apply applies the optional Options to the RequesterOptions.

type Scheduler added in v0.3.6

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

Scheduler is a Tangle component that takes care of scheduling the messages that shall be booked.

func NewScheduler added in v0.3.6

func NewScheduler(tangle *Tangle) *Scheduler

NewScheduler returns a new Scheduler.

func (*Scheduler) AccessManaCache added in v0.8.4

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

AccessManaCache returns the object which caches access mana values.

func (*Scheduler) BufferSize added in v0.8.4

func (s *Scheduler) BufferSize() int

BufferSize returns the size of the buffer.

func (*Scheduler) Clear added in v0.6.2

func (s *Scheduler) Clear()

Clear removes all submitted messages (ready or not) from the scheduler. The MessageDiscarded event is triggered for each of these messages.

func (*Scheduler) GetManaFromCache added in v0.8.4

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

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

func (*Scheduler) MaxBufferSize added in v0.8.4

func (s *Scheduler) MaxBufferSize() int

MaxBufferSize returns the max size of the buffer.

func (*Scheduler) NodeQueueSize added in v0.6.2

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

NodeQueueSize returns the size of the nodeIDs queue.

func (*Scheduler) NodeQueueSizes added in v0.6.2

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

NodeQueueSizes returns the size for each node queue.

func (*Scheduler) Rate added in v0.6.2

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

Rate gets the rate of the scheduler.

func (*Scheduler) Ready added in v0.6.2

func (s *Scheduler) Ready(messageID MessageID) (err error)

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

func (*Scheduler) ReadyMessagesCount added in v0.8.4

func (s *Scheduler) ReadyMessagesCount() int

ReadyMessagesCount returns the size buffer.

func (*Scheduler) Running added in v0.6.2

func (s *Scheduler) Running() bool

Running returns true if the scheduler has started.

func (*Scheduler) SetRate added in v0.6.2

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

SetRate sets the rate of the scheduler.

func (*Scheduler) Setup added in v0.3.6

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 added in v0.3.6

func (s *Scheduler) Shutdown()

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

func (*Scheduler) Start added in v0.6.2

func (s *Scheduler) Start()

Start starts the scheduler.

func (*Scheduler) Submit added in v0.6.2

func (s *Scheduler) Submit(messageID MessageID) (err error)

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

func (*Scheduler) SubmitAndReady added in v0.6.2

func (s *Scheduler) SubmitAndReady(messageID MessageID) (err error)

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

func (*Scheduler) TotalMessagesCount added in v0.8.4

func (s *Scheduler) TotalMessagesCount() int

TotalMessagesCount returns the size buffer.

func (*Scheduler) Unsubmit added in v0.6.2

func (s *Scheduler) Unsubmit(messageID MessageID) (err error)

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

type SchedulerEvents added in v0.3.6

type SchedulerEvents struct {
	// MessageScheduled is triggered when a message is ready to be scheduled.
	MessageScheduled *events.Event
	// MessageDiscarded is triggered when a message is removed from the longest mana-scaled queue when the buffer is full.
	MessageDiscarded *events.Event
	// MessageSkipped is triggered when a message is confirmed before it's scheduled, and is skipped by the scheduler.
	MessageSkipped  *events.Event
	NodeBlacklisted *events.Event
	Error           *events.Event
}

SchedulerEvents represents events happening in the Scheduler.

type SchedulerParams added in v0.6.2

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

SchedulerParams defines the scheduler config parameters.

type SendRequestEvent

type SendRequestEvent struct {
	ID MessageID
}

SendRequestEvent represents the parameters of sendRequestEventHandler

type SimpleMockOnTangleVoting added in v0.8.0

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

SimpleMockOnTangleVoting is mock of OTV mechanism.

func (*SimpleMockOnTangleVoting) BranchLiked added in v0.8.6

func (o *SimpleMockOnTangleVoting) BranchLiked(branchID ledgerstate.BranchID) (branchLiked bool)

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

func (*SimpleMockOnTangleVoting) LikedConflictMember added in v0.8.6

func (o *SimpleMockOnTangleVoting) LikedConflictMember(branchID ledgerstate.BranchID) (likedBranchID ledgerstate.BranchID, conflictMembers ledgerstate.BranchIDs)

LikedConflictMember returns branches that are liked instead of a disliked branch as predefined.

type Solidifier added in v0.3.6

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

Solidifier is the Tangle's component that solidifies messages.

func NewSolidifier added in v0.3.6

func NewSolidifier(tangle *Tangle) (solidifier *Solidifier)

NewSolidifier is the constructor of the Solidifier.

func (*Solidifier) RetrieveMissingMessage added in v0.8.1

func (s *Solidifier) RetrieveMissingMessage(messageID MessageID) (messageWasMissing bool)

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

func (*Solidifier) Setup added in v0.3.6

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 added in v0.3.6

func (s *Solidifier) Solidify(messageID MessageID)

Solidify solidifies the given Message.

type SolidifierEvents added in v0.3.6

type SolidifierEvents struct {
	// MessageSolid is triggered when a message becomes solid, i.e. its past cone is known and solid.
	MessageSolid *events.Event

	// MessageMissing is triggered when a message references an unknown parent Message.
	MessageMissing *events.Event
}

SolidifierEvents represents events happening in the Solidifier.

type Storage added in v0.3.6

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

Storage represents the storage of messages.

func NewStorage added in v0.3.6

func NewStorage(tangle *Tangle) (storage *Storage)

NewStorage creates a new Storage.

func (*Storage) AllLatestMarkerVotes added in v0.8.6

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

AllLatestMarkerVotes retrieves all LatestMarkerVotes for the named Sequence.

func (*Storage) Approvers added in v0.3.6

func (s *Storage) Approvers(messageID MessageID, optionalApproverType ...ApproverType) (cachedApprovers objectstorage.CachedObjects[*Approver])

Approvers retrieves the Approvers of a Message from the object storage. It is possible to provide an optional ApproverType to only return the corresponding Approvers.

func (*Storage) AttachmentMessageIDs added in v0.3.6

func (s *Storage) AttachmentMessageIDs(transactionID ledgerstate.TransactionID) (messageIDs MessageIDs)

AttachmentMessageIDs returns the messageIDs of the transaction in attachmentStorage.

func (*Storage) Attachments added in v0.3.6

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

Attachments retrieves the attachment of a transaction in attachmentStorage.

func (*Storage) BranchVoters added in v0.8.6

func (s *Storage) BranchVoters(branchID ledgerstate.BranchID, computeIfAbsentCallback ...func(branchID ledgerstate.BranchID) *BranchVoters) *objectstorage.CachedObject[*BranchVoters]

BranchVoters retrieves the BranchVoters with the given ledgerstate.BranchID.

func (*Storage) BranchWeight added in v0.5.7

func (s *Storage) BranchWeight(branchID ledgerstate.BranchID, computeIfAbsentCallback ...func(branchID ledgerstate.BranchID) *BranchWeight) *objectstorage.CachedObject[*BranchWeight]

BranchWeight retrieves the BranchWeight with the given BranchID.

func (*Storage) DBStats added in v0.3.6

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

DBStats returns the number of solid messages and total number of messages in the database (messageMetadataStorage, that should contain the messages as messageStorage), the number of messages in missingMessageStorage, furthermore the average time it takes to solidify messages.

func (*Storage) DeleteMarkerMessageMapping added in v0.5.7

func (s *Storage) DeleteMarkerMessageMapping(branchID ledgerstate.BranchID, messageID MessageID)

DeleteMarkerMessageMapping deleted a MarkerMessageMapping in the underlying object storage.

func (*Storage) DeleteMessage added in v0.3.6

func (s *Storage) DeleteMessage(messageID MessageID)

DeleteMessage deletes a message and its association to approvees by un-marking the given message as an approver.

func (*Storage) DeleteMissingMessage added in v0.3.6

func (s *Storage) DeleteMissingMessage(messageID MessageID)

DeleteMissingMessage deletes a message from the missingMessageStorage.

func (*Storage) IsTransactionAttachedByMessage added in v0.4.0

func (s *Storage) IsTransactionAttachedByMessage(transactionID ledgerstate.TransactionID, messageID MessageID) (attached bool)

IsTransactionAttachedByMessage checks whether Transaction with transactionID is attached by Message with messageID.

func (*Storage) LatestBranchVotes added in v0.8.6

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

LatestBranchVotes retrieves the LatestBranchVotes of the given Voter.

func (*Storage) LatestMarkerVotes added in v0.8.6

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) MarkerIndexBranchIDMapping added in v0.3.6

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

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

func (*Storage) MarkerMessageMapping added in v0.5.7

func (s *Storage) MarkerMessageMapping(marker *markers.Marker) (cachedMarkerMessageMappings *objectstorage.CachedObject[*MarkerMessageMapping])

MarkerMessageMapping retrieves the MarkerMessageMapping associated with the given details.

func (*Storage) MarkerMessageMappings added in v0.5.7

func (s *Storage) MarkerMessageMappings(sequenceID markers.SequenceID) (cachedMarkerMessageMappings objectstorage.CachedObjects[*MarkerMessageMapping])

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

func (*Storage) Message added in v0.3.6

func (s *Storage) Message(messageID MessageID) *objectstorage.CachedObject[*Message]

Message retrieves a message from the message store.

func (*Storage) MessageMetadata added in v0.3.6

func (s *Storage) MessageMetadata(messageID MessageID, computeIfAbsentCallback ...func() *MessageMetadata) *objectstorage.CachedObject[*MessageMetadata]

MessageMetadata retrieves the MessageMetadata with the given MessageID.

func (*Storage) MissingMessages added in v0.3.6

func (s *Storage) MissingMessages() (ids []MessageID)

MissingMessages return the ids of messages in missingMessageStorage

func (*Storage) Prune added in v0.3.6

func (s *Storage) Prune() error

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

func (*Storage) RetrieveAllTips added in v0.3.6

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

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

func (*Storage) Setup added in v0.3.6

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 added in v0.3.6

func (s *Storage) Shutdown()

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

func (*Storage) StoreAttachment added in v0.3.6

func (s *Storage) StoreAttachment(transactionID ledgerstate.TransactionID, messageID MessageID) (cachedAttachment *objectstorage.CachedObject[*Attachment], stored bool)

StoreAttachment stores a new attachment if not already stored.

func (*Storage) StoreMarkerMessageMapping added in v0.5.7

func (s *Storage) StoreMarkerMessageMapping(markerMessageMapping *MarkerMessageMapping)

StoreMarkerMessageMapping stores a MarkerMessageMapping in the underlying object storage.

func (*Storage) StoreMessage added in v0.3.6

func (s *Storage) StoreMessage(message *Message)

StoreMessage stores a new message to the message store.

func (*Storage) StoreMissingMessage added in v0.3.6

func (s *Storage) StoreMissingMessage(missingMessage *MissingMessage) (cachedMissingMessage *objectstorage.CachedObject[*MissingMessage], stored bool)

StoreMissingMessage stores a new MissingMessage entry in the object storage.

type StorageEvents added in v0.3.6

type StorageEvents struct {
	// Fired when a message has been stored.
	MessageStored *events.Event

	// Fired when a message was removed from storage.
	MessageRemoved *events.Event

	// Fired when a message which was previously marked as missing was received.
	MissingMessageStored *events.Event
}

StorageEvents represents events happening on the message store.

type SyncChangedEvent added in v0.6.0

type SyncChangedEvent struct {
	Synced bool
}

SyncChangedEvent represents a sync changed event.

type Tangle

type Tangle struct {
	Options               *Options
	Parser                *Parser
	Storage               *Storage
	Solidifier            *Solidifier
	Scheduler             *Scheduler
	Dispatcher            *Dispatcher
	Booker                *Booker
	ApprovalWeightManager *ApprovalWeightManager
	TimeManager           *TimeManager
	OTVConsensusManager   *OTVConsensusManager
	TipManager            *TipManager
	Requester             *Requester
	MessageFactory        *MessageFactory
	LedgerState           *LedgerState
	Utils                 *Utils
	WeightProvider        WeightProvider
	Events                *Events
	ConfirmationOracle    ConfirmationOracle
	// contains filtered or unexported fields
}

Tangle is the central data structure of the IOTA protocol.

func New

func New(options ...Option) (tangle *Tangle)

New is the constructor for the Tangle.

func NewTestTangle added in v0.8.0

func NewTestTangle(options ...Option) *Tangle

NewTestTangle returns a Tangle instance with a testing schedulerConfig.

func (*Tangle) Configure added in v0.5.0

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

Configure modifies the configuration of the Tangle.

func (*Tangle) IssuePayload added in v0.5.0

func (t *Tangle) IssuePayload(p payload.Payload, parentsCount ...int) (message *Message, err error)

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

func (*Tangle) ProcessGossipMessage added in v0.3.6

func (t *Tangle) ProcessGossipMessage(messageBytes []byte, peer *peer.Peer)

ProcessGossipMessage is used to feed new Messages from the gossip layer into the Tangle.

func (*Tangle) Prune

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

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

func (*Tangle) Setup added in v0.3.6

func (t *Tangle) Setup()

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

func (*Tangle) Shutdown

func (t *Tangle) Shutdown()

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

func (*Tangle) Synced added in v0.5.0

func (t *Tangle) Synced() (synced bool)

Synced returns a boolean value that indicates if the node is fully synced and the Tangle has solidified all messages until the genesis.

type TestScenario added in v0.8.0

type TestScenario struct {
	Steps    []TestStep
	PostStep TestStep
	Tangle   *Tangle
	// contains filtered or unexported fields
}

TestScenario is a sequence of steps applied onto test scenario.

func ProcessMessageScenario added in v0.8.0

func ProcessMessageScenario(t *testing.T) *TestScenario

ProcessMessageScenario the approval weight and voter adjustments.

func ProcessMessageScenario2 added in v0.8.6

func ProcessMessageScenario2(t *testing.T) *TestScenario

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

func (*TestScenario) Cleanup added in v0.8.0

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

Cleanup cleans up the scenario.

func (*TestScenario) HasNext added in v0.8.0

func (s *TestScenario) HasNext() bool

HasNext returns whether the scenario has a next step.

func (*TestScenario) Next added in v0.8.0

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

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

func (*TestScenario) Setup added in v0.8.0

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

Setup sets up the scenario.

type TestStep added in v0.8.0

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

TestStep defines a test scenario step.

type TimeManager added in v0.5.8

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

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

func NewTimeManager added in v0.5.8

func NewTimeManager(tangle *Tangle) *TimeManager

NewTimeManager is the constructor for TimeManager.

func (*TimeManager) LastConfirmedMessage added in v0.5.8

func (t *TimeManager) LastConfirmedMessage() LastConfirmedMessage

LastConfirmedMessage returns the last confirmed message.

func (*TimeManager) Setup added in v0.5.8

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 added in v0.5.8

func (t *TimeManager) Shutdown()

Shutdown shuts down the TimeManager and persists its state.

func (*TimeManager) Start added in v0.7.3

func (t *TimeManager) Start()

Start starts the TimeManager.

func (*TimeManager) Synced added in v0.5.8

func (t *TimeManager) Synced() bool

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

func (*TimeManager) Time added in v0.5.8

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

Time returns the TangleTime, i.e., the issuing time of the last confirmed message.

type TimeManagerEvents added in v0.6.0

type TimeManagerEvents struct {
	// Fired when the nodes sync status changes.
	SyncChanged *events.Event
}

TimeManagerEvents represents events happening in the TimeManager.

type TimeRetrieverFunc added in v0.5.8

type TimeRetrieverFunc func() time.Time

TimeRetrieverFunc is a function type to retrieve the time.

type TimedTaskExecutor added in v0.5.1

type TimedTaskExecutor struct {
	*timedexecutor.TimedExecutor
	// contains filtered or unexported fields
}

TimedTaskExecutor is a TimedExecutor that internally manages the scheduled callbacks as tasks with a unique identifier. It allows to replace existing scheduled tasks and cancel them using the same identifier.

func NewTimedTaskExecutor added in v0.5.1

func NewTimedTaskExecutor(workerCount int) *TimedTaskExecutor

NewTimedTaskExecutor is the constructor of the TimedTaskExecutor.

func (*TimedTaskExecutor) Cancel added in v0.5.1

func (t *TimedTaskExecutor) Cancel(identifier interface{}) (canceled bool)

Cancel cancels a queued task.

func (*TimedTaskExecutor) ExecuteAfter added in v0.5.1

func (t *TimedTaskExecutor) ExecuteAfter(identifier interface{}, callback func(), delay time.Duration) *timedexecutor.ScheduledTask

ExecuteAfter executes the given function after the given delay.

func (*TimedTaskExecutor) ExecuteAt added in v0.5.1

func (t *TimedTaskExecutor) ExecuteAt(identifier interface{}, callback func(), executionTime time.Time) *timedexecutor.ScheduledTask

ExecuteAt executes the given function at the given time.

type TipEvent added in v0.4.0

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

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

type TipManager added in v0.3.6

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 added in v0.3.6

func NewTipManager(tangle *Tangle, tips ...MessageID) *TipManager

NewTipManager creates a new tip-selector.

func (*TipManager) AddTip added in v0.3.6

func (t *TipManager) AddTip(message *Message)

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

func (*TipManager) AllTips added in v0.8.0

func (t *TipManager) AllTips() MessageIDs

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

func (*TipManager) Setup added in v0.3.6

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 added in v0.5.1

func (t *TipManager) Shutdown()

Shutdown stops the TipManager.

func (*TipManager) TipCount added in v0.3.6

func (t *TipManager) TipCount() int

TipCount the amount of strong tips.

func (*TipManager) Tips added in v0.3.6

func (t *TipManager) Tips(p payload.Payload, countParents int) (parents MessageIDs, err error)

Tips returns count number of tips, maximum MaxParentsCount.

type TipManagerEvents added in v0.3.6

type TipManagerEvents struct {
	// Fired when a tip is added.
	TipAdded *events.Event

	// Fired when a tip is removed.
	TipRemoved *events.Event
}

TipManagerEvents represents events happening on the TipManager.

type TipSelector

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

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

type TipSelectorFunc

type TipSelectorFunc func(p payload.Payload, countParents int) (parents MessageIDs, err error)

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 MessageIDs, err error)

Tips calls f().

type TransactionFilter added in v0.3.6

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

TransactionFilter filters messages based on their timestamps and transaction timestamp.

func NewTransactionFilter added in v0.3.6

func NewTransactionFilter() *TransactionFilter

NewTransactionFilter creates a new transaction filter.

func (*TransactionFilter) Close added in v0.7.6

func (f *TransactionFilter) Close() error

Close closes the filter.

func (*TransactionFilter) Filter added in v0.3.6

func (f *TransactionFilter) Filter(msg *Message, peer *peer.Peer)

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

func (*TransactionFilter) OnAccept added in v0.3.6

func (f *TransactionFilter) OnAccept(callback func(msg *Message, peer *peer.Peer))

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

func (*TransactionFilter) OnReject added in v0.3.6

func (f *TransactionFilter) OnReject(callback func(msg *Message, err error, peer *peer.Peer))

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

type Utils added in v0.3.6

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

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

func NewUtils added in v0.3.6

func NewUtils(tangle *Tangle) (utils *Utils)

NewUtils is the constructor of the Utils component.

func (*Utils) AllBranchesLiked added in v0.8.6

func (u *Utils) AllBranchesLiked(branchIDs ledgerstate.BranchIDs) bool

AllBranchesLiked returs true if all the passed branches are liked.

func (*Utils) AllTransactionsApprovedByMessages added in v0.4.1

func (u *Utils) AllTransactionsApprovedByMessages(transactionIDs ledgerstate.TransactionIDs, messageIDs MessageIDs) (approved bool)

AllTransactionsApprovedByMessages checks if all Transactions were attached by at least one Message that was directly or indirectly approved by the given Message.

func (*Utils) ApprovingMessageIDs added in v0.3.6

func (u *Utils) ApprovingMessageIDs(messageID MessageID, optionalApproverType ...ApproverType) (approvingMessageIDs MessageIDs)

ApprovingMessageIDs returns the MessageIDs that approve a given Message. It accepts an optional ApproverType to filter the Approvers.

func (*Utils) ComputeIfTransaction added in v0.3.6

func (u *Utils) ComputeIfTransaction(messageID MessageID, compute func(ledgerstate.TransactionID)) (computed bool)

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

func (*Utils) FirstAttachment added in v0.8.0

func (u *Utils) FirstAttachment(transactionID ledgerstate.TransactionID) (oldestAttachmentTime time.Time, oldestAttachmentMessageID MessageID, err error)

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

func (*Utils) MessageApprovedBy added in v0.3.6

func (u *Utils) MessageApprovedBy(approvedMessageID MessageID, approvingMessageID MessageID) (approved bool)

MessageApprovedBy checks if the Message given by approvedMessageID is directly or indirectly approved by the Message given by approvingMessageID.

func (*Utils) TransactionApprovedByMessage added in v0.4.0

func (u *Utils) TransactionApprovedByMessage(transactionID ledgerstate.TransactionID, messageID MessageID) (approved bool)

TransactionApprovedByMessage checks if the Transaction was attached by at least one Message that was directly or indirectly approved by the given Message.

func (*Utils) WalkMessage added in v0.3.6

func (u *Utils) WalkMessage(callback func(message *Message, walker *walker.Walker[MessageID]), entryPoints MessageIDs, revisitElements ...bool)

WalkMessage is a generic Tangle walker that executes a custom callback for every visited Message, starting from the given entry points. It accepts an optional boolean parameter which can be set to true if a Message 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) WalkMessageAndMetadata added in v0.3.6

func (u *Utils) WalkMessageAndMetadata(callback func(message *Message, messageMetadata *MessageMetadata, walker *walker.Walker[MessageID]), entryPoints MessageIDs, revisitElements ...bool)

WalkMessageAndMetadata is a generic Tangle walker that executes a custom callback for every visited Message and MessageMetadata, starting from the given entry points. It accepts an optional boolean parameter which can be set to true if a Message 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) WalkMessageID added in v0.3.6

func (u *Utils) WalkMessageID(callback func(messageID MessageID, walker *walker.Walker[MessageID]), entryPoints MessageIDs, revisitElements ...bool)

WalkMessageID is a generic Tangle walker that executes a custom callback for every visited MessageID, starting from the given entry points. It accepts an optional boolean parameter which can be set to true if a Message 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) WalkMessageMetadata added in v0.3.6

func (u *Utils) WalkMessageMetadata(callback func(messageMetadata *MessageMetadata, walker *walker.Walker[MessageID]), entryPoints MessageIDs, revisitElements ...bool)

WalkMessageMetadata is a generic Tangle walker that executes a custom callback for every visited MessageMetadata, starting from the given entry points. It accepts an optional boolean parameter which can be set to true if a Message 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 added in v0.8.6

type VotePower = uint64

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

type Voter added in v0.8.6

type Voter = identity.ID

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

type Voters added in v0.8.6

type Voters struct {
	set.Set[Voter]
}

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

func NewVoters added in v0.8.6

func NewVoters() (voters *Voters)

NewVoters is the constructor of the Voters type.

func (*Voters) AddAll added in v0.8.6

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

AddAll adds all new Voters to the Set.

func (*Voters) Clone added in v0.8.6

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

Clone returns a copy of the Voters.

func (*Voters) Decode added in v0.8.13

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

Decode deserializes bytes into a valid object.

func (*Voters) Encode added in v0.8.13

func (v *Voters) Encode() ([]byte, error)

Encode returns a serialized byte slice of the object.

func (*Voters) Intersect added in v0.8.6

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

Intersect creates an intersection of two set of Voters.

func (*Voters) String added in v0.8.6

func (v *Voters) String() string

String returns a human-readable version of the Voters.

type WeightProvider added in v0.5.7

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

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

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

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

WeightProvider is an interface that allows the ApprovalWeightManager to determine approval weights of Messages 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 message 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(msg []byte) (uint64, error)

DoPOW calls f(msg).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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