Documentation
¶
Index ¶
- Constants
- Variables
- func ConsensusCommonPrefixAggregation[T any]() func() (ConsensusAggregation[[]T], error)
- func ConsensusCommonSuffixAggregation[T any]() func() (ConsensusAggregation[[]T], error)
- func DonModeCallInNodeMode() error
- func NodeModeCallInDonMode() error
- func OrderedEntries[K cmp.Ordered, V any](m map[K]V) iter.Seq2[K, V]
- func OrderedEntriesFunc[K comparable, V any](m map[K]V, cmp func(a, b K) int) iter.Seq2[K, V]
- func ParseJSON[T any](bytes []byte) (*T, error)
- type ConsensusAggregation
- type Environment
- type ExecutionHandler
- type NodeRuntime
- type NumericType
- type Primitive
- type Promise
- func NewBasicPromise[T any](await func() (T, error)) Promise[T]
- func PromiseFromResult[T any](result T, err error) Promise[T]
- func RunInNodeMode[C, T any](config C, runtime Runtime, ...) Promise[T]
- func Then[I, O any](p Promise[I], fn func(I) (O, error)) Promise[O]
- func ThenPromise[I, O any](p Promise[I], fn func(I) Promise[O]) Promise[O]
- type Report
- func ParseReport(runtime Runtime, rawReport []byte, signatures [][]byte, reportContext []byte) (*Report, error)
- func ParseReportWithConfig(runtime Runtime, rawReport []byte, signatures [][]byte, reportContext []byte, ...) (*Report, error)
- func X_GeneratedCodeOnly_WrapReport(report *sdk.ReportResponse) (*Report, error)
- func (r *Report) Body() []byte
- func (r *Report) ConfigDigest() []byte
- func (r *Report) DONConfigVersion() uint32
- func (r *Report) DONID() uint32
- func (r *Report) ExecutionID() string
- func (r *Report) RawReport() []byte
- func (r *Report) ReportContext() []byte
- func (r *Report) ReportID() string
- func (r *Report) SeqNr() uint64
- func (r *Report) Timestamp() uint32
- func (r *Report) VerifySignatures(runtime Runtime) error
- func (r *Report) VerifySignaturesWithConfig(runtime Runtime, config ReportParseConfig) error
- func (r *Report) Version() uint32
- func (r *Report) WorkflowID() string
- func (r *Report) WorkflowName() string
- func (r *Report) WorkflowOwner() string
- func (r *Report) X_GeneratedCodeOnly_Unwrap() *sdk.ReportResponse
- type ReportParseConfig
- type ReportRequest
- type Runner
- type Runtime
- type RuntimeBase
- type Secret
- type SecretRequest
- type SecretsProvider
- type Trigger
- type Workflow
- type Zone
Examples ¶
Constants ¶
const ( DefaultMaxResponseSizeBytes = 5 * 1024 * 1024 // 5 MB ResponseBufferTooSmall = "response buffer too small" // proto encoder outputs a map with these keys so that user payload can be easily extracted ReportMetadataHeaderLength = 109 )
Variables ¶
var ( // ErrNilReport is returned when the report is nil. ErrNilReport = errors.New("report is nil") // ErrWrongSignatureCount is returned when fewer than f+1 signatures are provided. ErrWrongSignatureCount = errors.New("wrong number of signatures") // ErrParseSignature is returned when a signature cannot be parsed. ErrParseSignature = errors.New("failed to parse signature") // ErrRecoverSigner is returned when the signer address cannot be recovered from a signature. ErrRecoverSigner = errors.New("failed to recover signer address from signature") // ErrUnknownSigner is returned when a recovered signer address is not in the valid signers set. ErrUnknownSigner = errors.New("invalid signature") // ErrDuplicateSigner is returned when the same signer appears more than once. ErrDuplicateSigner = errors.New("duplicate signer") // ErrRawReportTooShort is returned when the raw report is shorter than the 109-byte metadata header. ErrRawReportTooShort = errors.New("raw report too short to contain metadata header") )
Functions ¶
func ConsensusCommonPrefixAggregation ¶
func ConsensusCommonPrefixAggregation[T any]() func() (ConsensusAggregation[[]T], error)
ConsensusCommonPrefixAggregation uses the longest common prefix across nodes. The aggregation tolerates up to F faulty nodes returning errors or different values for each element.
func ConsensusCommonSuffixAggregation ¶
func ConsensusCommonSuffixAggregation[T any]() func() (ConsensusAggregation[[]T], error)
ConsensusCommonSuffixAggregation uses the longest common suffix across nodes. The aggregation tolerates up to F faulty nodes returning errors or different values for each element.
func DonModeCallInNodeMode ¶
func DonModeCallInNodeMode() error
func NodeModeCallInDonMode ¶
func NodeModeCallInDonMode() error
func OrderedEntries ¶ added in v1.8.0
OrderedEntries returns a sequence that iterates over the entries in the map in the natural sorted order of the keys. For keys which do not implement cmp.Ordered, use OrderedEntriesFunc.
Example ¶
m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
for _, v := range OrderedEntries(m) {
fmt.Println(v)
}
Output: 1 2 3 4 5
func OrderedEntriesFunc ¶ added in v1.8.0
func OrderedEntriesFunc[K comparable, V any](m map[K]V, cmp func(a, b K) int) iter.Seq2[K, V]
OrderedEntriesFunc returns a sequence that iterates over the entries in the map based on sorting keys with the cmp func. For naturally cmp.Ordered keys, use OrderedEntries.
Example ¶
type k struct{ f string }
m := map[k]int{{"a"}: 1, {"b"}: 2, {"c"}: 3, {"d"}: 4, {"e"}: 5}
for _, v := range OrderedEntriesFunc(m, func(a, b k) int {
return cmp.Compare(a.f, b.f)
}) {
fmt.Println(v)
}
Output: 1 2 3 4 5
Types ¶
type ConsensusAggregation ¶
type ConsensusAggregation[T any] interface { // Descriptor is meant to be used by the Runtime Descriptor() *sdk.ConsensusDescriptor // Default returns the default value or nil when there is no default value Default() *T // Err is meant to be used by the Runtime Err() error // WithDefault returns a new ConsensusAggregation with the given default value // If consensus cannot be reached, the default value will be used if it is not nil instead of returning an error. WithDefault(t T) ConsensusAggregation[T] }
ConsensusAggregation is an interface that informs consensus how to aggregate values. Workflow author do not need to implement this interface directly; instead the helper functions below can be used to create instances of this interface: - ConsensusMedianAggregation - ConsensusIdenticalAggregation - ConsensusCommonPrefixAggregation - ConsensusCommonSuffixAggregation - ConsensusAggregationFromTags By using this interface with capability SDKs or RunInNodeMode, you are assured that all aggregated values are Byzantine fault-tolerant.
func ConsensusAggregationFromTags ¶
func ConsensusAggregationFromTags[T any]() ConsensusAggregation[T]
ConsensusAggregationFromTags works with structs using the `consensus_aggregation` tag to define how to aggregate each field. It supports the following tags: - `median`: for numeric types, it will take the median in the same manner as `ConsensusMedianAggregation` does for numeric types, but for a field on a struct. - `identical`: for primitive types, it will check if all values are identical in the same manner as `ConsensusIdenticalAggregation` does for primitive types, but for a field on a struct. - `common_prefix`: for slices or arrays of primitive types, it will take the longest common prefix in the same manner as `ConsensusCommonPrefixAggregation` does for slices or arrays. - `common_suffix`: for slices or arrays of primitive types, it will take the longest common suffix in the same manner as `ConsensusCommonSuffixAggregation` does for slices or arrays. - `nested`: for nested structs, it will recursively parse the struct and aggregate its fields using the same rules as above. - `ignore`: to ignore a field in the struct. If a field is not tagged or is not a valid type for the tag, it will return an error.
func ConsensusIdenticalAggregation ¶
func ConsensusIdenticalAggregation[T any]() ConsensusAggregation[T]
ConsensusIdenticalAggregation is used when responses from each node are expected to be identical. The aggregation tolerates up to F faulty nodes returning errors or different values.
func ConsensusMedianAggregation ¶
func ConsensusMedianAggregation[T NumericType]() ConsensusAggregation[T]
ConsensusMedianAggregation takes a median of all node observations. The median is Byzantine fault-tolerant and is guaranteed to be within the range of valid observations.
type Environment ¶
func ProductionEnvironment ¶ added in v1.8.0
func ProductionEnvironment() Environment
type ExecutionHandler ¶
type ExecutionHandler[C, R any] interface { CapabilityID() string Method() string TriggerCfg() *anypb.Any Callback() func(config C, runtime R, payload *anypb.Any) (any, error) }
ExecutionHandler defines a coupling of a Trigger and a callback function to be used by the SDK. The methods on the handler are meant to be used internally by the Runtime.
func Handler ¶
func Handler[C any, M proto.Message, T any, O any](trigger Trigger[M, T], callback func(config C, runtime Runtime, payload T) (O, error)) ExecutionHandler[C, Runtime]
Handler creates a coupling of a Trigger and a callback function to be used by the SDK. The coupling ensures that when the Trigger is invoked, the callback function is called with the appropriate parameters.
type NodeRuntime ¶
type NodeRuntime interface {
RuntimeBase
// IsNodeRuntime is a placeholder to differentiate NodeRuntime.
IsNodeRuntime()
}
NodeRuntime provides access to Node capabilities It is not thread safe and must not be used concurrently.
type NumericType ¶
type NumericType interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64 | ~*big.Int | decimal.Decimal | time.Time
}
NumericType represents types that can be used numerically for consensus aggregation. It includes all go primitive numeric types, big.Int, decimal.Decimal, and time.Time.
type Primitive ¶
type Primitive interface {
NumericType | ~string | ~bool
}
Primitive represents any `NumericType`, string, or bool.
type Promise ¶
type Promise[T any] interface { // Await blocks until the computation is complete and returns the result or an error. Await() (T, error) }
Promise allows for asynchronous computation, where the result can be awaited later.
func NewBasicPromise ¶
NewBasicPromise is meant to be used by Runtime implementations. It creates a new Promise that executes the provided function once awaited. This provides asynchronous callbacks in single-threaded guest environments as the host can execute while the guest continues to run.
func PromiseFromResult ¶
PromiseFromResult creates a Promise that immediately returns the provided result and error.
func RunInNodeMode ¶
func RunInNodeMode[C, T any]( config C, runtime Runtime, fn func(config C, nodeRuntime NodeRuntime) (T, error), ca ConsensusAggregation[T], ) Promise[T]
type Report ¶ added in v0.4.0
type Report struct {
// contains filtered or unexported fields
}
Report contains a signed report from the CRE workflow DON. Reports contain metadata, including the workflow ID, workflow owner, and execution ID, alongside the encoded payload, and signatures from F+1 nodes in the workflow DON. They can be used to prove that data came from a specific workflow, or author. Blockchains integrated with the CRE have forwarder contracts that can verify a report's integrity.
func ParseReport ¶ added in v1.8.0
func ParseReport(runtime Runtime, rawReport []byte, signatures [][]byte, reportContext []byte) (*Report, error)
ParseReport parses a CRE report and verifies it against the production CRE environment. The first time a DON's report is seen, the signatures will be fetched from chain. It will be cached for later report parsing.
func ParseReportWithConfig ¶ added in v1.8.0
func ParseReportWithConfig(runtime Runtime, rawReport []byte, signatures [][]byte, reportContext []byte, config ReportParseConfig) (*Report, error)
ParseReportWithConfig parses a CRE report and verifies it as specified by the config. The first time a DON's report is seen, and SkipSignatureVerification is false, the signatures will be fetched from chain. It will be cached for later report parsing.
func X_GeneratedCodeOnly_WrapReport ¶ added in v0.4.0
func X_GeneratedCodeOnly_WrapReport(report *sdk.ReportResponse) (*Report, error)
X_GeneratedCodeOnly_WrapReport is meant to be used by the code generator only.
func (*Report) Body ¶ added in v1.8.0
Body returns the workflow payload that follows the 109-byte metadata header.
func (*Report) ConfigDigest ¶ added in v1.8.0
ConfigDigest returns the OCR config digest from the ReportResponse.
func (*Report) DONConfigVersion ¶ added in v1.8.0
DONConfigVersion returns the DON configuration version from the report metadata.
func (*Report) ExecutionID ¶ added in v1.8.0
ExecutionID returns the 32-byte workflow execution ID as a hex string.
func (*Report) RawReport ¶ added in v1.8.0
RawReport returns the full raw report bytes (metadata header + body).
func (*Report) ReportContext ¶ added in v1.8.0
ReportContext returns the OCR report context bytes from the ReportResponse.
func (*Report) SeqNr ¶ added in v1.8.0
SeqNr returns the OCR sequence number from the ReportResponse.
func (*Report) Timestamp ¶ added in v1.8.0
Timestamp returns the Unix timestamp (seconds) embedded in the report metadata.
func (*Report) VerifySignatures ¶ added in v1.8.0
VerifySignatures verifies the signatures on a Report against the CRE's production environment. VerifySignatures only needs to be called if SkipSignatureVerification was used with ParseReportWithConfig. The first time a DON's report is seen, the signatures will be fetched from the chain. It will be cached for later report parsing.
func (*Report) VerifySignaturesWithConfig ¶ added in v1.8.0
func (r *Report) VerifySignaturesWithConfig(runtime Runtime, config ReportParseConfig) error
VerifySignaturesWithConfig verifies the signatures on a Report against the CRE's production environment. The first time a DON's report is seen, the signatures will be fetched from the chain. It will be cached for later report parsing. VerifySignaturesWithConfig only needs to be called if SkipSignatureVerification was used with ParseReportWithConfig. Note config.SkipSignatureVerification is ignored by this method since if it were true, signatures would not be verified at all.
func (*Report) Version ¶ added in v1.8.0
Version returns the single-byte version field from the report metadata header.
func (*Report) WorkflowID ¶ added in v1.8.0
WorkflowID returns the 32-byte workflow ID as a hex string.
func (*Report) WorkflowName ¶ added in v1.8.0
WorkflowName returns the 10-byte workflow name as a hex string.
func (*Report) WorkflowOwner ¶ added in v1.8.0
WorkflowOwner returns the 20-byte workflow owner address as a hex string.
func (*Report) X_GeneratedCodeOnly_Unwrap ¶ added in v0.4.0
func (r *Report) X_GeneratedCodeOnly_Unwrap() *sdk.ReportResponse
X_GeneratedCodeOnly_Unwrap is meant to be used by the code generator only.
type ReportParseConfig ¶ added in v1.8.0
type ReportParseConfig struct {
AcceptedZones []Zone
AcceptedEnvironments []Environment
// SkipSignatureVerification skips the signature verification step. This can be used for testing or in environments where trust is established by other means, but should be used with caution as it disables a critical security check.
// It should only be used alongside Report.Verify if filtering reports first to avoid unnecessary calls to the blockchain.
SkipSignatureVerification bool
}
type ReportRequest ¶ added in v0.6.0
type ReportRequest = sdk.ReportRequest
type Runner ¶
type Runner[C any] interface { // Run creates the workflow and starts it. // Upon registration of a workflow, a run is used to register to `Trigger`s. // Upon receiving a trigger, the appropriate handler's callback is invoked. Run(initFn func(config C, logger *slog.Logger, secretsProvider SecretsProvider) (Workflow[C], error)) }
Runner is the entry point to running a CRE workflow.
type Runtime ¶
type Runtime interface {
RuntimeBase
// RunInNodeMode is meant to be used by the helper method RunInNodeMode
RunInNodeMode(fn func(nodeRuntime NodeRuntime) *sdk.SimpleConsensusInputs) Promise[values.Value]
// GenerateReport is used to generate a report for a given ReportRequest.
GenerateReport(*ReportRequest) Promise[*Report]
SecretsProvider
}
Runtime provides access to DON capabilities and allows NodeRuntime use with consensus. It is not thread safe and must not be used concurrently.
type RuntimeBase ¶
type RuntimeBase interface {
// CallCapability is meant to be called by generated code
CallCapability(request *sdk.CapabilityRequest) Promise[*sdk.CapabilityResponse]
// Rand provides access to a random number generator for the mode the runtime operates in.
// Attempting to use the returned generator outside the correct scope will panic.
Rand() (*rand.Rand, error)
// Now provides the current time, with the mechanism for doing so based on the current mode.
Now() time.Time
// Logger provides a logger that can be used to log messages.
Logger() *slog.Logger
}
RuntimeBase provides the basic functionality of a CRE runtime. It is not thread safe and must not be used concurrently.
type SecretRequest ¶ added in v0.5.0
type SecretRequest = sdk.SecretRequest
type SecretsProvider ¶
type SecretsProvider interface {
// GetSecret retrieves a secret by its request.
GetSecret(*SecretRequest) Promise[*Secret]
}
SecretsProvider provides access to secrets.
type Trigger ¶
type Trigger[M proto.Message, T any] interface { Adapt(m M) (T, error) // contains filtered or unexported methods }
Trigger is a capability that initiates a workflow execution. This interface is meant for internal use by the Runner To obtain an implementation, use the SDKs for the capability you want to utilize.
type Workflow ¶
type Workflow[C any] []ExecutionHandler[C, Runtime]
Workflow is a sequence of ExecutionHandlers that define the logic of a CRE application.
type Zone ¶ added in v1.8.0
type Zone struct {
Environment Environment
DonID uint32
}
Zone is a specific CRE instance that has its own workflow DON. An environment can contain many zones. Most workflow authors should verify reports against ProductionEnvironment using ParseReport and Report.Verify, a Zones may be specified to lock down which production environments are allowed to sign.
func ZoneFromEnvironment ¶ added in v1.8.0
func ZoneFromEnvironment(env Environment, donId uint32) Zone