flow

package
v0.29.6 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2023 License: AGPL-3.0 Imports: 35 Imported by: 28

Documentation

Overview

(c) 2019 Dapper Labs - ALL RIGHTS RESERVED

Index

Constants

View Source
const (
	ServiceEventSetup  = "setup"
	ServiceEventCommit = "commit"
)
View Source
const (
	// AddressLength is the size of an account address in bytes.
	// (n) is the size of an account address in bits.
	AddressLength = (linearCodeN + 7) >> 3
)
View Source
const DefaultApprovalRequestsThreshold = uint64(10)

threshold for re-requesting approvals: min height difference between the latest finalized block and the block incorporating a result

View Source
const DefaultChunkAssignmentAlpha = 3

DefaultChunkAssignmentAlpha is the default number of verifiers that should be assigned to each chunk.

View Source
const DefaultEmergencySealingActive = false

DefaultEmergencySealingActive is a flag which indicates when emergency sealing is active, this is a temporary measure to make fire fighting easier while seal & verification is under development.

View Source
const DefaultInitialWeight = 100

DefaultInitialWeight is the default initial weight for a node identity. It is equal to the default initial weight in the FlowIDTableStaking smart contract.

View Source
const DefaultMaxCollectionByteSize = 3_000_000 // ~3MB. This is should always be higher than the limit on single tx size.

DefaultMaxCollectionByteSize is the default maximum value for a collection byte size.

View Source
const DefaultMaxCollectionSize = 100

DefaultMaxCollectionSize is the default maximum number of transactions allowed inside a collection.

View Source
const DefaultMaxCollectionTotalGas = 10_000_000 // 10M

DefaultMaxCollectionTotalGas is the default maximum value for total gas allowed to be included in a collection.

View Source
const DefaultMaxTransactionByteSize = 1_500_000

DefaultMaxTransactionByteSize is the default maximum transaction byte size. (~1.5MB)

View Source
const DefaultMaxTransactionGasLimit = 9999

DefaultMaxTransactionGasLimit is the default maximum value for the transaction gas limit.

View Source
const DefaultProtocolVersion = 0

DefaultProtocolVersion is the default protocol version, indicating none was explicitly set during bootstrapping.

View Source
const DefaultRequiredApprovalsForSealConstruction = uint(1)

DefaultRequiredApprovalsForSealConstruction is the default number of approvals required to construct a candidate seal for subsequent inclusion in block. when set to 1, it requires at least 1 approval to build a seal when set to 0, it can build seal without any approval

View Source
const DefaultRequiredApprovalsForSealValidation = 0

DefaultRequiredApprovalsForSealValidation is the default number of approvals that should be present and valid for each chunk. Setting this to 0 will disable counting of chunk approvals this can be used temporarily to ease the migration to new chunk based sealing. TODO:

  • This value will result in consensus not depending on verification at all for sealing (no approvals required)
  • Full protocol should be +2/3 of all currently authorized verifiers.
View Source
const DefaultTransactionExpiry = 10 * 60

DefaultTransactionExpiry is the default expiry for transactions, measured in blocks. The default value is equivalent to 10 minutes for a 1-second block time.

Let E by the transaction expiry. If a transaction T specifies a reference block R with height H, then T may be included in any block B where: * R<-*B - meaning B has R as an ancestor, and * R.height < B.height <= R.height+E

View Source
const DefaultTransactionExpiryBuffer = 30

DefaultTransactionExpiryBuffer is the default buffer time between a transaction being ingested by a collection node and being included in a collection and block.

View Source
const DefaultValueLogGCFrequency = 10 * 60

DefaultValueLogGCFrequency is the default frequency in blocks that we call the badger value log GC. Equivalent to 10 mins for a 1 second block time

View Source
const DomainTagLength = 32

DomainTagLength is set to 32 bytes.

Signatures on Flow that needs to be scoped to a certain domain need to have the same length in order to avoid tag collision issues, when prefixing the message to sign.

View Source
const EpochSetupRandomSourceLength = 16

EpochSetupRandomSourceLength is the required length of the random source included in an EpochSetup service event.

View Source
const IdentifierLen = 32
View Source
const TransactionTagString = "FLOW-V0.0-transaction"

Variables

View Source
var (
	ErrSegmentMissingSeal        = fmt.Errorf("sealing segment failed sanity check: missing seal referenced by segment")
	ErrSegmentBlocksWrongLen     = fmt.Errorf("sealing segment failed sanity check: non-root sealing segment must have at least 2 blocks")
	ErrSegmentInvalidBlockHeight = fmt.Errorf("sealing segment failed sanity check: blocks must be in ascending order")
	ErrSegmentResultLookup       = fmt.Errorf("failed to lookup execution result")
	ErrSegmentSealLookup         = fmt.Errorf("failed to lookup seal")
)
View Source
var DummyStateCommitment = StateCommitment(hash.DummyHash)

DummyStateCommitment is an arbitrary value used in function failure cases, although it can represent a valid state commitment.

View Source
var EmptyAddress = Address{}

EmptyAddress is the default value of a variable of type Address

View Source
var ErrNoChunks = errors.New("execution result has no chunks")
View Source
var GenesisTime = time.Date(2018, time.December, 19, 22, 32, 30, 42, time.UTC)

GenesisTime defines the timestamp of the genesis block.

View Source
var TransactionDomainTag = paddedDomainTag(TransactionTagString)

TransactionDomainTag is the prefix of all signed transaction payloads.

The tag is the string `TransactionTagString` encoded as UTF-8 bytes, right padded to a total length of 32 bytes.

View Source
var (
	// ZeroID is the lowest value in the 32-byte ID space.
	ZeroID = Identifier{}
)

Functions

func CheckConcatSum

func CheckConcatSum(sum Identifier, fps ...Identifier) bool

func CheckMerkleRoot

func CheckMerkleRoot(root Identifier, ids ...Identifier) bool

func CompatibleAlgorithms

func CompatibleAlgorithms(sigAlgo crypto.SigningAlgorithm, hashAlgo hash.HashingAlgorithm) bool

CompatibleAlgorithms returns true if the signature and hash algorithms are compatible.

func EncodeAccountPrivateKey

func EncodeAccountPrivateKey(a AccountPrivateKey) ([]byte, error)

func EncodeAccountPublicKey

func EncodeAccountPublicKey(a AccountPublicKey) ([]byte, error)

func EncodeRuntimeAccountPublicKey

func EncodeRuntimeAccountPublicKey(a AccountPublicKey) ([]byte, error)

func EncodeRuntimeAccountPublicKeys

func EncodeRuntimeAccountPublicKeys(keys []AccountPublicKey) ([]cadence.Value, error)

func IdToCid

func IdToCid(f Identifier) cid.Cid

func IdsToBytes

func IdsToBytes(identifiers []Identifier) [][]byte

func ToDKGParticipantLookup

func ToDKGParticipantLookup(participants IdentityList, keys []crypto.PublicKey) (map[Identifier]DKGParticipant, error)

ToDKGParticipantLookup constructs a DKG participant lookup from an identity list and a key list. The identity list must be EXACTLY the same (order and contents) as that used when initializing the corresponding DKG instance.

Types

type Account

type Account struct {
	Address   Address
	Balance   uint64
	Keys      []AccountPublicKey
	Contracts map[string][]byte
}

Account represents an account on the Flow network.

An account can be an externally owned account or a contract account with code.

type AccountPrivateKey

type AccountPrivateKey struct {
	PrivateKey crypto.PrivateKey
	SignAlgo   crypto.SigningAlgorithm
	HashAlgo   hash.HashingAlgorithm
}

AccountPrivateKey is a private key associated with an account.

func DecodeAccountPrivateKey

func DecodeAccountPrivateKey(b []byte) (AccountPrivateKey, error)

func (AccountPrivateKey) MarshalJSON

func (a AccountPrivateKey) MarshalJSON() ([]byte, error)

func (AccountPrivateKey) PublicKey

func (a AccountPrivateKey) PublicKey(weight int) AccountPublicKey

PublicKey returns a weighted public key.

type AccountPublicKey

type AccountPublicKey struct {
	Index     int
	PublicKey crypto.PublicKey
	SignAlgo  crypto.SigningAlgorithm
	HashAlgo  hash.HashingAlgorithm
	SeqNumber uint64
	Weight    int
	Revoked   bool
}

AccountPublicKey is a public key associated with an account.

An account public key contains the public key, signing and hashing algorithms, and a key weight.

func DecodeAccountPublicKey

func DecodeAccountPublicKey(b []byte, index uint64) (AccountPublicKey, error)

func DecodeRuntimeAccountPublicKey

func DecodeRuntimeAccountPublicKey(b []byte, seqNumber uint64) (AccountPublicKey, error)

DecodeRuntimeAccountPublicKey decode bytes into AccountPublicKey but it is designed to accept byte-format used by Cadence runtime (currently same as SDK, but we don't want to keep explicit dependency on SDK)

func (AccountPublicKey) MarshalJSON

func (a AccountPublicKey) MarshalJSON() ([]byte, error)

func (*AccountPublicKey) UnmarshalJSON

func (a *AccountPublicKey) UnmarshalJSON(data []byte) error

func (AccountPublicKey) Validate

func (a AccountPublicKey) Validate() error

Validate returns an error if this account key is invalid.

An account key can be invalid for the following reasons: - It specifies an incompatible signature/hash algorithm pairing - (TODO) It specifies a negative key weight

type Address

type Address [AddressLength]byte

Address represents the 8 byte address of an account.

func BytesToAddress

func BytesToAddress(b []byte) Address

BytesToAddress returns Address with value b.

If b is larger than 8, b will be cropped from the left. If b is smaller than 8, b will be appended by zeroes at the front.

func HexToAddress

func HexToAddress(h string) Address

HexToAddress converts a hex string to an Address.

func (Address) Bytes

func (a Address) Bytes() []byte

Bytes returns the byte representation of the address.

func (Address) Hex

func (a Address) Hex() string

Hex returns the hex string representation of the address.

func (Address) HexWithPrefix

func (a Address) HexWithPrefix() string

HexWithPrefix returns the hex string representation of the address, including the 0x prefix.

func (Address) MarshalJSON

func (a Address) MarshalJSON() ([]byte, error)

func (Address) Short

func (a Address) Short() string

Short returns the string representation of the address with leading zeros removed.

func (Address) String

func (a Address) String() string

String returns the string representation of the address.

func (*Address) UnmarshalJSON

func (a *Address) UnmarshalJSON(data []byte) error

type AddressGenerator

type AddressGenerator interface {
	NextAddress() (Address, error)
	CurrentAddress() Address
	Bytes() []byte
	AddressCount() uint64 // returns the total number of addresses that have been generated so far
}

type AggregatedSignature

type AggregatedSignature struct {
	// List of signatures
	VerifierSignatures []crypto.Signature
	// List of signer identifiers
	SignerIDs IdentifierList
}

AggregatedSignature contains a set of of signatures from verifiers attesting to the validity of an execution result chunk. TODO: this will be replaced with BLS aggregation

func (*AggregatedSignature) CardinalitySignerSet

func (a *AggregatedSignature) CardinalitySignerSet() int

CardinalitySignerSet returns the number of _distinct_ signer IDs in the AggregatedSignature. We explicitly de-duplicate here to prevent repetition attacks.

func (*AggregatedSignature) HasSigner

func (a *AggregatedSignature) HasSigner(signerID Identifier) bool

HasSigner returns true if and only if signer's signature is part of this aggregated signature

type AssignmentList

type AssignmentList []IdentifierList

AssignmentList is a list of identifier lists. Each list of identifiers lists the identities that are part of the given cluster.

func (AssignmentList) EqualTo

func (al AssignmentList) EqualTo(other AssignmentList) bool

type Attestation

type Attestation struct {
	BlockID           Identifier // ID of the block included the collection
	ExecutionResultID Identifier // ID of the execution result
	ChunkIndex        uint64     // index of the approved chunk
}

Attestation confirms correctness of a chunk of an exec result

func (Attestation) ID

func (a Attestation) ID() Identifier

ID generates a unique identifier using attestation

type Block

type Block struct {
	Header  *Header
	Payload *Payload
}

Block (currently) includes the header, the payload hashes as well as the payload contents.

func Genesis

func Genesis(chainID ChainID) *Block

func (Block) Checksum

func (b Block) Checksum() Identifier

Checksum returns the checksum of the header.

func (Block) ID

func (b Block) ID() Identifier

ID returns the ID of the header.

func (*Block) SetPayload

func (b *Block) SetPayload(payload Payload)

SetPayload sets the payload and updates the payload hash.

func (Block) Valid

func (b Block) Valid() bool

Valid will check whether the block is valid bottom-up.

type BlockEvents

type BlockEvents struct {
	BlockID        Identifier
	BlockHeight    uint64
	BlockTimestamp time.Time
	Events         []Event
}

BlockEvents contains events emitted in a single block.

type BlockStatus

type BlockStatus int

BlockStatus represents the status of a block.

const (
	// BlockStatusUnknown indicates that the block status is not known.
	BlockStatusUnknown BlockStatus = iota
	// BlockStatusFinalized is the status of a finalized block.
	BlockStatusFinalized
	// BlockStatusSealed is the status of a sealed block.
	BlockStatusSealed
)

func (BlockStatus) String

func (s BlockStatus) String() string

String returns the string representation of a transaction status.

type Chain

type Chain interface {
	NewAddressGenerator() AddressGenerator
	AddressAtIndex(index uint64) (Address, error)
	ServiceAddress() Address
	BytesToAddressGenerator(b []byte) AddressGenerator
	IsValid(Address) bool
	IndexFromAddress(address Address) (uint64, error)
	String() string
	ChainID() ChainID
	// contains filtered or unexported methods
}

Chain is the interface for address generation implementations.

type ChainID

type ChainID string

A ChainID is a unique identifier for a specific Flow network instance.

Chain IDs are used used to prevent replay attacks and to support network-specific address generation.

const (
	// Mainnet is the chain ID for the mainnet chain.
	Mainnet ChainID = "flow-mainnet"

	// Testnet is the chain ID for the testnet chain.
	Testnet ChainID = "flow-testnet"
	// Sandboxnet is the chain ID for internal sandboxnet chain.
	Sandboxnet ChainID = "flow-sandboxnet"

	// Benchnet is the chain ID for the transient benchmarking chain.
	Benchnet ChainID = "flow-benchnet"
	// Localnet is the chain ID for the local development chain.
	Localnet ChainID = "flow-localnet"
	// Emulator is the chain ID for the emulated chain.
	Emulator ChainID = "flow-emulator"
	// BftTestnet is the chain ID for testing attack vector scenarios.
	BftTestnet ChainID = "flow-bft-test-net"

	// MonotonicEmulator is the chain ID for the emulated node chain with monotonic address generation.
	MonotonicEmulator ChainID = "flow-emulator-monotonic"
)

func (ChainID) Chain

func (c ChainID) Chain() Chain

Chain returns the Chain corresponding to the string input

func (ChainID) String

func (c ChainID) String() string

func (ChainID) Transient

func (c ChainID) Transient() bool

Transient returns whether the chain ID is for a transient network.

type Chunk

type Chunk struct {
	ChunkBody

	Index uint64 // chunk index inside the ER (starts from zero)
	// EndState inferred from next chunk or from the ER
	EndState StateCommitment
}

func (*Chunk) Checksum

func (ch *Chunk) Checksum() Identifier

Checksum provides a cryptographic commitment for a chunk content

func (*Chunk) ID

func (ch *Chunk) ID() Identifier

ID returns a unique id for this entity

type ChunkBody

type ChunkBody struct {
	CollectionIndex uint

	// execution info
	StartState      StateCommitment // start state when starting executing this chunk
	EventCollection Identifier      // Events generated by executing results
	BlockID         Identifier      // Block id of the execution result this chunk belongs to

	// Computation consumption info
	TotalComputationUsed uint64 // total amount of computation used by running all txs in this chunk
	NumberOfTransactions uint64 // number of transactions inside the collection
}

type ChunkDataPack

type ChunkDataPack struct {
	ChunkID    Identifier
	StartState StateCommitment
	Proof      StorageProof
	Collection *Collection
}

ChunkDataPack holds all register touches (any read, or write).

Note that we have to capture a read proof for each write before updating the registers. `Proof` includes proofs for all registers read to execute the chunck. Register proofs order must not be correlated to the order of register reads during the chunk execution in order to enforce the SPoCK secret high entropy.

func (*ChunkDataPack) Checksum

func (c *ChunkDataPack) Checksum() Identifier

Checksum returns the checksum of the chunk data pack.

func (*ChunkDataPack) ID

func (c *ChunkDataPack) ID() Identifier

ID returns the unique identifier for the concrete view, which is the ID of the chunk the view is for.

type ChunkList

type ChunkList []*Chunk

TODO: This is the basic version of the list, we need to substitute it with something like Merkle tree at some point

func (ChunkList) ByChecksum

func (cl ChunkList) ByChecksum(cs Identifier) (*Chunk, bool)

ByChecksum returns an entity from the list by entity fingerprint

func (ChunkList) ByIndex

func (cl ChunkList) ByIndex(i uint64) (*Chunk, bool)

ByIndex returns an entity from the list by index if requested chunk is within range of list, it returns chunk and true if requested chunk is out of the range, it returns nil and false boolean return value indicates whether requested chunk is within range

func (ChunkList) Empty

func (cl ChunkList) Empty() bool

Empty returns true if the chunk list is empty. Otherwise it returns false.

func (ChunkList) Fingerprint

func (cl ChunkList) Fingerprint() Identifier

func (ChunkList) Indices

func (cl ChunkList) Indices() []uint64

func (*ChunkList) Insert

func (cl *ChunkList) Insert(ch *Chunk)

func (ChunkList) Items

func (cl ChunkList) Items() []*Chunk

func (ChunkList) Len

func (cl ChunkList) Len() int

Len returns the number of Chunks in the list. It is also part of the sort interface that makes ChunkList sortable

type ClusterList

type ClusterList []IdentityList

ClusterList is a list of identity lists. Each `IdentityList` represents the nodes assigned to a specific cluster.

func NewClusterList

func NewClusterList(assignments AssignmentList, collectors IdentityList) (ClusterList, error)

NewClusterList creates a new cluster list based on the given cluster assignment and the provided list of identities.

func (ClusterList) Assignments

func (clusters ClusterList) Assignments() AssignmentList

Assignments returns the assignment list for a cluster.

func (ClusterList) ByIndex

func (cl ClusterList) ByIndex(index uint) (IdentityList, bool)

ByIndex retrieves the list of identities that are part of the given cluster.

func (ClusterList) ByNodeID

func (cl ClusterList) ByNodeID(nodeID Identifier) (IdentityList, uint, bool)

ByNodeID select the cluster that the node with the given ID is part of.

Nodes will be divided into equally sized clusters as far as possible. The last return value will indicate if the look up was successful

func (ClusterList) ByTxID

func (cl ClusterList) ByTxID(txID Identifier) (IdentityList, bool)

ByTxID selects the cluster that should receive the transaction with the given transaction ID.

For evenly distributed transaction IDs, this will evenly distribute transactions between clusters.

func (ClusterList) IndexOf

func (cl ClusterList) IndexOf(cluster IdentityList) (uint, bool)

IndexOf returns the index of the given cluster.

type ClusterQCVoteData

type ClusterQCVoteData struct {
	SigData  crypto.Signature // the aggregated signature over all the votes
	VoterIDs []Identifier     // the set of voters that contributed to the qc
}

ClusterQCVoteData represents the votes for a cluster quorum certificate, as gathered by the ClusterQC smart contract. It contains the aggregated signature over the root block for the cluster as well as the set of voters.

func ClusterQCVoteDataFromQC

func ClusterQCVoteDataFromQC(qc *QuorumCertificateWithSignerIDs) ClusterQCVoteData

ClusterQCVoteDataFromQC converts a quorum certificate to the representation used by the smart contract, essentially discarding the block ID and view (which are protocol-defined given the EpochSetup event).

func ClusterQCVoteDatasFromQCs

func ClusterQCVoteDatasFromQCs(qcs []*QuorumCertificateWithSignerIDs) []ClusterQCVoteData

func (*ClusterQCVoteData) EqualTo

func (c *ClusterQCVoteData) EqualTo(other *ClusterQCVoteData) bool

type Collection

type Collection struct {
	Transactions []*TransactionBody
}

Collection is set of transactions.

func CollectionFromTransactions

func CollectionFromTransactions(transactions []*Transaction) Collection

CollectionFromTransactions creates a new collection from the list of transactions.

func (Collection) Checksum

func (c Collection) Checksum() Identifier

func (Collection) Fingerprint

func (c Collection) Fingerprint() []byte

func (*Collection) Guarantee

func (c *Collection) Guarantee() CollectionGuarantee

Guarantee returns a collection guarantee for this collection.

func (Collection) ID

func (c Collection) ID() Identifier

func (Collection) Len

func (c Collection) Len() int

func (Collection) Light

func (c Collection) Light() LightCollection

Light returns the light, reference-only version of the collection.

type CollectionGuarantee

type CollectionGuarantee struct {
	CollectionID     Identifier       // ID of the collection being guaranteed
	ReferenceBlockID Identifier       // defines expiry of the collection
	ChainID          ChainID          // the chainID of the cluster in order to determine which cluster this guarantee belongs to
	SignerIndices    []byte           // encoded indices of the signers
	Signature        crypto.Signature // guarantor signatures
}

CollectionGuarantee is a signed hash for a collection, which is used to announce collections to consensus nodes.

func (*CollectionGuarantee) Checksum

func (cg *CollectionGuarantee) Checksum() Identifier

Checksum returns a checksum of the collection guarantee including the signatures.

func (*CollectionGuarantee) ID

ID returns the fingerprint of the collection guarantee.

type CollectionList

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

Note that this is the basic version of the List, we need to substitute it with something like Merkle tree at some point

func (*CollectionList) ByChecksum

func (cl *CollectionList) ByChecksum(cs Identifier) (*Collection, bool)

ByChecksum returns an entity from the list by entity fingerprint

func (*CollectionList) ByIndex

func (cl *CollectionList) ByIndex(i uint64) *Collection

ByIndex returns an entity from the list by index

func (*CollectionList) ByIndexWithProof

func (cl *CollectionList) ByIndexWithProof(i uint64) (*Collection, Proof)

ByIndexWithProof returns an entity from the list by index and proof of membership

func (*CollectionList) Fingerprint

func (cl *CollectionList) Fingerprint() Identifier

func (*CollectionList) Insert

func (cl *CollectionList) Insert(ch *Collection)

func (*CollectionList) Items

func (cl *CollectionList) Items() []*Collection

type DKGEndState

type DKGEndState uint32

DKGEndState captures the final state of a completed DKG.

const (
	// DKGEndStateUnknown - zero value for this enum, indicates unset value
	DKGEndStateUnknown DKGEndState = iota
	// DKGEndStateSuccess - the DKG completed, this node has a valid beacon key.
	DKGEndStateSuccess
	// DKGEndStateInconsistentKey - the DKG completed, this node has an invalid beacon key.
	DKGEndStateInconsistentKey
	// DKGEndStateNoKey - this node did not store a key, typically caused by a crash mid-DKG.
	DKGEndStateNoKey
	// DKGEndStateDKGFailure - the underlying DKG library reported an error.
	DKGEndStateDKGFailure
)

func (DKGEndState) String

func (state DKGEndState) String() string

type DKGParticipant

type DKGParticipant struct {
	Index    uint
	KeyShare crypto.PublicKey
}

func (DKGParticipant) EncodeRLP

func (part DKGParticipant) EncodeRLP(w io.Writer) error

func (DKGParticipant) MarshalCBOR

func (part DKGParticipant) MarshalCBOR() ([]byte, error)

func (DKGParticipant) MarshalJSON

func (part DKGParticipant) MarshalJSON() ([]byte, error)

func (DKGParticipant) MarshalMsgpack

func (part DKGParticipant) MarshalMsgpack() ([]byte, error)

func (*DKGParticipant) UnmarshalCBOR

func (part *DKGParticipant) UnmarshalCBOR(b []byte) error

func (*DKGParticipant) UnmarshalJSON

func (part *DKGParticipant) UnmarshalJSON(b []byte) error

func (*DKGParticipant) UnmarshalMsgpack

func (part *DKGParticipant) UnmarshalMsgpack(b []byte) error

type Entity

type Entity interface {

	// ID returns a unique id for this entity using a hash of the immutable
	// fields of the entity.
	ID() Identifier

	// Checksum returns a unique checksum for the entity, including the mutable
	// data such as signatures.
	Checksum() Identifier
}

Entity defines how flow entities should be defined Entities are flat data structures holding multiple data fields. Entities don't include nested entities, they only include pointers to other entities. For example, they keep a slice of entity commits instead of keeping a slice of entity object itself. This simplifies storage, signature and validation of entities.

type EntityList

type EntityList interface {
	EntitySet

	// HasIndex checks if the list has an entity at the given index.
	HasIndex(i uint) bool

	// ByIndex returns an entity from the list by index
	ByIndex(i uint) (Entity, bool)

	// ByIndexWithProof returns an entity from the list by index and proof of membership
	ByIndexWithProof(i uint) (Entity, Proof, bool)
}

EntityList is a list of entities of the same type

type EntitySet

type EntitySet interface {

	// Insert adds an entity to the data structure.
	Insert(Entity) bool

	// Remove removes an entity from the data structure.
	Remove(Entity) bool

	// Items returns all items of the collection.
	Items() []Entity

	// Size returns the number of entities in the data structure.
	Size() uint

	// Fingerprint returns a unique identifier for all entities of the data
	// structure.
	Fingerprint() Identifier

	// ByID returns the entity with the given fingerprint.
	ByID(id Identifier) (Entity, bool)

	// if the set has an specific member providing proof of membership
	ByIDWithProof(id Identifier) (bool, Proof, error)
}

EntitySet holds a set of entities (order doesn't matter)

type EpochCommit

type EpochCommit struct {
	Counter            uint64              // the number of the epoch
	ClusterQCs         []ClusterQCVoteData // quorum certificates for each cluster
	DKGGroupKey        crypto.PublicKey    // group key from DKG
	DKGParticipantKeys []crypto.PublicKey  // public keys for DKG participants
}

EpochCommit is a service event emitted when epoch setup has been completed. When an EpochCommit event is emitted, the network is ready to transition to the epoch.

func (*EpochCommit) EncodeRLP

func (commit *EpochCommit) EncodeRLP(w io.Writer) error

EncodeRLP encodes the commit as RLP. The RLP encoding needs to be handled differently from JSON/msgpack, because it does not handle custom encoders within map types. NOTE: DecodeRLP is not needed, as this is only used for hashing.

func (*EpochCommit) EqualTo

func (commit *EpochCommit) EqualTo(other *EpochCommit) bool

func (*EpochCommit) ID

func (commit *EpochCommit) ID() Identifier

ID returns the hash of the event contents.

func (*EpochCommit) MarshalCBOR

func (commit *EpochCommit) MarshalCBOR() ([]byte, error)

func (EpochCommit) MarshalJSON

func (commit EpochCommit) MarshalJSON() ([]byte, error)

func (*EpochCommit) MarshalMsgpack

func (commit *EpochCommit) MarshalMsgpack() ([]byte, error)

func (*EpochCommit) ServiceEvent

func (commit *EpochCommit) ServiceEvent() ServiceEvent

func (*EpochCommit) UnmarshalCBOR

func (commit *EpochCommit) UnmarshalCBOR(b []byte) error

func (*EpochCommit) UnmarshalJSON

func (commit *EpochCommit) UnmarshalJSON(b []byte) error

func (*EpochCommit) UnmarshalMsgpack

func (commit *EpochCommit) UnmarshalMsgpack(b []byte) error

type EpochPhase

type EpochPhase int

EpochPhase represents a phase of the Epoch Preparation Protocol. The phase of an epoch is resolved based on a block reference and is fork-dependent. An epoch begins in the staking phase, then transitions to the setup phase in the block containing the EpochSetup service event, then to the committed phase in the block containing the EpochCommit service event. |<-- EpochPhaseStaking -->|<-- EpochPhaseSetup -->|<-- EpochPhaseCommitted -->|<-- EpochPhaseStaking -->... |<------------------------------- Epoch N ------------------------------------>|<-- Epoch N + 1 --...

const (
	EpochPhaseUndefined EpochPhase = iota
	EpochPhaseStaking
	EpochPhaseSetup
	EpochPhaseCommitted
)

func GetEpochPhase

func GetEpochPhase(phase string) EpochPhase

func (EpochPhase) String

func (p EpochPhase) String() string

type EpochSetup

type EpochSetup struct {
	Counter            uint64         // the number of the epoch
	FirstView          uint64         // the first view of the epoch
	DKGPhase1FinalView uint64         // the final view of DKG phase 1
	DKGPhase2FinalView uint64         // the final view of DKG phase 2
	DKGPhase3FinalView uint64         // the final view of DKG phase 3
	FinalView          uint64         // the final view of the epoch
	Participants       IdentityList   // all participants of the epoch
	Assignments        AssignmentList // cluster assignment for the epoch
	RandomSource       []byte         // source of randomness for epoch-specific setup tasks
}

EpochSetup is a service event emitted when the network is ready to set up for the upcoming epoch. It contains the participants in the epoch, the length, the cluster assignment, and the seed for leader selection.

func (*EpochSetup) EqualTo

func (setup *EpochSetup) EqualTo(other *EpochSetup) bool

func (*EpochSetup) ID

func (setup *EpochSetup) ID() Identifier

ID returns the hash of the event contents.

func (*EpochSetup) ServiceEvent

func (setup *EpochSetup) ServiceEvent() ServiceEvent

type EpochStatus

type EpochStatus struct {
	PreviousEpoch EventIDs // EpochSetup and EpochCommit events for the previous epoch
	CurrentEpoch  EventIDs // EpochSetup and EpochCommit events for the current epoch
	NextEpoch     EventIDs // EpochSetup and EpochCommit events for the next epoch
}

EpochStatus represents the status of the current and next epoch with respect to a reference block. Concretely, it contains the IDs for all relevant service events emitted as of the reference block. Events not yet emitted are represented by ZeroID.

func NewEpochStatus

func NewEpochStatus(previousSetup, previousCommit, currentSetup, currentCommit, nextSetup, nextCommit Identifier) (*EpochStatus, error)

func (*EpochStatus) Check

func (es *EpochStatus) Check() error

Check checks that the status is well-formed, returning an error if it is not. All errors indicate a malformed EpochStatus.

func (*EpochStatus) Copy

func (es *EpochStatus) Copy() *EpochStatus

Copy returns a copy of the epoch status.

func (*EpochStatus) HasPrevious

func (es *EpochStatus) HasPrevious() bool

func (*EpochStatus) Phase

func (es *EpochStatus) Phase() (EpochPhase, error)

Phase returns the phase for the CURRENT epoch, given this epoch status. All errors indicate a malformed EpochStatus.

type Event

type Event struct {
	// Type is the qualified event type.
	Type EventType
	// TransactionID is the ID of the transaction this event was emitted from.
	TransactionID Identifier
	// TransactionIndex defines the index of the transaction this event was emitted from within the block.
	// The first transaction has index 0, the second has index 1, and so on.
	TransactionIndex uint32
	// EventIndex defines the ordering of events in a transaction.
	// The first event emitted has index 0, the second has index 1, and so on.
	EventIndex uint32
	// Payload contains the encoded event data.
	Payload []byte
}

func (Event) Checksum

func (e Event) Checksum() Identifier

func (Event) Encode

func (e Event) Encode() []byte

Encode returns the canonical encoding of this event, containing only the fields necessary to uniquely identify it.

func (Event) Fingerprint

func (e Event) Fingerprint() []byte

func (Event) ID

func (e Event) ID() Identifier

ID returns a canonical identifier that is guaranteed to be unique.

func (Event) String

func (e Event) String() string

String returns the string representation of this event.

type EventIDs

type EventIDs struct {
	// SetupID is the ID of the EpochSetup event for the respective Epoch
	SetupID Identifier
	// CommitID is the ID of the EpochCommit event for the respective Epoch
	CommitID Identifier
}

EventIDs is a container for IDs of epoch service events.

type EventType

type EventType string
const (
	EventAccountCreated EventType = "flow.AccountCreated"
	EventAccountUpdated EventType = "flow.AccountUpdated"
)

List of built-in event types.

type EventsList

type EventsList []Event

func (EventsList) ByteSize

func (el EventsList) ByteSize() int

byteSize returns an approximate number of bytes needed to store the wrapped version of the event.

type ExecutedTransaction

type ExecutedTransaction struct {
	Tx         *Transaction
	GasSpent   uint64
	MaxGas     uint64
	StartState StateCommitment
	EndState   StateCommitment
}

ExecutedTransaction are generated by computer and pass to chunker

type ExecutionReceipt

type ExecutionReceipt struct {
	ExecutorID        Identifier
	ExecutionResult   ExecutionResult
	Spocks            []crypto.Signature
	ExecutorSignature crypto.Signature
}

ExecutionReceipt is the full execution receipt, as sent by the Execution Node. Specifically, it contains the detailed execution result.

func ExecutionReceiptFromMeta

func ExecutionReceiptFromMeta(meta ExecutionReceiptMeta, result ExecutionResult) *ExecutionReceipt

func (*ExecutionReceipt) Checksum

func (er *ExecutionReceipt) Checksum() Identifier

Checksum returns a checksum for the execution receipt including the signatures.

func (*ExecutionReceipt) ID

func (er *ExecutionReceipt) ID() Identifier

ID returns the canonical ID of the execution receipt.

func (*ExecutionReceipt) Meta

Meta returns the receipt metadata for the receipt.

type ExecutionReceiptGroupedList

type ExecutionReceiptGroupedList map[Identifier]ExecutionReceiptList

ExecutionReceiptGroupedList is a partition of an ExecutionReceiptList

func (ExecutionReceiptGroupedList) GetGroup

GetGroup returns the receipts that were mapped to the same identifier by the grouping function. Returns an empty (nil) ExecutionReceiptList if groupID does not exist.

func (ExecutionReceiptGroupedList) NumberGroups

func (g ExecutionReceiptGroupedList) NumberGroups() int

NumberGroups returns the number of groups

type ExecutionReceiptGroupingFunction

type ExecutionReceiptGroupingFunction func(*ExecutionReceipt) Identifier

ExecutionReceiptGroupingFunction is a function that assigns an identifier to each receipt

type ExecutionReceiptList

type ExecutionReceiptList []*ExecutionReceipt

ExecutionReceiptList is a slice of ExecutionReceipts with the additional functionality to group receipts by various properties

func (ExecutionReceiptList) GroupBy

GroupBy partitions the ExecutionReceiptList. All receipts that are mapped by the grouping function to the same identifier are placed in the same group. Within each group, the order and multiplicity of the receipts is preserved.

func (ExecutionReceiptList) GroupByExecutorID

func (l ExecutionReceiptList) GroupByExecutorID() ExecutionReceiptGroupedList

GroupByExecutorID partitions the ExecutionReceiptList by the receipts' ExecutorIDs. Within each group, the order and multiplicity of the receipts is preserved.

func (ExecutionReceiptList) GroupByResultID

GroupByResultID partitions the ExecutionReceiptList by the receipts' Result IDs. Within each group, the order and multiplicity of the receipts is preserved.

func (ExecutionReceiptList) Size

func (l ExecutionReceiptList) Size() int

Size returns the number of receipts in the list

type ExecutionReceiptMeta

type ExecutionReceiptMeta struct {
	ExecutorID        Identifier
	ResultID          Identifier
	Spocks            []crypto.Signature
	ExecutorSignature crypto.Signature
}

ExecutionReceiptMeta contains the fields from the Execution Receipts that vary from one executor to another (assuming they commit to the same result). It only contains the ID (cryptographic hash) of the execution result the receipt commits to. The ExecutionReceiptMeta is useful for storing results and receipts separately in a composable way.

func (*ExecutionReceiptMeta) Checksum

func (er *ExecutionReceiptMeta) Checksum() Identifier

Checksum returns a checksum for the execution receipt including the signatures.

func (*ExecutionReceiptMeta) ID

ID returns the canonical ID of the execution receipt. It is identical to the ID of the full receipt.

func (ExecutionReceiptMeta) MarshalJSON

func (er ExecutionReceiptMeta) MarshalJSON() ([]byte, error)

type ExecutionReceiptMetaGroupedList

type ExecutionReceiptMetaGroupedList map[Identifier]ExecutionReceiptMetaList

ExecutionReceiptMetaGroupedList is a partition of an ExecutionReceiptMetaList

func (ExecutionReceiptMetaGroupedList) GetGroup

GetGroup returns the receipts that were mapped to the same identifier by the grouping function. Returns an empty (nil) ExecutionReceiptMetaList if groupID does not exist.

func (ExecutionReceiptMetaGroupedList) NumberGroups

func (g ExecutionReceiptMetaGroupedList) NumberGroups() int

NumberGroups returns the number of groups

type ExecutionReceiptMetaGroupingFunction

type ExecutionReceiptMetaGroupingFunction func(*ExecutionReceiptMeta) Identifier

ExecutionReceiptMetaGroupingFunction is a function that assigns an identifier to each receipt meta

type ExecutionReceiptMetaList

type ExecutionReceiptMetaList []*ExecutionReceiptMeta

ExecutionReceiptMetaList is a slice of ExecutionResultMetas with the additional functionality to group them by various properties

func (ExecutionReceiptMetaList) GroupBy

GroupBy partitions the ExecutionReceiptMetaList. All receipts that are mapped by the grouping function to the same identifier are placed in the same group. Within each group, the order and multiplicity of the receipts is preserved.

func (ExecutionReceiptMetaList) GroupByExecutorID

GroupByExecutorID partitions the ExecutionReceiptMetaList by the receipts' ExecutorIDs. Within each group, the order and multiplicity of the receipts is preserved.

func (ExecutionReceiptMetaList) GroupByResultID

GroupByResultID partitions the ExecutionReceiptMetaList by the receipts' Result IDs. Within each group, the order and multiplicity of the receipts is preserved.

func (ExecutionReceiptMetaList) Lookup

Lookup generates a map from ExecutionReceipt ID to ExecutionReceiptMeta

func (ExecutionReceiptMetaList) Size

func (l ExecutionReceiptMetaList) Size() int

Size returns the number of receipts in the list

type ExecutionResult

type ExecutionResult struct {
	PreviousResultID Identifier // commit of the previous ER
	BlockID          Identifier // commit of the current block
	Chunks           ChunkList
	ServiceEvents    ServiceEventList
	ExecutionDataID  Identifier
}

ExecutionResult is cryptographic commitment to the computation result(s) from executing a block

func (ExecutionResult) Checksum

func (er ExecutionResult) Checksum() Identifier

Checksum ...

func (ExecutionResult) FinalStateCommitment

func (er ExecutionResult) FinalStateCommitment() (StateCommitment, error)

FinalStateCommitment returns the Execution Result's commitment to the final execution state of the block, i.e. the last chunk's output state. Error returns:

  • ErrNoChunks: if there are no chunks (ExecutionResult is malformed)

func (ExecutionResult) ID

func (er ExecutionResult) ID() Identifier

ID returns the hash of the execution result body

func (ExecutionResult) InitialStateCommit

func (er ExecutionResult) InitialStateCommit() (StateCommitment, error)

InitialStateCommit returns a commitment to the execution state used as input for computing the block, i.e. the leading chunk's input state. Error returns:

  • ErrNoChunks: if there are no chunks (ExecutionResult is malformed)

func (ExecutionResult) MarshalJSON

func (er ExecutionResult) MarshalJSON() ([]byte, error)

func (ExecutionResult) ValidateChunksLength

func (er ExecutionResult) ValidateChunksLength() bool

ValidateChunksLength checks whether the number of chuncks is zero.

It returns false if the number of chunks is zero (invalid). By protocol definition, each ExecutionReceipt must contain at least one chunk (system chunk).

type ExecutionResultGroupedList

type ExecutionResultGroupedList map[Identifier]ExecutionResultList

ExecutionResultGroupedList is a partition of an ExecutionResultList

func (ExecutionResultGroupedList) GetGroup

GetGroup returns the ExecutionResults that were mapped to the same identifier by the grouping function. Returns an empty (nil) ExecutionResultList if groupID does not exist.

func (ExecutionResultGroupedList) NumberGroups

func (g ExecutionResultGroupedList) NumberGroups() int

NumberGroups returns the number of groups

type ExecutionResultGroupingFunction

type ExecutionResultGroupingFunction func(*ExecutionResult) Identifier

ExecutionResultGroupingFunction is a function that assigns an identifier to each ExecutionResult

type ExecutionResultList

type ExecutionResultList []*ExecutionResult

ExecutionResultList is a slice of ExecutionResults with the additional functionality to group them by various properties

func (ExecutionResultList) GroupBy

GroupBy partitions the ExecutionResultList. All ExecutionResults that are mapped by the grouping function to the same identifier are placed in the same group. Within each group, the order and multiplicity of the ExecutionResults is preserved.

func (ExecutionResultList) GroupByExecutedBlockID

func (l ExecutionResultList) GroupByExecutedBlockID() ExecutionResultGroupedList

GroupByExecutedBlockID partitions the ExecutionResultList by the IDs of the executed blocks. Within each group, the order and multiplicity of the ExecutionResults is preserved.

func (ExecutionResultList) GroupByPreviousResultID

func (l ExecutionResultList) GroupByPreviousResultID() ExecutionResultGroupedList

GroupByPreviousResultID partitions the ExecutionResultList by the their PreviousResultIDs. Within each group, the order and multiplicity of the ExecutionResults is preserved.

func (ExecutionResultList) Lookup

Lookup generates a map from ExecutionResult ID to ExecutionResult

func (ExecutionResultList) Size

func (l ExecutionResultList) Size() int

Size returns the number of ExecutionResults in the list

type GetResultFunc

type GetResultFunc func(resultID Identifier) (*ExecutionResult, error)

GetResultFunc is a getter function for results by ID. No errors are expected during normal operation.

type GetSealByBlockIDFunc

type GetSealByBlockIDFunc func(blockID Identifier) (*Seal, error)

GetSealByBlockIDFunc is a getter function for seals by block ID, returning the latest seals incorporated as of the given block. No errors are expected during normal operation.

type Header struct {
	ChainID ChainID // ChainID is a chain-specific value to prevent replay attacks.

	ParentID Identifier // ParentID is the ID of this block's parent.

	Height uint64 // Height is the height of the parent + 1

	PayloadHash Identifier // PayloadHash is a hash of the payload of this block.

	Timestamp time.Time // Timestamp is the time at which this block was proposed.

	View uint64 // View number at which this block was proposed.

	ParentVoterIndices []byte // a bitvector that represents all the voters for the parent block.

	ParentVoterSigData []byte // aggregated signature over the parent block. Not a single cryptographic

	ProposerID Identifier // proposer identifier for the block

	ProposerSigData []byte // signature of the proposer over the new block. Not a single cryptographic

}

Header contains all meta-data for a block, as well as a hash representing the combined payload of the entire block. It is what consensus nodes agree on after validating the contents against the payload hash.

func (Header) Body

func (h Header) Body() interface{}

Body returns the immutable part of the block header.

func (Header) Checksum

func (h Header) Checksum() Identifier

Checksum returns the checksum of the header.

func (Header) Fingerprint

func (h Header) Fingerprint() []byte

func (Header) ID

func (h Header) ID() Identifier

ID returns a unique ID to singularly identify the header and its block within the flow system.

func (Header) MarshalCBOR

func (h Header) MarshalCBOR() ([]byte, error)

MarshalCBOR makes sure the timestamp is encoded in UTC.

func (Header) MarshalJSON

func (h Header) MarshalJSON() ([]byte, error)

MarshalJSON makes sure the timestamp is encoded in UTC.

func (Header) MarshalMsgpack

func (h Header) MarshalMsgpack() ([]byte, error)

MarshalMsgpack makes sure the timestamp is encoded in UTC.

func (*Header) UnmarshalCBOR

func (h *Header) UnmarshalCBOR(data []byte) error

UnmarshalCBOR makes sure the timestamp is decoded in UTC.

func (*Header) UnmarshalJSON

func (h *Header) UnmarshalJSON(data []byte) error

UnmarshalJSON makes sure the timestamp is decoded in UTC.

func (*Header) UnmarshalMsgpack

func (h *Header) UnmarshalMsgpack(data []byte) error

UnmarshalMsgpack makes sure the timestamp is decoded in UTC.

type Identifier

type Identifier [IdentifierLen]byte

Identifier represents a 32-byte unique identifier for an entity.

func ByteSliceToId

func ByteSliceToId(b []byte) (Identifier, error)

func CidToId

func CidToId(c cid.Cid) (Identifier, error)

func ConcatSum

func ConcatSum(ids ...Identifier) Identifier

func EventsMerkleRootHash

func EventsMerkleRootHash(el EventsList) (Identifier, error)

EventsMerkleRootHash calculates the root hash of events inserted into a merkle trie with the hash of event as the key and encoded event as value

func HashToID

func HashToID(hash []byte) Identifier

func HexStringToIdentifier

func HexStringToIdentifier(hexString string) (Identifier, error)

HexStringToIdentifier converts a hex string to an identifier. The input must be 64 characters long and contain only valid hex characters.

func MakeID

func MakeID(entity interface{}) Identifier

MakeID creates an ID from a hash of encoded data. MakeID uses `model.Fingerprint() []byte` to get the byte representation of the entity, which uses RLP to encode the data. If the input defines its own canonical encoding by implementing Fingerprinter, it uses that instead. That allows removal of non-unique fields from structs or overwriting of the used encoder. We are using Fingerprint instead of the default encoding for two reasons: a) JSON (the default encoding) does not specify an order for the elements of arrays and objects, which could lead to different hashes depending on the JSON implementation and b) the Fingerprinter interface allows to exclude fields not needed in the pre-image of the hash that comprises the Identifier, which could be different from the encoding for sending entities in messages or for storing them.

func MakeIDFromFingerPrint

func MakeIDFromFingerPrint(fingerPrint []byte) Identifier

MakeIDFromFingerPrint is similar to MakeID but skipping fingerprinting step.

func MerkleRoot

func MerkleRoot(ids ...Identifier) Identifier

func MustHexStringToIdentifier

func MustHexStringToIdentifier(hexString string) Identifier

func PublicKeyToID

func PublicKeyToID(pk crypto.PublicKey) (Identifier, error)

PublicKeyToID creates an ID from a public key.

func Sample

func Sample(size uint, ids ...Identifier) []Identifier

Sample returns random sample of length 'size' of the ids [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).

func (Identifier) Format

func (id Identifier) Format(state fmt.State, verb rune)

Format handles formatting of id for different verbs. This is called when formatting an identifier with fmt.

func (Identifier) IsSampled

func (id Identifier) IsSampled(sensitivity uint) bool

IsSampled is a utility method to sample entities based on their ids the range is from [0, 64]. 0 is 100% (all data will be collected) 1 is ~50% 2 is ~25% 3 is ~12.5% ... >64 is 0% (no data will be collected)

func (Identifier) MarshalText

func (id Identifier) MarshalText() ([]byte, error)

func (Identifier) String

func (id Identifier) String() string

String returns the hex string representation of the identifier.

func (*Identifier) UnmarshalText

func (id *Identifier) UnmarshalText(text []byte) error

type IdentifierFilter

type IdentifierFilter func(Identifier) bool

IdentifierFilter is a filter on identifiers.

type IdentifierList

type IdentifierList []Identifier

IdentifierList defines a sortable list of identifiers

func ByteSlicesToIds

func ByteSlicesToIds(b [][]byte) (IdentifierList, error)

func GetIDs

func GetIDs[T Entity](entities []T) IdentifierList

GetIDs gets the IDs for a slice of entities.

func (IdentifierList) Contains

func (il IdentifierList) Contains(target Identifier) bool

Contains returns whether this identifier list contains the target identifier.

func (IdentifierList) Copy

func (il IdentifierList) Copy() IdentifierList

func (IdentifierList) DeterministicSample

func (il IdentifierList) DeterministicSample(size uint, seed int64) IdentifierList

DeterministicSample returns deterministic random sample from the `IdentifierList` using the given seed

func (IdentifierList) Filter

Filter will apply a filter to the identifier list.

func (IdentifierList) Len

func (il IdentifierList) Len() int

Len returns length of the IdentiferList in the number of stored identifiers. It satisfies the sort.Interface making the IdentifierList sortable.

func (IdentifierList) Less

func (il IdentifierList) Less(i, j int) bool

Less returns true if element i in the IdentifierList is less than j based on its identifier. Otherwise it returns true. It satisfies the sort.Interface making the IdentifierList sortable.

func (IdentifierList) Lookup

func (il IdentifierList) Lookup() map[Identifier]struct{}

Lookup converts the Identifiers to a lookup table.

func (IdentifierList) Sample

func (il IdentifierList) Sample(size uint) IdentifierList

Sample returns random sample of length 'size' of the ids [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).

func (IdentifierList) Sort

func (IdentifierList) Sorted

func (il IdentifierList) Sorted(less IdentifierOrder) bool

Sorted returns whether the list is sorted by the input ordering.

func (IdentifierList) Strings

func (il IdentifierList) Strings() []string

func (IdentifierList) Swap

func (il IdentifierList) Swap(i, j int)

Swap swaps the element i and j in the IdentifierList. It satisfies the sort.Interface making the IdentifierList sortable.

func (IdentifierList) Union

Union returns a new identifier list containing the union of `il` and `other`. There are no duplicates in the output.

type IdentifierOrder

type IdentifierOrder func(Identifier, Identifier) bool

IdentifierOrder is a sort for identifier

type Identity

type Identity struct {
	// NodeID uniquely identifies a particular node. A node's ID is fixed for
	// the duration of that node's participation in the network.
	NodeID Identifier
	// Address is the network address where the node can be reached.
	Address string
	// Role is the node's role in the network and defines its abilities and
	// responsibilities.
	Role Role
	// Weight represents the node's authority to perform certain tasks relative
	// to other nodes. For example, in the consensus committee, the node's weight
	// represents the weight assigned to its votes.
	//
	// A node's weight is distinct from its stake. Stake represents the quantity
	// of FLOW tokens held by the network in escrow during the course of the node's
	// participation in the network. The stake is strictly managed by the service
	// account smart contracts.
	//
	// Nodes which are registered to join at the next epoch will appear in the
	// identity table but are considered to have zero weight up until their first
	// epoch begins. Likewise nodes which were registered in the previous epoch
	// but have left at the most recent epoch boundary will appear in the identity
	// table with zero weight.
	Weight uint64
	// Ejected represents whether a node has been permanently removed from the
	// network. A node may be ejected for either:
	// * committing one protocol felony
	// * committing a series of protocol misdemeanours
	Ejected       bool
	StakingPubKey crypto.PublicKey
	NetworkPubKey crypto.PublicKey
}

Identity represents the public identity of one network participant (node).

func ParseIdentity

func ParseIdentity(identity string) (*Identity, error)

ParseIdentity parses a string representation of an identity.

func (Identity) Checksum

func (iy Identity) Checksum() Identifier

Checksum returns a checksum for the identity including mutable attributes.

func (Identity) EncodeRLP

func (iy Identity) EncodeRLP(w io.Writer) error

func (*Identity) EqualTo

func (iy *Identity) EqualTo(other *Identity) bool

func (Identity) ID

func (iy Identity) ID() Identifier

ID returns a unique identifier for the identity.

func (Identity) MarshalCBOR

func (iy Identity) MarshalCBOR() ([]byte, error)

func (Identity) MarshalJSON

func (iy Identity) MarshalJSON() ([]byte, error)

func (Identity) MarshalMsgpack

func (iy Identity) MarshalMsgpack() ([]byte, error)

func (Identity) String

func (iy Identity) String() string

String returns a string representation of the identity.

func (*Identity) UnmarshalCBOR

func (iy *Identity) UnmarshalCBOR(b []byte) error

func (*Identity) UnmarshalJSON

func (iy *Identity) UnmarshalJSON(b []byte) error

func (*Identity) UnmarshalMsgpack

func (iy *Identity) UnmarshalMsgpack(b []byte) error

type IdentityFilter

type IdentityFilter func(*Identity) bool

IdentityFilter is a filter on identities.

type IdentityList

type IdentityList []*Identity

IdentityList is a list of nodes.

func (IdentityList) ByIndex

func (il IdentityList) ByIndex(index uint) (*Identity, bool)

ByIndex returns the node at the given index.

func (IdentityList) ByNetworkingKey

func (il IdentityList) ByNetworkingKey(key crypto.PublicKey) (*Identity, bool)

ByNetworkingKey gets a node from the list by network public key.

func (IdentityList) ByNodeID

func (il IdentityList) ByNodeID(nodeID Identifier) (*Identity, bool)

ByNodeID gets a node from the list by node ID.

func (IdentityList) Copy

func (il IdentityList) Copy() IdentityList

Copy returns a copy of the receiver. The resulting slice uses a different backing array, meaning appends and insert operations on either slice are guaranteed to only affect that slice.

Copy should be used when modifying an existing identity list by either appending new elements, re-ordering, or inserting new elements in an existing index.

func (IdentityList) Count

func (il IdentityList) Count() uint

Count returns the count of identities.

func (IdentityList) DeterministicSample

func (il IdentityList) DeterministicSample(size uint, seed int64) IdentityList

DeterministicSample returns deterministic random sample from the `IdentityList` using the given seed

func (IdentityList) DeterministicShuffle

func (il IdentityList) DeterministicShuffle(seed int64) IdentityList

DeterministicShuffle randomly and deterministically shuffles the identity list, returning the shuffled list without modifying the receiver.

func (IdentityList) EqualTo

func (il IdentityList) EqualTo(other IdentityList) bool

EqualTo checks if the other list if the same, that it contains the same elements in the same order

func (IdentityList) Exists

func (il IdentityList) Exists(target *Identity) bool

Exists takes a previously sorted Identity list and searches it for the target value This code is optimized, so the coding style will be different target: value to search for CAUTION: The identity list MUST be sorted prior to calling this method

func (IdentityList) Filter

func (il IdentityList) Filter(filter IdentityFilter) IdentityList

Filter will apply a filter to the identity list.

func (IdentityList) Fingerprint

func (il IdentityList) Fingerprint() Identifier

func (IdentityList) GetIndex

func (il IdentityList) GetIndex(target Identifier) (uint, bool)

GetIndex returns the index of the identifier in the IdentityList and true if the identifier is found.

func (IdentityList) IdentifierExists

func (il IdentityList) IdentifierExists(target Identifier) bool

IdentifierExists takes a previously sorted Identity list and searches it for the target value target: value to search for CAUTION: The identity list MUST be sorted prior to calling this method

func (IdentityList) Lookup

func (il IdentityList) Lookup() map[Identifier]*Identity

func (IdentityList) Map

Map returns a new identity list with the map function f applied to a copy of each identity.

CAUTION: this relies on structure copy semantics. Map functions that modify an object referenced by the input Identity structure will modify identities in the source slice as well.

func (IdentityList) NodeIDs

func (il IdentityList) NodeIDs() IdentifierList

NodeIDs returns the NodeIDs of the nodes in the list.

func (IdentityList) PublicStakingKeys

func (il IdentityList) PublicStakingKeys() []crypto.PublicKey

PublicStakingKeys returns a list with the public staking keys (order preserving).

func (IdentityList) Sample

func (il IdentityList) Sample(size uint) IdentityList

Sample returns simple random sample from the `IdentityList`

func (IdentityList) SamplePct

func (il IdentityList) SamplePct(pct float64) IdentityList

SamplePct returns a random sample from the receiver identity list. The sample contains `pct` percentage of the list. The sample is rounded up if `pct>0`, so this will always select at least one identity.

NOTE: The input must be between 0-1.

func (IdentityList) Selector

func (il IdentityList) Selector() IdentityFilter

Selector returns an identity filter function that selects only identities within this identity list.

func (IdentityList) Sort

func (il IdentityList) Sort(less IdentityOrder) IdentityList

Sort will sort the list using the given ordering. This is not recommended for performance. Expand the 'less' function in place for best performance, and don't use this function.

func (IdentityList) Sorted

func (il IdentityList) Sorted(less IdentityOrder) bool

Sorted returns whether the list is sorted by the input ordering.

func (IdentityList) TotalWeight

func (il IdentityList) TotalWeight() uint64

TotalWeight returns the total weight of all given identities.

func (IdentityList) Union

func (il IdentityList) Union(other IdentityList) IdentityList

Union returns a new identity list containing every identity that occurs in either `il`, or `other`, or both. There are no duplicates in the output, where duplicates are identities with the same node ID. The returned IdentityList is sorted

type IdentityMapFunc

type IdentityMapFunc func(Identity) Identity

IdentityMapFunc is a modifier function for map operations for identities. Identities are COPIED from the source slice.

type IdentityOrder

type IdentityOrder func(*Identity, *Identity) bool

IdentityOrder is a sort for identities.

type IncorporatedResult

type IncorporatedResult struct {
	// IncorporatedBlockID is the ID of the first block on its fork where a
	// receipt for this result was incorporated. Within a fork, multiple blocks
	// may contain receipts for the same result; only the first one is used to
	// compute the random beacon of the result's chunk assignment.
	IncorporatedBlockID Identifier

	// Result is the ExecutionResult contained in the ExecutionReceipt that was
	// incorporated in the payload of IncorporatedBlockID.
	Result *ExecutionResult
}

IncorporatedResult is a wrapper around an ExecutionResult which contains the ID of the first block on its fork in which it was incorporated.

func NewIncorporatedResult

func NewIncorporatedResult(incorporatedBlockID Identifier, result *ExecutionResult) *IncorporatedResult

func (*IncorporatedResult) Checksum

func (ir *IncorporatedResult) Checksum() Identifier

CheckSum implements flow.Entity.CheckSum for IncorporatedResult to make it capable of being stored directly in mempools and storage.

func (*IncorporatedResult) ID

func (ir *IncorporatedResult) ID() Identifier

ID implements flow.Entity.ID for IncorporatedResult to make it capable of being stored directly in mempools and storage.

type IncorporatedResultGroupedList

type IncorporatedResultGroupedList map[Identifier]IncorporatedResultList

IncorporatedResultGroupedList is a partition of an IncorporatedResultList

func (IncorporatedResultGroupedList) GetGroup

GetGroup returns the IncorporatedResults that were mapped to the same identifier by the grouping function. Returns an empty (nil) IncorporatedResultList if groupID does not exist.

func (IncorporatedResultGroupedList) NumberGroups

func (g IncorporatedResultGroupedList) NumberGroups() int

NumberGroups returns the number of groups

type IncorporatedResultGroupingFunction

type IncorporatedResultGroupingFunction func(*IncorporatedResult) Identifier

IncorporatedResultGroupingFunction is a function that assigns an identifier to each IncorporatedResult

type IncorporatedResultList

type IncorporatedResultList []*IncorporatedResult

IncorporatedResultList is a slice of IncorporatedResults with the additional functionality to group them by various properties

func (IncorporatedResultList) GroupBy

GroupBy partitions the IncorporatedResultList. All IncorporatedResults that are mapped by the grouping function to the same identifier are placed in the same group. Within each group, the order and multiplicity of the IncorporatedResults is preserved.

func (IncorporatedResultList) GroupByExecutedBlockID

func (l IncorporatedResultList) GroupByExecutedBlockID() IncorporatedResultGroupedList

GroupByExecutedBlockID partitions the IncorporatedResultList by the IDs of the executed blocks. Within each group, the order and multiplicity of the IncorporatedResults is preserved.

func (IncorporatedResultList) GroupByIncorporatedBlockID

func (l IncorporatedResultList) GroupByIncorporatedBlockID() IncorporatedResultGroupedList

GroupByIncorporatedBlockID partitions the IncorporatedResultList by the ID of the block that incorporates the result. Within each group, the order and multiplicity of the IncorporatedResults is preserved.

func (IncorporatedResultList) GroupByResultID

GroupByResultID partitions the IncorporatedResultList by the Results' IDs. Within each group, the order and multiplicity of the IncorporatedResults is preserved.

func (IncorporatedResultList) Size

func (l IncorporatedResultList) Size() int

Size returns the number of IncorporatedResults in the list

type IncorporatedResultSeal

type IncorporatedResultSeal struct {
	// IncorporatedResult is the incorporated result (result + ID of block where
	// it was incorporated) that the seal is for.
	IncorporatedResult *IncorporatedResult

	// Seal is a seal for the result contained in IncorporatedResult.
	Seal *Seal

	// the header of the executed block
	// useful for indexing the seal by height in the mempool in order for fast pruning
	Header *Header
}

IncorporatedResultSeal is a wrapper around a seal that keeps track of which IncorporatedResult the seal corresponds to. Sealing is a function of result And the ID of the block in which the result was incorporated, which is all contained in IncorporatedResult.

func (*IncorporatedResultSeal) Checksum

func (s *IncorporatedResultSeal) Checksum() Identifier

CheckSum implements flow.Entity.CheckSum for IncorporatedResultSeal to make it capable of being stored directly in mempools and storage.

func (*IncorporatedResultSeal) ID

ID implements flow.Entity.ID for IncorporatedResultSeal to make it capable of being stored directly in mempools and storage.

type Index

type Index struct {
	CollectionIDs []Identifier
	SealIDs       []Identifier
	ReceiptIDs    []Identifier
	ResultIDs     []Identifier
}

type LightCollection

type LightCollection struct {
	Transactions []Identifier
}

LightCollection is a collection containing references to the constituent transactions rather than full transaction bodies. It is used for indexing transactions by collection and for computing the collection fingerprint.

func (LightCollection) Checksum

func (lc LightCollection) Checksum() Identifier

func (LightCollection) Has

func (lc LightCollection) Has(txID Identifier) bool

func (LightCollection) ID

func (lc LightCollection) ID() Identifier

func (LightCollection) Len

func (lc LightCollection) Len() int

type MonotonicAddressGenerator

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

func (*MonotonicAddressGenerator) AddressCount

func (gen *MonotonicAddressGenerator) AddressCount() uint64

AddressCount returns the total number of addresses generated so far

func (*MonotonicAddressGenerator) Bytes

func (gen *MonotonicAddressGenerator) Bytes() []byte

Bytes converts an address index into a slice of bytes

func (*MonotonicAddressGenerator) CurrentAddress

func (gen *MonotonicAddressGenerator) CurrentAddress() Address

CurrentAddress returns the address corresponding to the internal index.

func (*MonotonicAddressGenerator) NextAddress

func (gen *MonotonicAddressGenerator) NextAddress() (Address, error)

NextAddress increments the internal index and generates the new address corresponding to the new index.

type Payload

type Payload struct {
	// Guarantees are ordered in execution order.
	Guarantees []*CollectionGuarantee
	Seals      []*Seal
	Receipts   ExecutionReceiptMetaList
	Results    ExecutionResultList
}

Payload is the actual content of each block.

func EmptyPayload

func EmptyPayload() Payload

EmptyPayload returns an empty block payload.

func (Payload) Hash

func (p Payload) Hash() Identifier

Hash returns the root hash of the payload.

func (Payload) Index

func (p Payload) Index() *Index

Index returns the index for the payload.

func (Payload) MarshalJSON

func (p Payload) MarshalJSON() ([]byte, error)

MarshalJSON defines the JSON marshalling for block payloads. Enforce a consistent representation for empty slices.

type Proof

type Proof []byte

Proof contains proof that an entity is part of a EntityList

type ProposalKey

type ProposalKey struct {
	Address        Address
	KeyIndex       uint64
	SequenceNumber uint64
}

A ProposalKey is the key that specifies the proposal key and sequence number for a transaction.

func (ProposalKey) ByteSize

func (p ProposalKey) ByteSize() int

ByteSize returns the byte size of the proposal key

type QuorumCertificate

type QuorumCertificate struct {
	View    uint64
	BlockID Identifier

	// SignerIndices encodes the HotStuff participants whose vote is included in this QC.
	// For `n` authorized consensus nodes, `SignerIndices` is an n-bit vector (padded with tailing
	// zeros to reach full bytes). We list the nodes in their canonical order, as defined by the protocol.
	SignerIndices []byte

	// For consensus cluster, the SigData is a serialization of the following fields
	// - SigType []byte, bit-vector indicating the type of sig produced by the signer.
	// - AggregatedStakingSig []byte
	// - AggregatedRandomBeaconSig []byte
	// - ReconstructedRandomBeaconSig crypto.Signature
	// For collector cluster HotStuff, SigData is simply the aggregated staking signatures
	// from all signers.
	SigData []byte
}

QuorumCertificate represents a quorum certificate for a block proposal as defined in the HotStuff algorithm. A quorum certificate is a collection of votes for a particular block proposal. Valid quorum certificates contain signatures from a super-majority of consensus committee members.

type QuorumCertificateWithSignerIDs

type QuorumCertificateWithSignerIDs struct {
	View      uint64
	BlockID   Identifier
	SignerIDs []Identifier
	SigData   []byte
}

QuorumCertificateWithSignerIDs is a QuorumCertificate, where the signing nodes are identified via their `flow.Identifier`s instead of indices. Working with IDs as opposed to indices is less efficient, but simpler, because we don't require a canonical node order. It is used for bootstrapping new Epochs, because the FlowEpoch smart contract has no notion of node ordering.

type RegisterEntries

type RegisterEntries []RegisterEntry

handy container for sorting

func (RegisterEntries) IDs

func (d RegisterEntries) IDs() []RegisterID

func (RegisterEntries) Len

func (d RegisterEntries) Len() int

func (RegisterEntries) Less

func (d RegisterEntries) Less(i, j int) bool

func (RegisterEntries) Swap

func (d RegisterEntries) Swap(i, j int)

func (RegisterEntries) Values

func (d RegisterEntries) Values() []RegisterValue

type RegisterEntry

type RegisterEntry struct {
	Key   RegisterID
	Value RegisterValue
}

type RegisterID

type RegisterID struct {
	Owner string
	Key   string
}

func NewRegisterID

func NewRegisterID(owner, key string) RegisterID

func (*RegisterID) Bytes

func (r *RegisterID) Bytes() []byte

Bytes returns a bytes representation of the RegisterID.

The encoding uses the injective fingerprint module.

func (*RegisterID) String

func (r *RegisterID) String() string

String returns formatted string representation of the RegisterID. TODO(rbtz): remove after the merge of https://github.com/onflow/flow-emulator/pull/235 Deprecated: used only by emultor.

type RegisterValue

type RegisterValue = []byte

RegisterValue (value part of Register)

type ResultApproval

type ResultApproval struct {
	Body              ResultApprovalBody
	VerifierSignature crypto.Signature // signature over all above fields
}

ResultApproval includes an approval for a chunk, verified by a verification node

func (ResultApproval) Checksum

func (ra ResultApproval) Checksum() Identifier

Checksum generates checksum using the result approval full content

func (ResultApproval) ID

func (ra ResultApproval) ID() Identifier

ID generates a unique identifier using result approval body

type ResultApprovalBody

type ResultApprovalBody struct {
	Attestation
	ApproverID           Identifier       // node id generating this result approval
	AttestationSignature crypto.Signature // signature over attestation, this has been separated for BLS aggregation
	Spock                crypto.Signature // proof of re-computation, one per each chunk
}

ResultApprovalBody holds body part of a result approval

func (ResultApprovalBody) ID

func (rab ResultApprovalBody) ID() Identifier

ID generates a unique identifier using ResultApprovalBody

func (ResultApprovalBody) PartialID

func (rab ResultApprovalBody) PartialID() Identifier

PartialID generates a unique identifier using Attestation + ApproverID

type Role

type Role uint8

Role represents a role in the flow system.

const (
	RoleCollection   Role = 1
	RoleConsensus    Role = 2
	RoleExecution    Role = 3
	RoleVerification Role = 4
	RoleAccess       Role = 5
)

Enumeration of the available flow node roles.

func ParseRole

func ParseRole(role string) (Role, error)

ParseRole will parse a role from string.

func (Role) MarshalText

func (r Role) MarshalText() ([]byte, error)

func (Role) String

func (r Role) String() string

String returns a string version of role.

func (*Role) UnmarshalText

func (r *Role) UnmarshalText(text []byte) error

func (Role) Valid

func (r Role) Valid() bool

type RoleList

type RoleList []Role

RoleList defines a slice of roles in flow system.

func Roles

func Roles() RoleList

func (RoleList) Contains

func (r RoleList) Contains(role Role) bool

Contains returns true if RoleList contains the role, otherwise false.

func (RoleList) ID

func (r RoleList) ID() Identifier

ID returns hash of the content of RoleList. It first sorts the RoleList and then takes its hash value.

func (RoleList) Len

func (r RoleList) Len() int

Len returns length of the RoleList in the number of stored roles. It satisfies the sort.Interface making the RoleList sortable.

func (RoleList) Less

func (r RoleList) Less(i, j int) bool

Less returns true if element i in the RoleList is less than j based on the numerical value of its role. Otherwise it returns true. It satisfies the sort.Interface making the RoleList sortable.

func (RoleList) Swap

func (r RoleList) Swap(i, j int)

Swap swaps the element i and j in the RoleList. It satisfies the sort.Interface making the RoleList sortable.

func (RoleList) Union

func (r RoleList) Union(other RoleList) RoleList

Union returns a new role list containing every role that occurs in either `r`, or `other`, or both. There are no duplicate roles in the output,

type Seal

type Seal struct {
	BlockID                Identifier
	ResultID               Identifier
	FinalState             StateCommitment
	AggregatedApprovalSigs []AggregatedSignature // one AggregatedSignature per chunk
}

A Seal is produced when an Execution Result (referenced by `ResultID`) for particular block (referenced by `BlockID`) is committed into the chain. A Seal for a block B can be included in the payload B's descendants. Only in the respective fork where the seal for B is included, the referenced result is considered committed. Different forks might contain different seals for the same result (or in edge cases, even for different results).

NOTES (1) As Seals are (currently) included in the payload, they are not strictly entities. (Entities can be sent between nodes as self-contained messages whose integrity is protected by a signature). By itself, a seal does _not_ contain enough information to determine its validity (verifier assignment cannot be computed) and its integrity is not protected by a signature of a node that is authorized to generate it. A seal should only be processed in the context of the block, which contains it.

(2) Even though seals are not strictly entities, they still implement the Entity interface. This allows us to store and retrieve seals individually. CAUTION: As seals are part of the block payload, their _exact_ content must be preserved by the storage system. This includes the exact list of approval signatures (incl. order). While it is possible to construct different valid seals for the same result (using different subsets of assigned verifiers), they cannot be treated as equivalent for the following reason:

  • Swapping a seal in a block with a different once changes the binary representation of the block payload containing the seal.
  • Changing the binary block representation would invalidate the block proposer's signature.

Therefore, to retrieve valid blocks from storage, it is required that the Seal.ID includes all fields with independent degrees of freedom (such as AggregatedApprovalSigs).

func (Seal) Body

func (s Seal) Body() interface{}

func (Seal) Checksum

func (s Seal) Checksum() Identifier

func (Seal) ID

func (s Seal) ID() Identifier

func (Seal) MarshalJSON

func (s Seal) MarshalJSON() ([]byte, error)

type SealingSegment

type SealingSegment struct {
	// Blocks contain the chain segment blocks in ascending height order.
	Blocks []*Block

	// ExecutionResults contain any results which are referenced by receipts
	// or seals in the sealing segment, but not included in any segment block
	// payloads.
	//
	// Due to decoupling of execution receipts from execution results,
	// it's possible that blocks from the sealing segment will be referring to
	// execution results incorporated in blocks that aren't part of the segment.
	ExecutionResults ExecutionResultList

	// LatestSeals is a mapping from block ID to the ID of the latest seal
	// incorporated as of that block. Note: we store the seals' IDs here
	// (instead of the full seals), because the seals for all blocks, except for
	// the lowest one, are contained in the blocks of the sealing segment.
	LatestSeals map[Identifier]Identifier

	// FirstSeal contains the latest seal as of the first block in the segment.
	// Per convention, this field holds a seal that was included _prior_ to the
	// first block of the sealing segment. If the first block in the segment
	// contains a seal, then this field is `nil`.
	// This information is needed for the `Commit` method of protocol snapshot
	// to return the sealed state, when the first block contains no seal.
	FirstSeal *Seal
}

SealingSegment is the chain segment such that the last block (greatest height) is this snapshot's reference block and the first (least height) is the most recently sealed block as of this snapshot (ie. the block referenced by LatestSeal).

In other words, the most recently incorporated seal as of the highest block references the lowest block. The highest block does not need to contain this seal.

Example 1 - E seals A:

A <- B <- C <- D <- E(SA)

The above sealing segment's last block (E) has a seal for block A, which is the first block of the sealing segment.

Example 2 - E contains no seals, but latest seal prior to E seals A:

A <- B <- C <- D(SA) <- E

Example 3 - E contains multiple seals

B <- C <- D <- E(SA, SB)

MINIMALITY REQUIREMENT: Note that block B is the highest sealed block as of E. Therefore, the sealing segment's lowest block must be B. Essentially, this is a minimality requirement for the history: it shouldn't be longer than necessary. So extending the chain segment above to A <- B <- C <- D <- E(SA, SB) would _not_ yield a valid SealingSegment.

ROOT SEALING SEGMENTS: Root sealing segments are sealing segments which contain the root block: * the root block is a self-sealing block with an empty payload * the root block must be the first block (least height) in the segment * no blocks in the segment may contain any seals (by the minimality requirement) * it is possible (but not necessary) for root sealing segments to contain only the root block

Example 1 - one self-sealing root block

ROOT

The above sealing segment is the form of sealing segments within root snapshots, for example those snapshots used to bootstrap a new network, or spork.

Example 2 - one self-sealing root block followed by any number of seal-less blocks

ROOT <- A <- B

All non-root sealing segments contain more than one block. Sealing segments are in ascending height order.

In addition to storing the blocks within the sealing segment, as defined above, the SealingSegment structure also stores any resources which are referenced by blocks in the segment, but not included in the payloads of blocks within the segment. In particular: * results referenced by receipts within segment payloads * results referenced by seals within segment payloads * seals which represent the latest state commitment as of a segment block

func (*SealingSegment) FinalizedSeal

func (segment *SealingSegment) FinalizedSeal() (*Seal, error)

FinalizedSeal returns the seal that seals the lowest block. Per specification, this seal must be included in a SealingSegment. The SealingSegment must be validated. No errors are expected during normal operation.

func (*SealingSegment) Highest

func (segment *SealingSegment) Highest() *Block

func (*SealingSegment) Lowest

func (segment *SealingSegment) Lowest() *Block

func (*SealingSegment) Validate

func (segment *SealingSegment) Validate() error

Validate validates the sealing segment structure and returns an error if the segment isn't valid. This is done by re-building the segment from scratch, re-using the validation logic already present in the SealingSegmentBuilder. The node logic requires a valid sealing segment to bootstrap. No errors are expected during normal operation.

type SealingSegmentBuilder

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

SealingSegmentBuilder is a utility for incrementally building a sealing segment.

func NewSealingSegmentBuilder

func NewSealingSegmentBuilder(resultLookup GetResultFunc, sealLookup GetSealByBlockIDFunc) *SealingSegmentBuilder

NewSealingSegmentBuilder returns *SealingSegmentBuilder

func (*SealingSegmentBuilder) AddBlock

func (builder *SealingSegmentBuilder) AddBlock(block *Block) error

AddBlock appends a block to the sealing segment under construction. No errors are expected during normal operation.

func (*SealingSegmentBuilder) SealingSegment

func (builder *SealingSegmentBuilder) SealingSegment() (*SealingSegment, error)

SealingSegment completes building the sealing segment, validating the segment constructed so far, and returning it as a SealingSegment if it is valid.

All errors indicate the SealingSegmentBuilder internal state does not represent a valid sealing segment. No errors are expected during normal operation.

type ServiceEvent

type ServiceEvent struct {
	Type  string
	Event interface{}
}

ServiceEvent represents a service event, which is a special event that when emitted from a service account smart contract, is propagated to the protocol and included in blocks. Service events typically cause changes to the protocol state. See EpochSetup and EpochCommit events in this package for examples.

This type represents a generic service event and primarily exists to simplify encoding and decoding.

func (*ServiceEvent) EqualTo

func (se *ServiceEvent) EqualTo(other *ServiceEvent) (bool, error)

func (*ServiceEvent) UnmarshalCBOR

func (se *ServiceEvent) UnmarshalCBOR(b []byte) error

func (*ServiceEvent) UnmarshalJSON

func (se *ServiceEvent) UnmarshalJSON(b []byte) error

func (*ServiceEvent) UnmarshalMsgpack

func (se *ServiceEvent) UnmarshalMsgpack(b []byte) error

type ServiceEventList

type ServiceEventList []ServiceEvent

ServiceEventList is a handy container to enable comparisons

func (ServiceEventList) EqualTo

func (sel ServiceEventList) EqualTo(other ServiceEventList) (bool, error)

type Slashable

type Slashable[T any] struct {
	OriginID Identifier // this will become the inspector object, once we have message forensics
	Message  *T
}

Slashable represents an message we got from a different node, whose validity has not been _entirely_ confirmed. We want to retain information about the origin that published this particular message within the network, so we can potentially raise a slashing challenge against the origin, should we discover that this message is evidence of a protocol violation. TODO: this struct does not have its final form. We only retain the ID of the node where the message originated. However, this will not allow us to prove to somebody else that `OriginID` really sent this message, as we could have tempered with the message and then erroneously accuse `OriginID` of a protocol violation. In the mature protocol, `OriginID` will be replaced by an inspector object (generated by the networking layer) that allows us to generate a cryptographic proof of who sent the message.

func NoSlashable

func NoSlashable[T any]() Slashable[T]

NoSlashable returns the zero value for Slashable[T].

type Spock

type Spock []byte

type StateCommitment

type StateCommitment hash.Hash

StateCommitment holds the root hash of the tree (Snapshot) TODO: solve the circular dependency and define StateCommitment as ledger.State

func ToStateCommitment

func ToStateCommitment(stateBytes []byte) (StateCommitment, error)

ToStateCommitment converts a byte slice into a StateCommitment. It returns an error if the slice has an invalid length. The returned error indicates that the given byte slice is not a valid root hash of an execution state. As the function is side-effect free, all failures are simply a no-op.

func (StateCommitment) MarshalJSON

func (s StateCommitment) MarshalJSON() ([]byte, error)

func (*StateCommitment) UnmarshalJSON

func (s *StateCommitment) UnmarshalJSON(data []byte) error

type StorageProof

type StorageProof = []byte

StorageProof (proof of a read or update to the state, Merkle path of some sort)

type Transaction

type Transaction struct {
	TransactionBody
	Status           TransactionStatus
	Events           []Event
	ComputationSpent uint64
	StartState       StateCommitment
	EndState         StateCommitment
}

Transaction is the smallest unit of task.

func (*Transaction) Checksum

func (tx *Transaction) Checksum() Identifier

Checksum provides a cryptographic commitment for a chunk content

func (*Transaction) PayloadMessage

func (tx *Transaction) PayloadMessage() []byte

func (*Transaction) String

func (tx *Transaction) String() string

type TransactionBody

type TransactionBody struct {

	// A reference to a previous block
	// A transaction is expired after specific number of blocks (defined by network) counting from this block
	// for example, if block reference is pointing to a block with height of X and network limit is 10,
	// a block with x+10 height is the last block that is allowed to include this transaction.
	// user can adjust this reference to older blocks if he/she wants to make tx expire faster
	ReferenceBlockID Identifier

	// the transaction script as UTF-8 encoded Cadence source code
	Script []byte

	// arguments passed to the Cadence transaction
	Arguments [][]byte

	// Max amount of computation which is allowed to be done during this transaction
	GasLimit uint64

	// Account key used to propose the transaction
	ProposalKey ProposalKey

	// Account that pays for this transaction fees
	Payer Address

	// A ordered (ascending) list of addresses that scripts will touch their assets (including payer address)
	// Accounts listed here all have to provide signatures
	// Each account might provide multiple signatures (sum of weight should be at least 1)
	// If code touches accounts that is not listed here, tx fails
	Authorizers []Address

	// List of account signatures excluding signature of the payer account
	PayloadSignatures []TransactionSignature

	// payer signature over the envelope (payload + payload signatures)
	EnvelopeSignatures []TransactionSignature
}

TransactionBody includes the main contents of a transaction

func NewTransactionBody

func NewTransactionBody() *TransactionBody

NewTransactionBody initializes and returns an empty transaction body

func (*TransactionBody) AddArgument

func (tb *TransactionBody) AddArgument(arg []byte) *TransactionBody

AddArgument adds an argument to the Cadence arguments list for this transaction.

func (*TransactionBody) AddAuthorizer

func (tb *TransactionBody) AddAuthorizer(address Address) *TransactionBody

AddAuthorizer adds an authorizer account to this transaction.

func (*TransactionBody) AddEnvelopeSignature

func (tb *TransactionBody) AddEnvelopeSignature(address Address, keyID uint64, sig []byte) *TransactionBody

AddEnvelopeSignature adds an envelope signature to the transaction for the given address and key ID.

func (*TransactionBody) AddPayloadSignature

func (tb *TransactionBody) AddPayloadSignature(address Address, keyID uint64, sig []byte) *TransactionBody

AddPayloadSignature adds a payload signature to the transaction for the given address and key ID.

func (TransactionBody) ByteSize

func (tb TransactionBody) ByteSize() uint

func (TransactionBody) Checksum

func (tb TransactionBody) Checksum() Identifier

func (*TransactionBody) EnvelopeMessage

func (tb *TransactionBody) EnvelopeMessage() []byte

EnvelopeMessage returns the signable message for transaction envelope.

This message is only signed by the payer account.

func (TransactionBody) Fingerprint

func (tb TransactionBody) Fingerprint() []byte

func (TransactionBody) ID

func (tb TransactionBody) ID() Identifier

func (TransactionBody) InclusionEffort

func (tb TransactionBody) InclusionEffort() uint64

InclusionEffort returns the inclusion effort of the transaction

func (*TransactionBody) MissingFields

func (tb *TransactionBody) MissingFields() []string

MissingFields checks if a transaction is missing any required fields and returns those that are missing.

func (*TransactionBody) PayloadMessage

func (tb *TransactionBody) PayloadMessage() []byte

func (*TransactionBody) SetArguments

func (tb *TransactionBody) SetArguments(args [][]byte) *TransactionBody

SetArguments sets the Cadence arguments list for this transaction.

func (*TransactionBody) SetGasLimit

func (tb *TransactionBody) SetGasLimit(limit uint64) *TransactionBody

SetGasLimit sets the gas limit for this transaction.

func (*TransactionBody) SetPayer

func (tb *TransactionBody) SetPayer(address Address) *TransactionBody

SetPayer sets the payer account for this transaction.

func (*TransactionBody) SetProposalKey

func (tb *TransactionBody) SetProposalKey(address Address, keyID uint64, sequenceNum uint64) *TransactionBody

SetProposalKey sets the proposal key and sequence number for this transaction.

The first two arguments specify the account key to be used, and the last argument is the sequence number being declared.

func (*TransactionBody) SetReferenceBlockID

func (tb *TransactionBody) SetReferenceBlockID(blockID Identifier) *TransactionBody

SetReferenceBlockID sets the reference block ID for this transaction.

func (*TransactionBody) SetScript

func (tb *TransactionBody) SetScript(script []byte) *TransactionBody

SetScript sets the Cadence script for this transaction.

func (*TransactionBody) Sign

func (tb *TransactionBody) Sign(
	message []byte,
	privateKey crypto.PrivateKey,
	hasher hash.Hasher,
) ([]byte, error)

Sign signs the data (transaction_tag + message) with the specified private key and hasher.

This function returns an error if:

  • crypto.InvalidInputsError if the private key cannot sign with the given hasher
  • other error if an unexpected error occurs

func (*TransactionBody) SignEnvelope

func (tb *TransactionBody) SignEnvelope(
	address Address,
	keyID uint64,
	privateKey crypto.PrivateKey,
	hasher hash.Hasher,
) error

SignEnvelope signs the full transaction (TransactionDomainTag + payload + payload signatures) with the specified account key using the default transaction domain tag.

The resulting signature is combined with the account address and key ID before being added to the transaction.

This function returns an error if the signature cannot be generated.

func (*TransactionBody) SignPayload

func (tb *TransactionBody) SignPayload(
	address Address,
	keyID uint64,
	privateKey crypto.PrivateKey,
	hasher hash.Hasher,
) error

SignPayload signs the transaction payload (TransactionDomainTag + payload) with the specified account key using the default transaction domain tag.

The resulting signature is combined with the account address and key ID before being added to the transaction.

This function returns an error if the signature cannot be generated.

type TransactionField

type TransactionField int

TransactionField represents a required transaction field.

const (
	TransactionFieldUnknown TransactionField = iota
	TransactionFieldScript
	TransactionFieldRefBlockID
	TransactionFieldPayer
)

func (TransactionField) String

func (f TransactionField) String() string

String returns the string representation of a transaction field.

type TransactionResult

type TransactionResult struct {
	// TransactionID is the ID of the transaction this error was emitted from.
	TransactionID Identifier
	// ErrorMessage contains the error message of any error that may have occurred when the transaction was executed
	ErrorMessage string
	// Computation used
	ComputationUsed uint64
	// Memory used (estimation)
	MemoryUsed uint64
}

TransactionResult contains the artifacts generated after executing a Cadence transaction.

func (*TransactionResult) Checksum

func (te *TransactionResult) Checksum() Identifier

func (TransactionResult) ID

ID returns a canonical identifier that is guaranteed to be unique.

func (TransactionResult) String

func (t TransactionResult) String() string

String returns the string representation of this error.

type TransactionSignature

type TransactionSignature struct {
	Address     Address
	SignerIndex int
	KeyIndex    uint64
	Signature   []byte
}

A TransactionSignature is a signature associated with a specific account key.

func (TransactionSignature) ByteSize

func (s TransactionSignature) ByteSize() int

ByteSize returns the byte size of the transaction signature

func (TransactionSignature) Fingerprint

func (s TransactionSignature) Fingerprint() []byte

func (TransactionSignature) String

func (s TransactionSignature) String() string

String returns the string representation of a transaction signature.

type TransactionStatus

type TransactionStatus int

TransactionStatus represents the status of a transaction.

const (
	// TransactionStatusUnknown indicates that the transaction status is not known.
	TransactionStatusUnknown TransactionStatus = iota
	// TransactionStatusPending is the status of a pending transaction.
	TransactionStatusPending
	// TransactionStatusFinalized is the status of a finalized transaction.
	TransactionStatusFinalized
	// TransactionStatusExecuted is the status of an executed transaction.
	TransactionStatusExecuted
	// TransactionStatusSealed is the status of a sealed transaction.
	TransactionStatusSealed
	// TransactionStatusExpired is the status of an expired transaction.
	TransactionStatusExpired
)

func (TransactionStatus) String

func (s TransactionStatus) String() string

String returns the string representation of a transaction status.

type TransactionTiming

type TransactionTiming struct {
	TransactionID Identifier
	Received      time.Time
	Finalized     time.Time
	Executed      time.Time
}

TransactionTiming is used to track the timing/durations of a transaction through the system

func (TransactionTiming) Checksum

func (t TransactionTiming) Checksum() Identifier

func (TransactionTiming) ID

Directories

Path Synopsis
id
(c) 2021 Dapper Labs - ALL RIGHTS RESERVED
(c) 2021 Dapper Labs - ALL RIGHTS RESERVED

Jump to

Keyboard shortcuts

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