flow

package
v0.33.21 Latest Latest
Warning

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

Go to latest
Published: May 9, 2024 License: AGPL-3.0 Imports: 36 Imported by: 241

Documentation

Overview

(c) 2019 Dapper Labs - ALL RIGHTS RESERVED

Index

Constants

View Source
const (
	// Service level keys (owner is empty):
	UUIDKeyPrefix   = "uuid"
	AddressStateKey = "account_address_state"

	// Account level keys
	AccountKeyPrefix   = "a."
	AccountStatusKey   = AccountKeyPrefix + "s"
	CodeKeyPrefix      = "code."
	ContractNamesKey   = "contract_names"
	PublicKeyKeyPrefix = "public_key_"
)
View Source
const AddressLength = (linearCodeN + 7) >> 3

AddressLength is the size of an account address in bytes. (n) is the size of an account address in bits.

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 uint = 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 DefaultValueLogGCWaitDuration time.Duration = 10 * time.Minute

DefaultValueLogGCWaitDuration is the default wait duration before we repeatedly call the badger value log GC.

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 EstimatedComputationPerMillisecond = 9999.0 / 200.0

EstimatedComputationPerMillisecond is the approximate number of computation units that can be performed in a millisecond. this was calibrated during the Variable Transaction Fees: Execution Effort FLIP https://github.com/onflow/flow/pull/753

View Source
const ExtraBlocksInRootSealingSegment = DefaultTransactionExpiry - 10

ExtraBlocksInRootSealingSegment is the default number of extra blocks to be included in the the root sealing segment. "- 10" is to be backward compatible, since some dynamically bootstrapped execution nodes are using previously generated root snapshot which has about 6-7 blocks less than DefaultTransactionExpiry number of extra blocks in the sealing segment.

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 (
	ServiceEventJSONMarshaller = marshallerImpl{
		MarshalFunc:   json.Marshal,
		UnmarshalFunc: json.Unmarshal,
	}
	ServiceEventMSGPACKMarshaller = marshallerImpl{
		MarshalFunc:   msgpack.Marshal,
		UnmarshalFunc: msgpack.Unmarshal,
	}
	ServiceEventCBORMarshaller = marshallerImpl{
		MarshalFunc:   cborcodec.EncMode.Marshal,
		UnmarshalFunc: cbor.Unmarshal,
	}
)
View Source
var AddressStateRegisterID = RegisterID{
	Owner: "",
	Key:   AddressStateKey,
}
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 = BytesToAddress(nil)

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

func ByReferenceOrder(nodeIDs []Identifier) func(*Identity, *Identity) int

ByReferenceOrder return a function for sorting identities based on the order of the given nodeIDs

func Canonical added in v0.33.1

func Canonical(identity1 *Identity, identity2 *Identity) int

Canonical is a function that defines a weak strict ordering "<" for identities. It returns:

  • a strict negative number if id1 < id2
  • a strict positive number if id2 < id1
  • zero if id1 and id2 are equal

By definition, two identities (id1, id2) are in canonical order if id1's NodeID is lexicographically _strictly_ smaller than id2's NodeID. The strictness is important, meaning that identities with equal NodeIDs do not satisfy canonical ordering (order is irreflexive). Hence, only a returned strictly negative value means the pair is in canonical order. Use `IsCanonical` for canonical order checks.

The current function is based on the identifiers bytes lexicographic comparison.

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

func Deduplicate[T IDEntity](entities []T) []T

Deduplicate entities in a slice by the ID method The original order of the entities is preserved.

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

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

func IdToCid added in v0.25.0

func IdToCid(f Identifier) cid.Cid

func IdentifierCanonical added in v0.33.1

func IdentifierCanonical(id1 Identifier, id2 Identifier) int

IdentifierCanonical is a function that defines a weak strict ordering "<" for identifiers. It returns:

  • a strict negative number if id1 < id2
  • a strict positive number if id2 < id1
  • zero if id1 and id2 are equal

By definition, two Identifiers (id1, id2) are in canonical order if id1 is lexicographically _strictly_ smaller than id2. The strictness is important, meaning that duplicates do not satisfy canonical ordering (order is irreflexive). Hence, only a returned strictly negative value means the pair is in canonical order. Use `IsIdentifierCanonical` for canonical order checks.

The current function is based on the identifiers bytes lexicographic comparison. Example:

IdentifierCanonical(Identifier{1}, Identifier{2}) // -1
IdentifierCanonical(Identifier{2}, Identifier{1}) // 1
IdentifierCanonical(Identifier{1}, Identifier{1}) // 0
IdentifierCanonical(Identifier{0, 1}, Identifier{0, 2}) // -1

func IdsToBytes added in v0.25.0

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

func IsCanonical added in v0.33.1

func IsCanonical(i1, i2 *Identity) bool

IsCanonical returns true if and only if the given Identities are in canonical order.

By convention, two Identities (i1, i2) are in canonical order if i1's NodeID bytes are lexicographically _strictly_ smaller than i2's NodeID bytes.

The strictness is important, meaning that two identities with the same NodeID do not satisfy the canonical order. This also implies that the canonical order is irreflexive ((i,i) isn't in canonical order).

func IsIdentifierCanonical added in v0.33.1

func IsIdentifierCanonical(i1, i2 Identifier) bool

IsCanonical returns true if and only if the given identifiers are in canonical order.

By convention, two identifiers (i1, i2) are in canonical order if i1's bytes are lexicographically _strictly_ smaller than i2's bytes.

The strictness is important, meaning that the canonical order is irreflexive ((i,i) isn't in canonical order).

func IsIdentifierListCanonical added in v0.33.1

func IsIdentifierListCanonical(il IdentifierList) bool

IsIdentityListCanonical returns true if and only if the given list is _strictly_ sorted with regards to the canonical order.

The strictness is important here, meaning that a list with 2 equal identifiers isn't considered well sorted.

func IsIdentityListCanonical added in v0.33.1

func IsIdentityListCanonical(il IdentityList) bool

IsIdentityListCanonical returns true if and only if the given IdentityList is _strictly_ sorted with regards to the canonical order.

The strictness is important here, meaning that a list with 2 successive entities with equal NodeID isn't considered well sorted.

func ToDKGParticipantLookup added in v0.17.0

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

func ConvertAddress(b [AddressLength]byte) Address

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

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

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

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

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

type BlockExecutionDataRoot struct {
	// BlockID is the ID of the block, whose result this execution data is for.
	BlockID Identifier

	// ChunkExecutionDataIDs is a list of the root CIDs for each serialized execution_data.ChunkExecutionData
	// associated with this block.
	ChunkExecutionDataIDs []cid.Cid
}

BlockExecutionDataRoot represents the root of a serialized execution_data.BlockExecutionData. The hash of the serialized BlockExecutionDataRoot is the ExecutionDataID used within an flow.ExecutionResult. Context:

  • The trie updates in BlockExecutionDataRoot contain the _mutated_ registers only, which is helpful for clients to truslessly replicate the state.
  • In comparison, the chunk data packs contains all the register values at the chunk's starting state that were _touched_ (written and/or read). This is necessary for Verification Nodes to re-run the chunk the computation.

type BlockStatus added in v0.29.0

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

func (s BlockStatus) String() string

String returns the string representation of a transaction status.

type CertifiedBlock added in v0.30.2

type CertifiedBlock struct {
	Block        *Block
	CertifyingQC *QuorumCertificate
}

CertifiedBlock holds a certified block, which is a block and a QC that is pointing to the block. A QC is the aggregated form of votes from a supermajority of HotStuff and therefore proves validity of the block. A certified block satisfies: Block.View == QC.View and Block.BlockID == QC.BlockID

func NewCertifiedBlock added in v0.30.2

func NewCertifiedBlock(block *Block, qc *QuorumCertificate) (CertifiedBlock, error)

NewCertifiedBlock constructs a new certified block. It checks the consistency requirements and errors otherwise:

Block.View == QC.View and Block.BlockID == QC.BlockID

func (*CertifiedBlock) Height added in v0.30.2

func (b *CertifiedBlock) Height() uint64

Height returns height of the block.

func (*CertifiedBlock) ID added in v0.30.2

func (b *CertifiedBlock) ID() Identifier

ID returns unique identifier for the block. To avoid repeated computation, we use value from the QC.

func (*CertifiedBlock) View added in v0.30.2

func (b *CertifiedBlock) View() uint64

View returns view where the block was produced.

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

func (c ChainID) Transient() bool

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

type ChainIDList added in v0.31.0

type ChainIDList []ChainID

func AllChainIDs added in v0.33.1

func AllChainIDs() ChainIDList

AllChainIDs returns a list of all supported chain IDs.

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

func NewChunk(
	blockID Identifier,
	collectionIndex int,
	startState StateCommitment,
	numberOfTransactions int,
	eventCollection Identifier,
	endState StateCommitment,
	totalComputationUsed uint64,
) *Chunk

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      // ID of the chunk this data pack is for
	StartState StateCommitment // commitment for starting state
	Proof      StorageProof    // proof for all registers read during the chunk execution
	Collection *Collection     // collection executed in this chunk

	// ExecutionDataRoot is the root data structure of an execution_data.BlockExecutionData.
	// It contains the necessary information for a verification node to validate that the
	// BlockExecutionData produced is valid.
	ExecutionDataRoot BlockExecutionDataRoot
}

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 chunk. 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 NewChunkDataPack added in v0.30.0

func NewChunkDataPack(
	chunkID Identifier,
	startState StateCommitment,
	proof StorageProof,
	collection *Collection,
	execDataRoot BlockExecutionDataRoot,
) *ChunkDataPack

NewChunkDataPack returns an initialized chunk data pack.

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

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

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

func (cl 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 added in v0.17.1

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

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

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

func (*ClusterQCVoteData) EqualTo added in v0.19.0

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

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

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

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

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 {
	IDEntity

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

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

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

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

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

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
	// InvalidServiceEventIncorporated encodes whether an invalid service event is
	// incorporated in this fork. When this happens, epoch fallback is triggered
	// AFTER the fork is finalized.
	InvalidServiceEventIncorporated bool
}

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

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

func (es *EpochStatus) Copy() *EpochStatus

Copy returns a copy of the epoch status.

func (*EpochStatus) HasPrevious added in v0.15.0

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

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

type EventsList []Event

func (EventsList) ByteSize added in v0.28.7

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

type ExecutionReceiptGroupedList map[Identifier]ExecutionReceiptList

ExecutionReceiptGroupedList is a partition of an ExecutionReceiptList

func (ExecutionReceiptGroupedList) GetGroup added in v0.15.0

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

func (g ExecutionReceiptGroupedList) NumberGroups() int

NumberGroups returns the number of groups

type ExecutionReceiptGroupingFunction added in v0.15.0

type ExecutionReceiptGroupingFunction func(*ExecutionReceipt) Identifier

ExecutionReceiptGroupingFunction is a function that assigns an identifier to each receipt

type ExecutionReceiptList added in v0.15.0

type ExecutionReceiptList []*ExecutionReceipt

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

func (ExecutionReceiptList) GroupBy added in v0.15.0

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

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

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

func (ExecutionReceiptList) Size added in v0.15.0

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

func (er *ExecutionReceiptMeta) Checksum() Identifier

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

func (*ExecutionReceiptMeta) ID added in v0.16.0

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

func (ExecutionReceiptMeta) MarshalJSON added in v0.23.2

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

type ExecutionReceiptMetaGroupedList added in v0.16.1

type ExecutionReceiptMetaGroupedList map[Identifier]ExecutionReceiptMetaList

ExecutionReceiptMetaGroupedList is a partition of an ExecutionReceiptMetaList

func (ExecutionReceiptMetaGroupedList) GetGroup added in v0.16.1

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

func (g ExecutionReceiptMetaGroupedList) NumberGroups() int

NumberGroups returns the number of groups

type ExecutionReceiptMetaGroupingFunction added in v0.16.1

type ExecutionReceiptMetaGroupingFunction func(*ExecutionReceiptMeta) Identifier

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

type ExecutionReceiptMetaList added in v0.16.1

type ExecutionReceiptMetaList []*ExecutionReceiptMeta

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

func (ExecutionReceiptMetaList) GroupBy added in v0.16.1

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

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

func (ExecutionReceiptMetaList) GroupByResultID added in v0.16.1

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

func (ExecutionReceiptMetaList) Lookup added in v0.16.1

Lookup generates a map from ExecutionReceipt ID to ExecutionReceiptMeta

func (ExecutionReceiptMetaList) Size added in v0.16.1

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 // hash commitment to flow.BlockExecutionDataRoot
}

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

func NewExecutionResult added in v0.30.0

func NewExecutionResult(
	previousResultID Identifier,
	blockID Identifier,
	chunks ChunkList,
	serviceEvents ServiceEventList,
	executionDataID Identifier,
) *ExecutionResult

func (ExecutionResult) Checksum

func (er ExecutionResult) Checksum() Identifier

Checksum ...

func (ExecutionResult) FinalStateCommitment added in v0.11.0

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

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

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

func (ExecutionResult) ValidateChunksLength added in v0.17.0

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

type ExecutionResultGroupedList map[Identifier]ExecutionResultList

ExecutionResultGroupedList is a partition of an ExecutionResultList

func (ExecutionResultGroupedList) GetGroup added in v0.16.1

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

func (g ExecutionResultGroupedList) NumberGroups() int

NumberGroups returns the number of groups

type ExecutionResultGroupingFunction added in v0.16.1

type ExecutionResultGroupingFunction func(*ExecutionResult) Identifier

ExecutionResultGroupingFunction is a function that assigns an identifier to each ExecutionResult

type ExecutionResultList added in v0.16.1

type ExecutionResultList []*ExecutionResult

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

func (ExecutionResultList) GroupBy added in v0.16.1

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

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

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

Lookup generates a map from ExecutionResult ID to ExecutionResult

func (ExecutionResultList) Size added in v0.16.1

func (l ExecutionResultList) Size() int

Size returns the number of ExecutionResults in the list

type GetResultFunc added in v0.23.9

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

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 is a chain-specific value to prevent replay attacks.
	ChainID ChainID
	// ParentID is the ID of this block's parent.
	ParentID Identifier
	// Height is the height of the parent + 1
	Height uint64
	// PayloadHash is a hash of the payload of this block.
	PayloadHash Identifier
	// Timestamp is the time at which this block was proposed.
	// The proposer can choose any time, so this should not be trusted as accurate.
	Timestamp time.Time
	// View number at which this block was proposed.
	View uint64
	// ParentView number at which parent block was proposed.
	ParentView uint64
	// ParentVoterIndices is a bitvector that represents all the voters for the parent block.
	ParentVoterIndices []byte
	// ParentVoterSigData is an aggregated signature over the parent block. Not a single cryptographic
	// signature since the data represents cryptographic signatures serialized in some way (concatenation or other)
	// A quorum certificate can be extracted from the header.
	// This field is the SigData field of the extracted quorum certificate.
	ParentVoterSigData []byte
	// ProposerID is a proposer identifier for the block
	ProposerID Identifier
	// ProposerSigData is a signature of the proposer over the new block. Not a single cryptographic
	// signature since the data represents cryptographic signatures serialized in some way (concatenation or other)
	ProposerSigData []byte
	// LastViewTC is a timeout certificate for previous view, it can be nil
	// it has to be present if previous round ended with timeout.
	LastViewTC *TimeoutCertificate
}

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

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) QuorumCertificate added in v0.30.0

func (h Header) QuorumCertificate() *QuorumCertificate

QuorumCertificate returns quorum certificate that is incorporated in the block header.

func (*Header) UnmarshalCBOR added in v0.21.0

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

type IDEntity interface {
	// ID returns a unique id for this entity using a hash of the immutable
	// fields of the entity.
	ID() Identifier
}

type Identifier

type Identifier [IdentifierLen]byte

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

var EmptyEventCollectionID Identifier

func ByteSliceToId added in v0.25.0

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

func CidToId added in v0.25.0

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

func ConcatSum

func ConcatSum(ids ...Identifier) Identifier

func EntitiesToIDs added in v0.31.7

func EntitiesToIDs[T Entity](entities []T) []Identifier

func EventsMerkleRootHash added in v0.23.9

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

func MakeIDFromFingerPrint(fingerPrint []byte) Identifier

MakeIDFromFingerPrint is similar to MakeID but skipping fingerprinting step.

func MerkleRoot

func MerkleRoot(ids ...Identifier) Identifier

func MustHexStringToIdentifier added in v0.19.0

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

Sample returns non-deterministic random sample of length 'size' of the ids

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

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

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

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) Checksum added in v0.30.0

func (il IdentifierList) Checksum() Identifier

Checksum returns a cryptographic commitment to the list of identifiers.

func (IdentifierList) Contains added in v0.17.0

func (il IdentifierList) Contains(target Identifier) bool

Contains returns whether this identifier list contains the target identifier.

func (IdentifierList) Copy added in v0.17.1

func (il IdentifierList) Copy() IdentifierList

func (IdentifierList) Filter added in v0.21.0

Filter will apply a filter to the identifier list.

func (IdentifierList) ID added in v0.30.0

func (il IdentifierList) ID() Identifier

ID returns a cryptographic commitment to the list of identifiers. Since an IdentifierList has no mutable fields, it is equal to the checksum.

func (IdentifierList) Len

func (il IdentifierList) Len() int

Len returns length of the IdentifierList 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 added in v0.17.1

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

Lookup converts the Identifiers to a lookup table.

func (IdentifierList) Sample added in v0.21.0

func (il IdentifierList) Sample(size uint) (IdentifierList, error)

Sample returns random sample of length 'size' of the ids

func (IdentifierList) Sort added in v0.26.1

Sort returns a sorted _copy_ of the IdentifierList, leaving the original invariant.

func (IdentifierList) Strings added in v0.13.0

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

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

type IdentifierOrder added in v0.26.1

type IdentifierOrder func(Identifier, Identifier) int

IdentifierOrder is an order function for identifiers.

It defines a strict weak ordering between identifiers. It returns a negative number if the first identifier is "strictly less" than the second, a positive number if the second identifier is "strictly less" than the first, and zero if the two identifiers are equal.

`IdentifierOrder` can be used to sort identifiers with https://pkg.go.dev/golang.org/x/exp/slices#SortFunc.

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

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

func (*Identity) EqualTo added in v0.19.0

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

func (*Identity) Equals added in v0.33.1

func (id *Identity) Equals(other *Identity) bool

func (Identity) ID

func (iy Identity) ID() Identifier

ID returns a unique, persistent identifier for the identity. CAUTION: the ID may be chosen by a node operator, so long as it is unique.

func (Identity) MarshalCBOR added in v0.21.0

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

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

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) Checksum added in v0.30.0

func (il IdentityList) Checksum() Identifier

Checksum generates a cryptographic commitment to the full IdentityList, including mutable fields. The checksum for the same group of identities (by NodeID) may change from block to block.

func (IdentityList) Copy added in v0.12.0

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) EqualTo added in v0.19.0

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

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) GetIndex added in v0.23.9

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) ID added in v0.30.0

func (il IdentityList) ID() Identifier

ID uniquely identifies a list of identities, by node ID. This can be used to perpetually identify a group of nodes, even if mutable fields of some nodes are changed, as node IDs are immutable. CAUTION:

  • An IdentityList's ID is a cryptographic commitment to only node IDs. A node operator can freely choose the ID for their node. There is no relationship whatsoever between a node's ID and keys.
  • To generate a cryptographic commitment for the full IdentityList, use method `Checksum()`.
  • The outputs of `IdentityList.ID()` and `IdentityList.Checksum()` are both order-sensitive. Therefore, the `IdentityList` must be in canonical order, unless explicitly specified otherwise by the protocol.

func (IdentityList) IdentifierExists added in v0.25.0

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

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

func (IdentityList) Map added in v0.12.0

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

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

Sample returns non-deterministic random sample from the `IdentityList`

func (IdentityList) SamplePct

func (il IdentityList) SamplePct(pct float64) (IdentityList, error)

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) Shuffle added in v0.32.0

func (il IdentityList) Shuffle() (IdentityList, error)

Shuffle randomly shuffles the identity list (non-deterministic), and returns the shuffled list without modifying the receiver.

func (IdentityList) Sort added in v0.17.0

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) TotalWeight added in v0.25.0

func (il IdentityList) TotalWeight() uint64

TotalWeight returns the total weight of all given identities.

func (IdentityList) Union added in v0.10.1

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 canonically.

type IdentityMapFunc added in v0.12.0

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) int

IdentityOrder is an order function for identities.

It defines a strict weak ordering between identities. It returns a negative number if the first identity is "strictly less" than the second, a positive number if the second identity is "strictly less" than the first, and zero if the two identities are equal.

`IdentityOrder` can be used to sort identities with https://pkg.go.dev/golang.org/x/exp/slices#SortFunc.

type IncorporatedResult added in v0.11.0

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

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

func (*IncorporatedResult) Checksum added in v0.11.0

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

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

type IncorporatedResultGroupedList map[Identifier]IncorporatedResultList

IncorporatedResultGroupedList is a partition of an IncorporatedResultList

func (IncorporatedResultGroupedList) GetGroup added in v0.15.0

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

func (g IncorporatedResultGroupedList) NumberGroups() int

NumberGroups returns the number of groups

type IncorporatedResultGroupingFunction added in v0.15.0

type IncorporatedResultGroupingFunction func(*IncorporatedResult) Identifier

IncorporatedResultGroupingFunction is a function that assigns an identifier to each IncorporatedResult

type IncorporatedResultList added in v0.15.0

type IncorporatedResultList []*IncorporatedResult

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

func (IncorporatedResultList) GroupBy added in v0.15.0

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

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

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

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

func (IncorporatedResultList) Size added in v0.15.0

func (l IncorporatedResultList) Size() int

Size returns the number of IncorporatedResults in the list

type IncorporatedResultSeal added in v0.11.0

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

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

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

type LightTransactionResult struct {
	// TransactionID is the ID of the transaction this result was emitted from.
	TransactionID Identifier
	// Failed is true if the transaction's execution failed resulting in an error, false otherwise.
	Failed bool
	// ComputationUsed is amount of computation used while executing the transaction.
	ComputationUsed uint64
}

LightTransactionResult represents a TransactionResult, omitting any fields that are prone to non-determinism; i.e. the error message and memory used estimate.

While the net causes of a transaction failing are deterministic, the specific error and message propagated back to FVM are prone to bugs resulting in slight variations. Rather than including the error and risking execution forks if an undetected bug is introduced, we simplify it to just a boolean value. This will likely change in the future to include some additional information about the error.

Additionally, MemoryUsed is omitted because it is an estimate from the specific execution node, and will vary across nodes.

type MonotonicAddressGenerator

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

func (*MonotonicAddressGenerator) AddressCount added in v0.18.3

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. May be empty, in which case
	// only the system chunk is executed for this block.
	Guarantees []*CollectionGuarantee
	// Seals holds block seals for ancestor blocks.
	// The oldest seal must connect to the latest seal in the fork extended by this block.
	// Seals must be internally connected, containing no seals with duplicate block IDs or heights.
	// Seals may be empty. It presents a set, i.e. there is no protocol-defined ordering.
	Seals    []*Seal
	Receipts ExecutionReceiptMetaList
	Results  ExecutionResultList
}

Payload is the actual content of each block.

func EmptyPayload added in v0.12.0

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

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

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

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

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.

func (*QuorumCertificate) ID added in v0.29.0

func (qc *QuorumCertificate) ID() Identifier

ID returns the QuorumCertificate's identifier

type QuorumCertificateWithSignerIDs added in v0.26.1

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

type RegisterEntries []RegisterEntry

handy container for sorting TODO(ramtin): add canonical encoding and fingerprint for RegisterEntries

func (RegisterEntries) IDs added in v0.10.0

func (d RegisterEntries) IDs() []RegisterID

func (RegisterEntries) Len added in v0.10.0

func (d RegisterEntries) Len() int

func (RegisterEntries) Less added in v0.10.0

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

func (RegisterEntries) Swap added in v0.10.0

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

func (RegisterEntries) Values added in v0.10.0

func (d RegisterEntries) Values() []RegisterValue

type RegisterEntry added in v0.10.0

type RegisterEntry struct {
	Key   RegisterID
	Value RegisterValue
}

type RegisterID

type RegisterID struct {
	Owner string
	Key   string
}

func AccountStatusRegisterID added in v0.30.0

func AccountStatusRegisterID(address Address) RegisterID

func CadenceRegisterID added in v0.30.0

func CadenceRegisterID(owner []byte, key []byte) RegisterID

func ContractNamesRegisterID added in v0.30.0

func ContractNamesRegisterID(address Address) RegisterID

func ContractRegisterID added in v0.30.0

func ContractRegisterID(address Address, contractName string) RegisterID

func NewRegisterID added in v0.10.0

func NewRegisterID(owner Address, key string) RegisterID

func PublicKeyRegisterID added in v0.30.0

func PublicKeyRegisterID(address Address, index uint64) RegisterID

func UUIDRegisterID added in v0.30.0

func UUIDRegisterID(partition byte) RegisterID

func (*RegisterID) Bytes added in v0.19.0

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

Bytes returns a bytes representation of the RegisterID.

The encoding uses the injective fingerprint module.

func (RegisterID) IsInternalState added in v0.30.0

func (id RegisterID) IsInternalState() bool

IsInternalState returns true if the register id is controlled by flow-go and return false otherwise (key controlled by the cadence env).

func (RegisterID) IsSlabIndex added in v0.30.0

func (id RegisterID) IsSlabIndex() bool

IsSlabIndex returns true if the key is a slab index for an account's ordered fields map.

In general, each account's regular fields are stored in ordered map known only to cadence. Cadence encodes this map into bytes and split the bytes into slab chunks before storing the slabs into the ledger.

func (RegisterID) String added in v0.10.0

func (id RegisterID) String() string

String returns formatted string representation of the RegisterID.

type RegisterIDs added in v0.30.0

type RegisterIDs []RegisterID

handy container for sorting

func (RegisterIDs) Len added in v0.30.0

func (d RegisterIDs) Len() int

func (RegisterIDs) Less added in v0.30.0

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

func (RegisterIDs) Swap added in v0.30.0

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

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

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

func (r Role) Valid() bool

type RoleList added in v0.12.0

type RoleList []Role

RoleList defines a slice of roles in flow system.

func Roles

func Roles() RoleList

func (RoleList) Contains added in v0.12.0

func (r RoleList) Contains(role Role) bool

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

func (RoleList) ID added in v0.14.0

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

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

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

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

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

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

type SealedVersionBeacon added in v0.31.0

type SealedVersionBeacon struct {
	*VersionBeacon
	SealHeight uint64
}

SealedVersionBeacon is a VersionBeacon with a SealHeight field. Version beacons are effective only after the results containing the version beacon are sealed.

type SealingSegment added in v0.23.2

type SealingSegment struct {
	// Blocks contain the chain `B <- ... <- Head` in ascending height order.
	// Formally, Blocks contains exactly (not more!) the history to satisfy condition
	// (see sealing_segment.md for details):
	//   (i) The highest sealed block as of `head` needs to be included in the sealing segment.
	//       This is relevant if `head` does not contain any seals.
	Blocks []*Block

	// ExtraBlocks [optional] holds ancestors of `Blocks` in ascending height order.
	// Formally, ExtraBlocks contains at least the additional history to satisfy conditions
	// (see sealing_segment.md for details):
	//  (ii) All blocks that are sealed by `head`. This is relevant if `head` contains _multiple_ seals.
	// (iii) The sealing segment holds the history of all non-expired collection guarantees, i.e.
	//       limitHeight := max(blockSealedAtHead.Height - flow.ExtraBlocksInRootSealingSegment, SporkRootBlockHeight)
	//       where blockSealedAtHead is the block sealed by `head` block.
	// (Potentially longer history is permitted)
	ExtraBlocks []*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 a continuous segment of recently finalized blocks that contains enough history for a new node to execute its business logic normally. It is part of the data need to initialize a new node to join the network. DETAILED SPECIFICATION: ./sealing_segment.md

├═══════════┤  ├───────────────────────┤
 ExtraBlocks   ^          Blocks       ^
               B                      head

Lets denote the highest block in the sealing segment as `head`. Per convention, `head` must be a finalized block. Consider the chain of blocks leading up to `head` (included). The highest block in chain leading up to `head` that is sealed, we denote as B. In other words, head is the last finalized block, and B is the last sealed block, block at height (B.Height + 1) is not sealed.

func (*SealingSegment) AllBlocks added in v0.29.6

func (segment *SealingSegment) AllBlocks() []*Block

AllBlocks returns all blocks within the sealing segment, including extra blocks, in ascending height order.

func (*SealingSegment) Finalized added in v0.30.7

func (segment *SealingSegment) Finalized() *Block

Finalized returns the last finalized block, which is an alias of Highest

func (*SealingSegment) FinalizedSeal added in v0.26.6

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

func (segment *SealingSegment) Highest() *Block

Highest is the highest block in the sealing segment and the reference block from snapshot that was used to produce this sealing segment.

func (*SealingSegment) Sealed added in v0.29.6

func (segment *SealingSegment) Sealed() *Block

Sealed returns the most recently sealed block based on head of sealing segment(highest block).

func (*SealingSegment) Validate added in v0.23.9

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

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

SealingSegmentBuilder is a utility for incrementally building a sealing segment.

func NewSealingSegmentBuilder added in v0.23.2

func NewSealingSegmentBuilder(resultLookup GetResultFunc, sealLookup GetSealByBlockIDFunc) *SealingSegmentBuilder

NewSealingSegmentBuilder returns *SealingSegmentBuilder

func (*SealingSegmentBuilder) AddBlock added in v0.23.2

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) AddExtraBlock added in v0.29.6

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

AddExtraBlock appends an extra block to sealing segment under construction. Extra blocks needs to be added in descending order and the first block must connect to the lowest block of sealing segment, this way they form a continuous chain. No errors are expected during normal operation.

func (*SealingSegmentBuilder) SealingSegment added in v0.23.2

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

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

func (*ServiceEvent) UnmarshalCBOR added in v0.21.0

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

func (*ServiceEvent) UnmarshalJSON

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

func (*ServiceEvent) UnmarshalMsgpack added in v0.14.0

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

type ServiceEventList added in v0.19.0

type ServiceEventList []ServiceEvent

ServiceEventList is a handy container to enable comparisons

func (ServiceEventList) EqualTo added in v0.19.0

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

type ServiceEventMarshaller added in v0.31.0

type ServiceEventMarshaller interface {
	Unmarshal(b []byte) (ServiceEvent, error)
	UnmarshalWithType(
		b []byte,
		eventType ServiceEventType,
	) (
		ServiceEvent,
		error,
	)
}

type ServiceEventType added in v0.31.0

type ServiceEventType string
const (
	ServiceEventSetup         ServiceEventType = "setup"
	ServiceEventCommit        ServiceEventType = "commit"
	ServiceEventVersionBeacon ServiceEventType = "version-beacon"
)

func (ServiceEventType) String added in v0.31.0

func (set ServiceEventType) String() string

String returns the string representation of the service event type. TODO: this should not be needed. We should use ServiceEventType directly everywhere.

type Slashable added in v0.29.0

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

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

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

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

func (*StateCommitment) UnmarshalJSON added in v0.23.2

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

type TimeoutCertificate struct {
	View uint64
	// NewestQCViews lists for each signer (in the same order) the view of the newest QC they supplied
	// as part of their TimeoutObject message (specifically TimeoutObject.NewestQC.View).
	NewestQCViews []uint64
	// NewestQC is the newest QC from all TimeoutObject that were aggregated for this certificate.
	NewestQC *QuorumCertificate
	// SignerIndices encodes the HotStuff participants whose TimeoutObjects are included in this TC.
	// 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
	// SigData is an aggregated signature from multiple TimeoutObjects, each from a different replica.
	// In their TimeoutObjects, replicas sign the pair (View, NewestQCView) with their staking keys.
	SigData crypto.Signature
}

TimeoutCertificate proves that a super-majority of consensus participants want to abandon the specified View. At its core, a timeout certificate is an aggregation of TimeoutObjects, which individual nodes send to signal their intent to leave the active view.

func (*TimeoutCertificate) ID added in v0.29.0

ID returns the TimeoutCertificate's identifier

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

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

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

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

type TransactionResults []TransactionResult

TODO(ramtin): add canonical encoding and ID

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

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

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

type VersionBeacon added in v0.30.5

type VersionBeacon struct {
	VersionBoundaries []VersionBoundary
	Sequence          uint64
}

VersionBeacon represents a service event specifying the required software versions for upcoming blocks.

It contains a VersionBoundaries field, which is an ordered list of VersionBoundary (sorted by VersionBoundary.BlockHeight). While heights are strictly increasing, versions must be equal or greater when compared using semver semantics. It must contain at least one entry. The first entry is for a past block height. The remaining entries are for all future block heights. Future version boundaries can be removed, in which case the emitted event will not contain the removed version boundaries. VersionBeacon is produced by the NodeVersionBeacon smart contract.

Sequence is the event sequence number, which can be used to verify that no event has been skipped by the follower. Every time the smart contract emits a new event, it increments the sequence number by one.

func (*VersionBeacon) EqualTo added in v0.30.5

func (v *VersionBeacon) EqualTo(other *VersionBeacon) bool

EqualTo returns true if two VersionBeacons are equal. If any of the VersionBeacons has a malformed version, it will return false.

func (*VersionBeacon) ServiceEvent added in v0.30.5

func (v *VersionBeacon) ServiceEvent() ServiceEvent

func (*VersionBeacon) String added in v0.32.1

func (v *VersionBeacon) String() string

func (*VersionBeacon) Validate added in v0.31.0

func (v *VersionBeacon) Validate() error

Validate validates the internal structure of a flow.VersionBeacon. An error with an appropriate message is returned if any validation fails.

type VersionBoundary added in v0.30.5

type VersionBoundary struct {
	BlockHeight uint64
	Version     string
}

VersionBoundary represents a boundary between semver versions. BlockHeight is the first block height that must be run by the given Version (inclusive). Version is a semver string.

func (VersionBoundary) Semver added in v0.31.0

func (v VersionBoundary) Semver() (*semver.Version, error)

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