recipes

package
v0.0.0-...-afd5655 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package recipes discovers and assembles committed programs. It resolves numeric dependencies through an EVM prefix lens; full original execute is authoritative.

Index

Constants

View Source
const (
	Read uint8 = iota
	Add
	Sub
	SaturatingSub
	Min
	Max
	MulDiv
	Equal
	LessOrEqual
	Manage
	Approve
	Call
)
View Source
const (
	Literal uint8 = iota
	Input
	Result
)
View Source
const MaxInputIndex = parse.MaxInputIndex

MaxInputIndex bounds host memory used by a recipe's sparse input vector.

Variables

This section is empty.

Functions

func AccessManagerCalldata

func AccessManagerCalldata(executor common.Address, data []byte) ([]byte, error)

AccessManagerCalldata preserves atomic same-executor batches using the manager's multicall of execute calls. Only the inner execute selector needs authorization; the executor's own multicall need not be granted separately.

func AnchoredInputs

func AnchoredInputs(recipe Recipe, owned map[uint]bool) (map[uint]EconomicValue, error)

AnchoredInputs fills deterministic non-provider inputs. A recipe comparison must uniquely equate the input to a deterministic numerical expression.

func Arguments

func Arguments(types ...string) abi.Arguments

Arguments builds an ABI argument list from fixed, internally reviewed type names.

func Assemble

func Assemble(recipe Recipe, tree *Tree, inputs map[uint]string, actions map[string]hexutil.Bytes, skipSteps []uint) ([]byte, []common.Hash, error)

Assemble builds a complete execute call without evaluating the program. Explicit skipped Manage slots remain empty; full simulation must prove their gates zero. actions keys are absolute "step:action" indices, not runtime slot indices.

func BatchExecution

func BatchExecution(ctx context.Context, reader BatchReader, snapshot Snapshot, call []byte, gas uint64) ([]byte, error)

BatchExecution extends a prepared execution while its live actions make progress and the complete transaction simulates. Runtime-input recipes remain single executions: external values cannot be reused after state changes. Exponential growth and bounded prefix search avoid replaying lengths 1..N. A reverted extension, gas limit or idle gate ends the batch; RPC failures fail preparation. The final selected bytes always receive an exact simulation.

func BatchRejected

func BatchRejected(err error) bool

BatchRejected distinguishes a contract/gas rejection from transport failure.

func DelegatedMulticall

func DelegatedMulticall(calls []ExecutorCall) ([]byte, error)

DelegatedMulticall uses ERC-7579's atomic batch mode, supported by MetaMask's EIP-7702 account. No allowance, recipe management or arbitrary call is accepted.

func DiscoverExecutors

func DiscoverExecutors(ctx context.Context, reader Reader, executors []common.Address) (map[common.Address]ExecutorIdentity, error)

DiscoverExecutors reads every distinct executor at one block and checks that block again before returning. The host owns the deadline and caller policy.

func EconomicResult

func EconomicResult(v EconomicValue, results map[uint]*big.Int) (*big.Int, error)

func Executions

func Executions(data []byte) ([][]byte, error)

Executions validates and unwraps an executor's execute or homogeneous multicall.

func HasWork

func HasWork(calldata, returned []byte) (bool, error)

HasWork classifies the results of a successful full original execute call. It does not simulate execution or prove success itself. Manage is conditional on its committed gate; Call and Approve are unconditional, including zero approvals and calls with zero-valued arguments. Every instruction and the complete result vector are checked before returning a work decision.

func HashLeaf

func HashLeaf(leaf Leaf) (common.Hash, error)

func HashRecipe

func HashRecipe(recipe Recipe) (common.Hash, error)

func ManagedTargets

func ManagedTargets(calldata []byte) (map[string]common.Address, error)

ManagedTargets reads every populated Manage slot from immutable execute bytes. Gates and numerical bindings cannot change targets, so even zero-gated slots participate. Explicit empty skipped slots cannot emit a Manage event. Arbitrary Call steps are unsupported: they can invoke account.manage indirectly.

func Multicall

func Multicall(calls [][]byte) ([]byte, error)

Multicall preserves the order and original execute bytes. All entries execute on the same executor with the same caller; failure reverts the whole batch. It cannot encode management calls, nested batches or different recipes.

func ProbePrefix

func ProbePrefix(ctx context.Context, reader provider.Reader, snapshot Snapshot, recipe Recipe, before uint, runtime PrefixRuntime, code, query []byte) ([]byte, map[uint]*big.Int, error)

ProbePrefix replays an authenticated prefix at the original executor and probes its resulting state with host-owned eth_call-only code. Numerical witnesses must be verified against the full original execute before sending.

func Proof

func Proof(root, leaf common.Hash, proof []common.Hash) bool

Proof verifies the sorted-pair OpenZeppelin proof used by MerkleAccount.

func ResolveValues

func ResolveValues(ctx context.Context, reader provider.Reader, snapshot Snapshot, recipe Recipe, expressions []Value) (map[uint]*big.Int, error)

ResolveValues resolves a pure numerical prefix. Hosts with authenticated prior effects use ResolveValuesWithRuntime with the already prepared runtime data.

func ResolveValuesWithRuntime

func ResolveValuesWithRuntime(ctx context.Context, reader provider.Reader, snapshot Snapshot, recipe Recipe, expressions []Value, runtime PrefixRuntime) (map[uint]*big.Int, error)

ResolveValuesWithRuntime uses one same-executor code override for the union of signed-value dependencies, replaying authenticated Manage/Approve/Call effects before later reads. The full original execute validates the prepared witness.

func ResultsWitness

func ResultsWitness(results map[uint]*big.Int) map[uint]string

func SimulateBatch

func SimulateBatch(ctx context.Context, reader BatchReader, snapshot Snapshot, calls [][]byte, gas uint64) ([][]byte, error)

SimulateBatch obtains each execute result in one temporary EVM state. It also runs the exact multicall against the unchanged contract; only that calldata may be submitted. No helper contract is deployed on-chain.

func SimulateExecutors

func SimulateExecutors(ctx context.Context, reader BatchReader, caller common.Address, calls []ExecutorCall, block *big.Int, gas uint64) ([][]byte, error)

SimulateExecutors returns every execution's values after its predecessors. The final check executes the exact envelope through the installed delegation; replacement code is used only to inspect values omitted by ERC-7579 execute.

func SupportsDelegatedBatch

func SupportsDelegatedBatch(ctx context.Context, reader BatchReader, caller common.Address, block *big.Int) (bool, error)

SupportsDelegatedBatch detects the installed EIP-7702 account without changing its delegation. A delegated account that lacks atomic batches is an error.

func ValidatePrefix

func ValidatePrefix(recipe Recipe, expressions []Value, runtime PrefixRuntime) error

ValidatePrefix performs source/dependency validation without network I/O.

func ValidatePreparedBatch

func ValidatePreparedBatch(ctx context.Context, reader Reader, prepared []PreparedRecipe, calls []ExecutorCall, leaves [][]common.Hash, witnesses []map[uint]string, caller common.Address, maxGas ...uint64) error

ValidatePreparedBatch authenticates all selected members at one fresh head, simulates the exact transaction and closes every distinct block pin together. Cache entries become visible only after complete admission succeeds. The optional maxGas budget defaults to 16,777,216 when omitted or zero and is bounded by the fresh block gas limit. More than one budget is invalid.

func ValidatePreparedBatchForSender

func ValidatePreparedBatchForSender(ctx context.Context, reader Reader, prepared []PreparedRecipe, calls []ExecutorCall, leaves [][]common.Hash, witnesses []map[uint]string, caller, sender common.Address, maxGas ...uint64) error

ValidatePreparedBatchForSender checks immediate AccessManager authorization, the exact outer call and the executor's results under the signing EOA at the same fresh block. Forwarded plans contain one executor (which may batch several executions); independent executors are admitted on subsequent ticks.

func ValidatePreparedBatchWithSimulation

func ValidatePreparedBatchWithSimulation(ctx context.Context, reader Reader, prepared []PreparedRecipe, calls []ExecutorCall, leaves [][]common.Hash, caller common.Address, simulate PreparedBatchSimulation, maxGas ...uint64) error

ValidatePreparedBatchWithSimulation shares recipe, identity, role and canonical guards with ValidatePreparedBatch. Its mandatory callback validates an external envelope instead of generic result witnesses and HasWork classification. The optional maxGas budget has the same defaults and bounds as that entry point.

func ValidatePreparedRoutesWithSimulation

func ValidatePreparedRoutesWithSimulation(ctx context.Context, reader Reader, prepared []PreparedRecipe, calls []ExecutorCall, leaves [][]common.Hash, executor common.Address, simulate PreparedBatchSimulation, maxGas ...uint64) error

ValidatePreparedRoutesWithSimulation authenticates each recipe's own caller at the same fresh block and simulates the complete external transaction once. The callback receives the outer executor as Caller and must exercise every selected recipe, including any AccessManager forwarding.

func ValidateProbePrefix

func ValidateProbePrefix(recipe Recipe, before uint, runtime PrefixRuntime) error

ValidateProbePrefix rejects unresolved runtime dependencies before network I/O.

func VerifyResults

func VerifyResults(calldata, returned []byte, witness map[uint]string) error

VerifyResults validates prepared indices against the original immutable steps and checks the original executor's returned values, including on recovery.

Types

type BatchReader

type BatchReader interface {
	Reader
	provider.CodeOverrideReader
	// contains filtered or unexported methods
}

BatchReader adds original bytecode and eth_call-only code overrides to the ordinary pinned recipe reader. The chain client implements it directly.

type Binding

type Binding struct {
	Offset uint32
	Value  Value
}

type DiscoveryResult

type DiscoveryResult struct {
	Prepared PreparedRecipe
	Err      error
}

DiscoveryResult keeps one candidate's authenticated evidence or local failure. An error-free result still requires prepared-batch admission before execution.

func DiscoverCandidates

func DiscoverCandidates(ctx context.Context, reader Reader, executors, accounts []common.Address, caller common.Address, options PreparationOptions) ([]DiscoveryResult, error)

DiscoverCandidates pins all candidates to one head and batches metadata, shared roots and event evidence. A local member failure preserves independent results; transport failures and the closing common block guard fail the group.

type EconomicValue

type EconomicValue struct {
	Expression Value
	Upper      []Value
	Lower      []Value
	Input      *uint
	// Exact means the field itself is bound to this result. A provider must not
	// select a different signed value, even when it exceeds a minimum floor.
	Exact bool
}

func Budget

func Budget(recipe Recipe, value Value, before uint) (EconomicValue, error)

Budget requires the recipe to select an exact amount. Bounds validate that amount; they never choose it. Use MIN/MAX arithmetic in the recipe to express a capped amount, bound directly or through an input equality.

func ExactValue

func ExactValue(recipe Recipe, value Value, before uint) (EconomicValue, error)

ExactValue resolves deterministic recipe values, including literal and constant-arithmetic results. Inputs require an exact preceding equality; a ceiling never selects a request ID, epoch or other identity index.

func Floor

func Floor(recipe Recipe, value Value, before uint) ([]EconomicValue, error)

Floor combines the recipe's preceding lower bounds. Equality remains exact.

type ExecutorCall

type ExecutorCall struct {
	Executor common.Address `json:"executor"`
	Data     hexutil.Bytes  `json:"data"`
}

ExecutorCall keeps the committed execution attached to its own executor.

func RouteExecution

func RouteExecution(ctx context.Context, reader Reader, snapshot Snapshot, sender common.Address, data []byte) (ExecutorCall, error)

RouteExecution preserves the authenticated recipe payload and routes it through its on-chain caller when that caller is an AccessManager. Delayed grants cannot execute an atomic fill and are rejected; this never schedules an operation.

type ExecutorIdentity

type ExecutorIdentity struct {
	Account common.Address
	Caller  common.Address
}

ExecutorIdentity contains the account and authorized caller observed together.

type Inspection

type Inspection struct {
	Slots  []RuntimeSlot
	Inputs []uint
}

func Inspect

func Inspect(recipe Recipe) (Inspection, error)

Inspect checks instruction structure and references without interpreting values. Original payload bytes are retained: Solidity permits trailing ABI data.

type Leaf

type Leaf struct {
	Hash           common.Hash
	Target         common.Address
	Value          *big.Int
	Data, DataMask []byte
	Proof          []common.Hash
}

type ManagedAction

type ManagedAction struct {
	Key      string
	Step     uint
	Slot     RuntimeSlot
	Leaf     Leaf
	Bindings []Binding
}

ManagedAction retains the authenticated template and its exact instruction.

func ManagedActions

func ManagedActions(recipe Recipe, tree *Tree) ([]ManagedAction, error)

func (ManagedAction) Field

func (a ManagedAction) Field(offset int) (Value, error)

Field identifies a complete, non-overlapping word binding. Unbound numerical fields cannot acquire policy merely from a masked permission preimage.

func (ManagedAction) Pinned

func (a ManagedAction) Pinned(offset, length int) error

Pinned checks an identity field is fully committed and cannot be rebound.

type MemberError

type MemberError struct {
	Index int
	// Indices contains every inactive member after a successful canonical envelope.
	// Index remains the first member for callers handling one error at a time.
	Indices []int
	Err     error
}

MemberError identifies runtime data that must be deferred without discarding other independent candidates. Contract and gas rejection concern the envelope.

func (*MemberError) Error

func (e *MemberError) Error() string

func (*MemberError) Unwrap

func (e *MemberError) Unwrap() error

type PrefixRuntime

type PrefixRuntime struct {
	Tree            *Tree
	Inputs          map[uint]string
	Actions         map[string]hexutil.Bytes
	SkipSteps       []uint
	AvailableInputs map[uint]bool
	BlockedActions  map[string]bool
}

PrefixRuntime contains only authenticated outputs already prepared before the shared lens. AvailableInputs permits pure preflight before external fetches; Resolve requires each such input to actually exist. BlockedActions prevents executing unresolved quote templates as if their placeholder bytes were data.

type PreparationOptions

type PreparationOptions struct {
	ChainID *big.Int
	Cache   *RecipeCache
}

PreparationOptions configures authenticated recipe discovery and its RAM cache.

type PreparedBatchSimulation

type PreparedBatchSimulation func(context.Context, PreparedBatchSimulationRequest) error

PreparedBatchSimulation must simulate the exact selected calls inside the unchanged external envelope at the supplied block and gas limit. The host owns external usefulness and settlement semantics; no inner return bytes are needed.

type PreparedBatchSimulationRequest

type PreparedBatchSimulationRequest struct {
	Calls       []ExecutorCall
	Caller      common.Address
	BlockNumber *big.Int
	GasLimit    uint64
}

PreparedBatchSimulationRequest contains independent copies of authenticated calls and their fresh execution context. Mutating it cannot change admission.

type PreparedRecipe

type PreparedRecipe struct {
	Snapshot Snapshot
	Recipe   Recipe
	// contains filtered or unexported fields
}

PreparedRecipe is provisional authenticated discovery. Providers may inspect a copy of Recipe; prepared-batch admission authenticates assembled execution bytes.

func DiscoverBatch

func DiscoverBatch(ctx context.Context, reader Reader, executors, accounts []common.Address, caller common.Address, options PreparationOptions) ([]PreparedRecipe, error)

DiscoverBatch requires every configured member to authenticate successfully. Startup callers retain strict behavior while sharing the partial discovery core.

type Reader

type Reader interface {
	CallContract(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error)
	HeaderByNumber(context.Context, *big.Int) (*types.Header, error)
	FilterLogs(context.Context, ethereum.FilterQuery) ([]types.Log, error)
}

type Recipe

type Recipe struct {
	Queries [][]byte
	// Each committed step is one opcode byte followed by its ABI payload.
	Steps [][]byte
}

func CloneRecipe

func CloneRecipe(r Recipe) Recipe

func DecodeRecipe

func DecodeRecipe(encoded []byte) (Recipe, error)

type RecipeCache

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

RecipeCache retains only exact, previously authenticated event bodies. It is safe to share across planners/goroutines. Entries are copied under the mutex; discovery and callbacks never hold the lock. Eviction is insertion-order FIFO, bounded by both entries and a conservative retained-byte charge (including payloads, slice slots, key and entry/allocation overhead). Transient copies are not retained and are released with their preparation attempt.

func NewRecipeCache

func NewRecipeCache(capacity int, bytes int64) *RecipeCache

NewRecipeCache returns nil when either bound disables caching. Host callers derive capacity from their configured strategy count, never untrusted events.

type RuntimeSlot

type RuntimeSlot struct {
	Index, StepIndex uint
	Operation        uint8
	Gate, Amount     Value
	Leaves           []common.Hash
	Bindings         [][]Binding
	Token, Spender   common.Address
}

type Snapshot

type Snapshot struct {
	BlockNumber               uint64
	BlockHash                 common.Hash
	Timestamp                 uint64
	Executor, Account, Caller common.Address
	Sender                    common.Address `json:"-"` // Optional transaction origin for simulation.
	RecipeHash, Root          common.Hash
	RecipeBlock               uint64
}

type Tree

type Tree struct {
	Root    common.Hash
	ChainID *big.Int
	Account *common.Address
	Leaves  []Leaf
}

func CloneTree

func CloneTree(t *Tree) *Tree

func DecodeTree

func DecodeTree(data []byte) (*Tree, error)

func LoadTree

func LoadTree(path string) (*Tree, error)

LoadTree accepts both the Solidity/frontend leaves artifact and the permission service calls artifact. Display metadata is ignored; all cryptographic data is verified, including unused leaves. Proofs may describe a subset of the root.

type Value

type Value struct {
	Source uint8
	Value  *big.Int
}

func EconomicExpressions

func EconomicExpressions(value EconomicValue) []Value

EconomicExpressions includes every bound whose value must be proved before requesting external data.

func Operands

func Operands(recipe Recipe, index uint) ([]Value, error)

Operands decodes every Value one instruction reads, in ABI order: binding values for Read and Call, the gate then bindings for Manage, and the amount for Approve.

Jump to

Keyboard shortcuts

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