logic

package
v0.0.0-...-13169aa Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: AGPL-3.0 Imports: 51 Imported by: 7

README

The Algorand Virtual Machine (AVM) and TEAL.

The AVM is a bytecode based stack interpreter that executes programs associated with Algorand transactions. TEAL is an assembly language syntax for specifying a program that is ultimately converted to AVM bytecode. These programs can be used to check the parameters of the transaction and approve the transaction as if by a signature. This use is called a Smart Signature. Starting with v2, these programs may also execute as Smart Contracts, which are often called Applications. Contract executions are invoked with explicit application call transactions.

Programs have read-only access to the transaction they are attached to, the other transactions in their atomic transaction group, and a few global values. In addition, Smart Contracts have access to limited state that is global to the application, per-account local state for each account that has opted-in to the application, and additional per-application arbitrary state in named boxes. For both types of program, approval is signaled by finishing with the stack containing a single non-zero uint64 value, though return can be used to signal an early approval which approves based only upon the top stack value being a non-zero uint64 value.

The Stack

The stack starts empty and can contain values of either uint64 or byte-arrays (byte-arrays may not exceed 4096 bytes in length). Most operations act on the stack, popping arguments from it and pushing results to it. Some operations have immediate arguments that are encoded directly into the instruction, rather than coming from the stack.

The maximum stack depth is 1000. If the stack depth is exceeded or if a byte-array element exceeds 4096 bytes, the program fails. If an opcode is documented to access a position in the stack that does not exist, the operation fails. Most often, this is an attempt to access an element below the stack -- the simplest example is an operation like concat which expects two arguments on the stack. If the stack has fewer than two elements, the operation fails. Some operations, like frame_dig and proto could fail because of an attempt to access above the current stack.

Stack Types

While every element of the stack is restricted to the types uint64 and bytes, the values of these types may be known to be bounded. The more common bounded types are named to provide more semantic information in the documentation. They're also used during assembly time to do type checking and to provide more informative error messages.

Documentation

Index

Constants

View Source
const (
	// NoOp = transactions.NoOpOC
	NoOp = OnCompletionConstType(transactions.NoOpOC)
	// OptIn = transactions.OptInOC
	OptIn = OnCompletionConstType(transactions.OptInOC)
	// CloseOut = transactions.CloseOutOC
	CloseOut = OnCompletionConstType(transactions.CloseOutOC)
	// ClearState = transactions.ClearStateOC
	ClearState = OnCompletionConstType(transactions.ClearStateOC)
	// UpdateApplication = transactions.UpdateApplicationOC
	UpdateApplication = OnCompletionConstType(transactions.UpdateApplicationOC)
	// DeleteApplication = transactions.DeleteApplicationOC
	DeleteApplication = OnCompletionConstType(transactions.DeleteApplicationOC)
)
View Source
const AssemblerDefaultVersion = 1

AssemblerDefaultVersion what version of code do we emit by default AssemblerDefaultVersion is set to 1 on purpose to prevent accidental building of v1 official templates with version 2 because these templates are not aware of rekeying.

View Source
const AssemblerMaxVersion = LogicVersion

AssemblerMaxVersion is a maximum supported assembler version

View Source
const LogicVersion = 13

LogicVersion defines default assembler and max eval versions

Variables

View Source
var (
	// StackUint64 is any valid uint64
	StackUint64 = NewStackType(avmUint64, bound(0, math.MaxUint64))
	// StackBytes is any valid bytestring
	StackBytes = NewStackType(avmBytes, bound(0, maxStringSize))
	// StackAny could be Bytes or Uint64
	StackAny = StackType{
		Name:    avmAny.String(),
		AVMType: avmAny,
		Bound:   [2]uint64{0, 0},
	}
	// StackNone is used when there is no input or output to
	// an opcode
	StackNone = StackType{
		Name:    avmNone.String(),
		AVMType: avmNone,
	}

	// StackBoolean constrains the int to 1 or 0, representing True or False
	StackBoolean = NewStackType(avmUint64, bound(0, 1), "bool")
	// StackAddress represents an address
	StackAddress = NewStackType(avmBytes, static(32), "address")
	// StackBytes32 represents a bytestring that should have exactly 32 bytes
	StackBytes32 = NewStackType(avmBytes, static(32), "[32]byte")
	// StackBytes64 represents a bytestring that should have exactly 64 bytes
	StackBytes64 = NewStackType(avmBytes, static(64), "[64]byte")
	// StackBytes80 represents a bytestring that should have exactly 80 bytes
	StackBytes80 = NewStackType(avmBytes, static(80), "[80]byte")
	// StackBigInt represents a bytestring that should be treated like an int
	StackBigInt = NewStackType(avmBytes, bound(0, maxByteMathSize), "bigint")
	// StackMethodSelector represents a bytestring that should be treated like a method selector
	StackMethodSelector = NewStackType(avmBytes, static(4), "method")
	// StackStateKey represents a bytestring that can be used as a key to some storage (global/local/box)
	StackStateKey = NewStackType(avmBytes, bound(0, 64), "stateKey")
	// StackBoxName represents a bytestring that can be used as a key to a box
	StackBoxName = NewStackType(avmBytes, bound(1, 64), "boxName")

	// StackZeroUint64 is a StackUint64 with a minimum value of 0 and a maximum value of 0
	StackZeroUint64 = NewStackType(avmUint64, bound(0, 0), "0")
	// StackZeroBytes is a StackBytes with a minimum length of 0 and a maximum length of 0
	StackZeroBytes = NewStackType(avmUint64, bound(0, 0), "''")

	// AllStackTypes is a map of all the stack types we recognize
	// so that we can iterate over them in doc prep
	// and use them for opcode proto shorthand
	AllStackTypes = map[byte]StackType{
		'a': StackAny,
		'b': StackBytes,
		'i': StackUint64,
		'x': StackNone,
		'A': StackAddress,
		'I': StackBigInt,
		'T': StackBoolean,
		'M': StackMethodSelector,
		'K': StackStateKey,
		'N': StackBoxName,
	}
)
View Source
var AcctParamsFields = FieldGroup{
	"acct_params", "Fields",
	acctParamsFieldNames[:],
	acctParamsFieldSpecByName,
}

AcctParamsFields describes acct_params_get's immediates

View Source
var AppParamsFields = FieldGroup{
	"app_params", "Fields",
	appParamsFieldNames[:],
	appParamsFieldSpecByName,
}

AppParamsFields describes app_params_get's immediates

View Source
var AssetHoldingFields = FieldGroup{
	"asset_holding", "Fields",
	assetHoldingFieldNames[:],
	assetHoldingFieldSpecByName,
}

AssetHoldingFields describes asset_holding_get's immediates

View Source
var AssetParamsFields = FieldGroup{
	"asset_params", "Fields",
	assetParamsFieldNames[:],
	assetParamsFieldSpecByName,
}

AssetParamsFields describes asset_params_get's immediates

View Source
var Base64Encodings = FieldGroup{
	"base64", "Encodings",
	base64EncodingNames[:],
	base64EncodingSpecByName,
}

Base64Encodings describes the base64_encode immediate

View Source
var BlockFields = FieldGroup{
	"block", "Fields",
	blockFieldNames[:],
	blockFieldSpecByName,
}

BlockFields describes the json_ref immediate

View Source
var EcGroups = FieldGroup{
	"EC", "Groups",
	ecGroupNames[:],
	ecGroupSpecByName,
}

EcGroups collects details about the constants used to describe EcGroups

View Source
var EcdsaCurves = FieldGroup{
	"ECDSA", "Curves",
	ecdsaCurveNames[:],
	ecdsaCurveSpecByName,
}

EcdsaCurves collects details about the constants used to describe EcdsaCurves

View Source
var GlobalFieldNames [invalidGlobalField]string

GlobalFieldNames are arguments to the 'global' opcode

View Source
var GlobalFields = FieldGroup{
	"global", "Fields",
	GlobalFieldNames[:],
	globalFieldSpecByName,
}

GlobalFields has info on the global opcode's immediate

View Source
var ItxnSettableFields = FieldGroup{
	"itxn_field", "",
	itxnSettableFieldNames(),
	txnFieldSpecByName,
}

ItxnSettableFields collects info for itxn_field opcode

View Source
var JSONRefTypes = FieldGroup{
	"json_ref", "Types",
	jsonRefTypeNames[:],
	jsonRefSpecByName,
}

JSONRefTypes describes the json_ref immediate

View Source
var MimcConfigs = FieldGroup{
	"MimcConfigurations", "Parameters",
	mimcConfigNames[:],
	mimcConfigSpecByName,
}

MimcConfigs collects details about the constants used to describe MimcConfigs

View Source
var OnCompletionDescriptions = map[string]string{
	NoOp.String():              "_Only_ execute the Approval Program associated with the _application ID_, with no additional effects.",
	OptIn.String():             "_Before_ executing the Approval Program, allocate _local state_ for this _application ID_ into the _sender_'s account data.",
	CloseOut.String():          "_After_ executing the Approval Program, clear any _local state_ for this _application ID_ out of the _sender_'s account data.",
	ClearState.String():        "_Do not_ execute the Approval Program, and instead execute the Clear State Program (which may not reject this transaction). Additionally, clear any _local state_ for the _application ID_ out of the _sender_’s account data (as in `CloseOutOC`).",
	UpdateApplication.String(): "_After_ executing the Approval Program, _replace_ the Approval Program and Clear State Program associated with the _application ID_ with the programs specified in this transaction.",
	DeleteApplication.String(): "_After_ executing the Approval Program, _delete_ the parameters of with the _application ID_ from the account data of the application’s creator.",
}

OnCompletionDescriptions end up in the spec, describing what happens for each OnCompletion value.

View Source
var OnCompletionNames [invalidOnCompletionConst]string

OnCompletionNames is the string names of Txn.OnCompletion, array index is the const value

View Source
var OpGroups = map[string][]string{
	"Arithmetic":              {"+", "-", "/", "*", "<", ">", "<=", ">=", "&&", "||", "shl", "shr", "sqrt", "bitlen", "exp", "==", "!=", "!", "itob", "btoi", "%", "|", "&", "^", "~", "mulw", "addw", "divw", "divmodw", "expw"},
	"Byte Array Manipulation": {"getbit", "setbit", "getbyte", "setbyte", "concat", "len", "substring", "substring3", "extract", "extract3", "extract_uint16", "extract_uint32", "extract_uint64", "replace2", "replace3", "base64_decode", "json_ref"},
	"Byte Array Arithmetic":   {"b+", "b-", "b/", "b*", "b<", "b>", "b<=", "b>=", "b==", "b!=", "b%", "bsqrt"},
	"Byte Array Logic":        {"b|", "b&", "b^", "b~"},
	"Cryptography":            {"sha256", "keccak256", "sha512_256", "sha3_256", "sha512", "sumhash512", "falcon_verify", "ed25519verify", "ed25519verify_bare", "ecdsa_verify", "ecdsa_pk_recover", "ecdsa_pk_decompress", "vrf_verify", "ec_add", "ec_scalar_mul", "ec_pairing_check", "ec_multi_scalar_mul", "ec_subgroup_check", "ec_map_to", "mimc"},
	"Loading Values":          {"intcblock", "intc", "intc_0", "intc_1", "intc_2", "intc_3", "pushint", "pushints", "bytecblock", "bytec", "bytec_0", "bytec_1", "bytec_2", "bytec_3", "pushbytes", "pushbytess", "bzero", "arg", "arg_0", "arg_1", "arg_2", "arg_3", "args", "txn", "gtxn", "txna", "txnas", "gtxna", "gtxnas", "gtxns", "gtxnsa", "gtxnsas", "global", "load", "loads", "store", "stores", "gload", "gloads", "gloadss", "gaid", "gaids"},
	"Flow Control":            {"err", "bnz", "bz", "b", "return", "pop", "popn", "dup", "dup2", "dupn", "dig", "bury", "cover", "uncover", "frame_dig", "frame_bury", "swap", "select", "assert", "callsub", "proto", "retsub", "switch", "match"},
	"Block Access":            {"online_stake", "log", "block"},
	"Account Access":          {"balance", "min_balance", "acct_params_get", "voter_params_get"},
	"Asset Access":            {"asset_holding_get", "asset_params_get"},
	"Application Access":      {"app_opted_in", "app_local_get", "app_local_get_ex", "app_global_get", "app_global_get_ex", "app_local_put", "app_global_put", "app_local_del", "app_global_del", "app_params_get"},
	"Box Access":              {"box_create", "box_extract", "box_replace", "box_splice", "box_del", "box_len", "box_get", "box_put", "box_resize"},
	"Inner Transactions":      {"itxn_begin", "itxn_next", "itxn_field", "itxn_submit", "itxn", "itxna", "itxnas", "gitxn", "gitxna", "gitxnas"},
}

OpGroups is groupings of ops for documentation purposes. The order here is the order args opcodes are presented, so place related opcodes consecutively, even if their opcode values are not.

View Source
var OpSpecs = []OpSpec{}/* 199 elements not displayed */

OpSpecs is the table of operations that can be assembled and evaluated.

Note: assembly can specialize an Any return type if known at assembly-time, with ops.returns()

View Source
var OpsByName [LogicVersion + 1]map[string]OpSpec

OpsByName map for each version, mapping opcode name to OpSpec

View Source
var TxnArrayFields = FieldGroup{
	"txna", "Fields (see [transaction reference](https://developer.algorand.org/docs/reference/transactions/))",
	txnaFieldNames(),
	txnFieldSpecByName,
}

TxnArrayFields narows TxnFields to only have the names of array fetching opcodes

View Source
var TxnFieldNames [invalidTxnField]string

TxnFieldNames are arguments to the 'txn' family of opcodes.

View Source
var TxnFields = FieldGroup{
	"txn", "",
	TxnFieldNames[:],
	txnFieldSpecByName,
}

TxnFields contains info on the arguments to the txn* family of opcodes

View Source
var TxnScalarFields = FieldGroup{
	"txn", "Fields (see [transaction reference](https://developer.algorand.org/docs/reference/transactions/))",
	txnScalarFieldNames(),
	txnFieldSpecByName,
}

TxnScalarFields narrows TxnFields to only have the names of scalar fetching opcodes

TxnTypeNames is the values of Txn.Type in enum order

View Source
var TypeNameDescriptions = map[string]string{
	string(protocol.UnknownTx):         "Unknown type, invalid transaction",
	string(protocol.PaymentTx):         "ALGO transfers (payment)",
	string(protocol.KeyRegistrationTx): "Consensus keys registration",
	string(protocol.AssetConfigTx):     "Asset creation and configuration",
	string(protocol.AssetTransferTx):   "Asset transfer",
	string(protocol.AssetFreezeTx):     "Asset freeze and unfreeze",
	string(protocol.ApplicationCallTx): "Application calls",
	string(protocol.StateProofTx):      "State Proof",
	string(protocol.HeartbeatTx):       "Consensus heartbeat",
}

TypeNameDescriptions contains descriptions about low level protocol transaction types.

View Source
var VoterParamsFields = FieldGroup{
	"voter_params", "Fields",
	voterParamsFieldNames[:],
	voterParamsFieldSpecByName,
}

VoterParamsFields describes voter_params_get's immediates

View Source
var VrfStandards = FieldGroup{
	"vrf_verify", "Standards",
	vrfStandardNames[:],
	vrfStandardSpecByName,
}

VrfStandards describes the json_ref immediate

Functions

func AppStateQuerying

func AppStateQuerying(
	cx *EvalContext,
	appState AppStateEnum, stateOp AppStateOpEnum,
	appID basics.AppIndex, account basics.Address, key string) basics.TealValue

AppStateQuerying is used for simulation endpoint exec trace export: it reads *new* app state after opcode that writes to app-state. Since it is collecting new/updated app state, we don't have to error again here, and thus we omit the error or non-existence case, just returning empty TealValue. Otherwise, we find the updated new state value, and wrap up with new TealValue.

func CheckContract

func CheckContract(program []byte, gi int, params *EvalParams) error

CheckContract should be faster than EvalContract. It can perform static checks and reject programs that are invalid. Prior to v4, these static checks include a cost estimate that must be low enough (controlled by params.Proto).

func CheckSignature

func CheckSignature(gi int, params *EvalParams) error

CheckSignature should be faster than EvalSignature. It can perform static checks and reject programs that are invalid. Prior to v4, these static checks include a cost estimate that must be low enough (controlled by params.Proto).

func Disassemble

func Disassemble(program []byte) (text string, err error)

Disassemble produces a text form of program bytes. AssembleString(Disassemble()) should result in the same program bytes.

func EvalApp

func EvalApp(program []byte, gi int, aid basics.AppIndex, params *EvalParams) (bool, error)

EvalApp is a lighter weight interface that doesn't return the EvalContext

func EvalSignature

func EvalSignature(gi int, params *EvalParams) (bool, error)

EvalSignature evaluates the logicsig of the ith transaction in params. A program passes successfully if it finishes with one int element on the stack that is non-zero.

func GetProgramID

func GetProgramID(program []byte) string

GetProgramID returns program or execution ID that is string representation of sha256 checksum. It is used later to link program on the user-facing side of the debugger with TEAL evaluator.

func HasStatefulOps

func HasStatefulOps(program []byte) (bool, error)

HasStatefulOps checks if the program has stateful opcodes

func HashProgram

func HashProgram(program []byte) crypto.Digest

HashProgram takes program bytes and returns the Digest This Digest can be used as an Address for a logic controlled account.

func MakeSourceMapLine

func MakeSourceMapLine(tcol, sindex, sline, scol int) string

MakeSourceMapLine creates source map mapping's line entry

func MustAssemble

func MustAssemble(text string) []byte

MustAssemble assembles a program and panics on error. It is useful for defining globals.

func TxnFieldToTealValue

func TxnFieldToTealValue(txn *transactions.Transaction, groupIndex int, field TxnField, arrayFieldIdx uint64, inner bool) (basics.TealValue, error)

TxnFieldToTealValue is a thin wrapper for txnFieldToStack for external use

Types

type AcctParamsField

type AcctParamsField int

AcctParamsField is an enum for `acct_params_get` opcode

const (
	// AcctBalance is the balance, with pending rewards
	AcctBalance AcctParamsField = iota
	// AcctMinBalance is algos needed for this accounts apps and assets
	AcctMinBalance
	// AcctAuthAddr is the rekeyed address if any, else ZeroAddress
	AcctAuthAddr

	// AcctTotalNumUint is the count of all uints from created global apps or opted in locals
	AcctTotalNumUint
	// AcctTotalNumByteSlice is the count of all byte slices from created global apps or opted in locals
	AcctTotalNumByteSlice

	// AcctTotalExtraAppPages is the extra code pages across all apps
	AcctTotalExtraAppPages

	// AcctTotalAppsCreated is the number of apps created by this account
	AcctTotalAppsCreated
	// AcctTotalAppsOptedIn is the number of apps opted in by this account
	AcctTotalAppsOptedIn
	// AcctTotalAssetsCreated is the number of ASAs created by this account
	AcctTotalAssetsCreated
	// AcctTotalAssets is the number of ASAs opted in by this account (always includes AcctTotalAssetsCreated)
	AcctTotalAssets
	// AcctTotalBoxes is the number of boxes created by the app this account is associated with
	AcctTotalBoxes
	// AcctTotalBoxBytes is the number of bytes in all boxes of this app account
	AcctTotalBoxBytes

	// AcctIncentiveEligible is whether this account opted into block payouts by
	// paying extra in `keyreg`. Does not reflect eligibility based on balance.
	AcctIncentiveEligible
	// AcctLastProposed is the last time this account proposed. Does not include _this_ round.
	AcctLastProposed
	// AcctLastHeartbeat is the last heartbeat from this account.
	AcctLastHeartbeat
)

func (AcctParamsField) String

func (i AcctParamsField) String() string

type AppParamsField

type AppParamsField int

AppParamsField is an enum for `app_params_get` opcode

const (
	// AppApprovalProgram AppParams.ApprovalProgram
	AppApprovalProgram AppParamsField = iota
	// AppClearStateProgram AppParams.ClearStateProgram
	AppClearStateProgram
	// AppGlobalNumUint AppParams.StateSchemas.GlobalStateSchema.NumUint
	AppGlobalNumUint
	// AppGlobalNumByteSlice AppParams.StateSchemas.GlobalStateSchema.NumByteSlice
	AppGlobalNumByteSlice
	// AppLocalNumUint AppParams.StateSchemas.LocalStateSchema.NumUint
	AppLocalNumUint
	// AppLocalNumByteSlice AppParams.StateSchemas.LocalStateSchema.NumByteSlice
	AppLocalNumByteSlice
	// AppExtraProgramPages AppParams.ExtraProgramPages
	AppExtraProgramPages

	// AppCreator is not *in* the Params, but it is uniquely determined.
	AppCreator

	// AppAddress is also not *in* the Params, but can be derived
	AppAddress

	// AppVersion begins at 0 and increasing each time either program changes
	AppVersion

	// AppSizeSponsor is responsible for extra pages and global state balance requirement.
	AppSizeSponsor
)

func (AppParamsField) String

func (i AppParamsField) String() string

type AppStateEnum

type AppStateEnum uint64

AppStateEnum stands for the enum of app state type, should be one of global/local/box.

const (
	// GlobalState stands for global state of an app.
	GlobalState AppStateEnum = iota + 1

	// LocalState stands for local state of an app.
	LocalState

	// BoxState stands for box storage of an app.
	BoxState
)

type AppStateOpEnum

type AppStateOpEnum uint64

AppStateOpEnum stands for the operation enum to app state, should be one of create, write, read, delete.

const (
	// AppStateWrite stands for writing to an app state.
	AppStateWrite AppStateOpEnum = iota + 1

	// AppStateDelete stands for deleting an app state.
	AppStateDelete

	// AppStateRead stands for reading from an app state.
	AppStateRead
)

type AssetHoldingField

type AssetHoldingField int

AssetHoldingField is an enum for `asset_holding_get` opcode

const (
	// AssetBalance AssetHolding.Amount
	AssetBalance AssetHoldingField = iota
	// AssetFrozen AssetHolding.Frozen
	AssetFrozen
)

func (AssetHoldingField) String

func (i AssetHoldingField) String() string

type AssetParamsField

type AssetParamsField int

AssetParamsField is an enum for `asset_params_get` opcode

const (
	// AssetTotal AssetParams.Total
	AssetTotal AssetParamsField = iota
	// AssetDecimals AssetParams.Decimals
	AssetDecimals
	// AssetDefaultFrozen AssetParams.AssetDefaultFrozen
	AssetDefaultFrozen
	// AssetUnitName AssetParams.UnitName
	AssetUnitName
	// AssetName AssetParams.AssetName
	AssetName
	// AssetURL AssetParams.URL
	AssetURL
	// AssetMetadataHash AssetParams.MetadataHash
	AssetMetadataHash
	// AssetManager AssetParams.Manager
	AssetManager
	// AssetReserve AssetParams.Reserve
	AssetReserve
	// AssetFreeze AssetParams.Freeze
	AssetFreeze
	// AssetClawback AssetParams.Clawback
	AssetClawback

	// AssetCreator is not *in* the Params, but it is uniquely determined.
	AssetCreator
)

func (AssetParamsField) String

func (i AssetParamsField) String() string

type Base64Encoding

type Base64Encoding int

Base64Encoding is an enum for the `base64decode` opcode

const (
	// URLEncoding represents the base64url encoding defined in https://www.rfc-editor.org/rfc/rfc4648.html
	URLEncoding Base64Encoding = iota
	// StdEncoding represents the standard encoding of the RFC
	StdEncoding
)

func (Base64Encoding) String

func (i Base64Encoding) String() string

type BlockField

type BlockField int

BlockField is an enum for the `block` opcode

const (
	// BlkSeed is the Block's vrf seed
	BlkSeed BlockField = iota
	// BlkTimestamp is the Block's timestamp, seconds from epoch
	BlkTimestamp
	// BlkProposer is the Block's proposer, or ZeroAddress, pre Payouts.Enabled
	BlkProposer
	// BlkFeesCollected is the sum of fees for the block, or 0, pre Payouts.Enabled
	BlkFeesCollected
	// BlkBonus is the extra amount to be paid for the given block (from FeeSink)
	BlkBonus
	// BlkBranch is the hash of the previous block
	BlkBranch
	// BlkFeeSink is the fee sink for the given round
	BlkFeeSink
	// BlkProtocol is the ConsensusVersion of the block.
	BlkProtocol
	// BlkTxnCounter is the number of the next transaction after the block
	BlkTxnCounter
	// BlkProposerPayout is the actual amount moved from feesink to proposer
	BlkProposerPayout

	// BlkBranch512 is the wider, sha-512 hash of the previous block
	BlkBranch512

	// BlkSha512_256TxnCommitment is "Algorand Native" txn merkle root
	BlkSha512_256TxnCommitment

	// BlkSha256TxnCommitment is the sha256 txn merkle root
	BlkSha256TxnCommitment

	// BlkSha512TxnCommitment is the sha512 txn merkle root
	BlkSha512TxnCommitment
)

func (BlockField) String

func (i BlockField) String() string

type BoxOperation

type BoxOperation int

BoxOperation is an enum of box operation types

const (
	// BoxCreateOperation creates a box
	BoxCreateOperation BoxOperation = iota
	// BoxReadOperation reads a box
	BoxReadOperation
	// BoxWriteOperation writes to a box
	BoxWriteOperation
	// BoxDeleteOperation deletes a box
	BoxDeleteOperation
	// BoxResizeOperation resizes a box
	BoxResizeOperation
)

type CallFrame

type CallFrame struct {
	FrameLine int    `codec:"frameLine"`
	LabelName string `codec:"labelname"`
}

CallFrame stores the label name and the line of the subroutine. An array of CallFrames form the CallStack.

type DebugState

type DebugState struct {
	// fields set once on Register
	ExecID      string                         `codec:"execid"`
	Disassembly string                         `codec:"disasm"`
	PCOffset    []PCOffset                     `codec:"pctooffset"`
	TxnGroup    []transactions.SignedTxnWithAD `codec:"txngroup"`
	GroupIndex  int                            `codec:"gindex"`
	Proto       *config.ConsensusParams        `codec:"proto"`
	Globals     []basics.TealValue             `codec:"globals"`

	// fields updated every step
	PC           int                `codec:"pc"`
	Line         int                `codec:"line"`
	Stack        []basics.TealValue `codec:"stack"`
	Scratch      []basics.TealValue `codec:"scratch"`
	Error        string             `codec:"error"`
	OpcodeBudget int                `codec:"budget"`
	CallStack    []CallFrame        `codec:"callstack"`

	// global/local state changes are updated every step. Stateful TEAL only.
	transactions.EvalDelta
}

DebugState is a representation of the evaluation context that we encode to json and send to tealdbg

func (*DebugState) LineToPC

func (d *DebugState) LineToPC(line int) int

LineToPC converts line to pc Return 0 on unsuccess

func (*DebugState) PCToLine

func (d *DebugState) PCToLine(pc int) int

PCToLine converts pc to line Return 0 on unsuccess

type Debugger deprecated

type Debugger interface {
	// Register is fired on program creation
	Register(state *DebugState)
	// Update is fired on every step
	Update(state *DebugState)
	// Complete is called when the program exits
	Complete(state *DebugState)
}

Debugger is an interface that supports the first version of AVM debuggers. It consists of a set of functions called by eval function during AVM program execution.

Deprecated: This interface does not support non-app call or inner transactions. Use EvalTracer instead.

type EcGroup

type EcGroup int

EcGroup is an enum for `ec_` opcodes

const (
	// BN254g1 is the G1 group of BN254
	BN254g1 EcGroup = iota
	// BN254g2 is the G2 group of BN254
	BN254g2
	// BLS12_381g1 specifies the G1 group of BLS 12-381
	BLS12_381g1
	// BLS12_381g2 specifies the G2 group of BLS 12-381
	BLS12_381g2
)

func (EcGroup) String

func (i EcGroup) String() string

type EcdsaCurve

type EcdsaCurve int

EcdsaCurve is an enum for `ecdsa_` opcodes

const (
	// Secp256k1 curve for bitcoin/ethereum
	Secp256k1 EcdsaCurve = iota
	// Secp256r1 curve
	Secp256r1
)

func (EcdsaCurve) String

func (i EcdsaCurve) String() string

type EvalConstants

type EvalConstants struct {
	// MaxLogSize is the limit of total log size from n log calls in a program
	MaxLogSize int

	// MaxLogCalls is the limit of total log calls during a program execution
	MaxLogCalls int

	// UnnamedResources, if provided, allows resources to be used without being named according to
	// this policy.
	UnnamedResources UnnamedResourcePolicy
}

EvalConstants contains constant parameters that are used by opcodes during evaluation (including both real-execution and simulation).

func RuntimeEvalConstants

func RuntimeEvalConstants() EvalConstants

RuntimeEvalConstants gives a set of const params used in normal runtime of opcodes

type EvalContext

type EvalContext struct {
	*EvalParams

	Stack []stackValue

	Scratch scratchSpace
	// contains filtered or unexported fields
}

EvalContext is the execution context of AVM bytecode. It contains the full state of the running program, and tracks some of the things that the program has done, like log messages and inner transactions.

func EvalContract

func EvalContract(program []byte, gi int, aid basics.AppIndex, params *EvalParams) (bool, *EvalContext, error)

EvalContract executes stateful program as the gi'th transaction in params

func EvalSignatureFull

func EvalSignatureFull(gi int, params *EvalParams) (bool, *EvalContext, error)

EvalSignatureFull evaluates the logicsig of the ith transaction in params. A program passes successfully if it finishes with one int element on the stack that is non-zero. It returns EvalContext suitable for obtaining additional info about the execution.

func (*EvalContext) AppID

func (cx *EvalContext) AppID() basics.AppIndex

AppID returns the ID of the currently executing app. For LogicSigs it returns 0.

func (*EvalContext) Cost

func (cx *EvalContext) Cost() int

Cost return cost incurred so far

func (*EvalContext) GetOpSpec

func (cx *EvalContext) GetOpSpec() OpSpec

GetOpSpec queries for the OpSpec w.r.t. current program byte.

func (*EvalContext) GetProgram

func (cx *EvalContext) GetProgram() []byte

GetProgram queries for the current program

func (*EvalContext) GroupIndex

func (cx *EvalContext) GroupIndex() int

GroupIndex returns the group index of the transaction being evaluated

func (*EvalContext) PC

func (cx *EvalContext) PC() int

PC returns the program counter of the current application being evaluated

func (*EvalContext) ProgramVersion

func (cx *EvalContext) ProgramVersion() uint64

ProgramVersion returns the AVM version of the current program.

func (*EvalContext) RunMode

func (cx *EvalContext) RunMode() RunMode

RunMode returns the evaluation context's mode (signature or application)

type EvalError

type EvalError struct {
	Err error
	// contains filtered or unexported fields
}

EvalError indicates AVM evaluation failure

func (EvalError) Error

func (err EvalError) Error() string

Error satisfies builtin interface `error`

func (EvalError) Unwrap

func (err EvalError) Unwrap() error

type EvalErrorDetailsTracer

type EvalErrorDetailsTracer struct{ NullEvalTracer }

EvalErrorDetailsTracer enables disassembled details in EvalError messages, and nothing else.

func (EvalErrorDetailsTracer) DetailedEvalErrors

func (EvalErrorDetailsTracer) DetailedEvalErrors() bool

DetailedEvalErrors returns true.

type EvalParams

type EvalParams struct {
	Proto *config.ConsensusParams

	Trace *strings.Builder

	TxnGroup []transactions.SignedTxnWithAD

	SigLedger LedgerForSignature
	Ledger    LedgerForLogic

	// optional tracer
	Tracer EvalTracer

	// Amount "overpaid" by the transactions of the group.  Often 0.  When
	// positive, it can be spent by inner transactions.  Shared across a group's
	// txns, so that it can be updated (including upward, by overpaying inner
	// transactions). nil is treated as 0 (used before fee pooling is enabled).
	FeeCredit *uint64

	Specials *transactions.SpecialAddresses

	// Total pool of app call budget in a group transaction (nil before budget pooling enabled)
	PooledApplicationBudget *int

	// Total pool of logicsig budget in a group transaction (nil before lsig pooling enabled)
	PooledLogicSigBudget *int

	// SurplusReadBudget is the number of bytes from the IO budget that were not
	// used for reading in boxes before evaluation began. In other words, the
	// txn group could have read in SurplusReadBudget more box bytes, but did
	// not.  It is signed because `simulate` evaluates groups even if they come
	// in with insufficient io budget, and reports the need, when invoked with
	// AllowUnnamedResources.
	SurplusReadBudget int64

	EvalConstants
	// contains filtered or unexported fields
}

EvalParams contains data that comes into condition evaluation.

func NewAppEvalParams

func NewAppEvalParams(txgroup []transactions.SignedTxnWithAD, proto *config.ConsensusParams, specials *transactions.SpecialAddresses) *EvalParams

NewAppEvalParams creates an EvalParams to use while evaluating a top-level txgroup.

func NewInnerEvalParams

func NewInnerEvalParams(txg []transactions.SignedTxnWithAD, caller *EvalContext) *EvalParams

NewInnerEvalParams creates an EvalParams to be used while evaluating an inner group txgroup

func NewSigEvalParams

func NewSigEvalParams(txgroup []transactions.SignedTxn, proto *config.ConsensusParams, ls LedgerForSignature) *EvalParams

NewSigEvalParams creates an EvalParams to be used while evaluating a group's logicsigs

func (*EvalParams) BoxDirtyBytes

func (ep *EvalParams) BoxDirtyBytes() uint64

BoxDirtyBytes returns the number of bytes that have been written to boxes

func (*EvalParams) GetApplicationAddress

func (ep *EvalParams) GetApplicationAddress(app basics.AppIndex) basics.Address

GetApplicationAddress memoizes app.Address() across a tx group's evaluation

func (*EvalParams) GetCaller

func (ep *EvalParams) GetCaller() *EvalContext

GetCaller returns the calling EvalContext if this is an inner transaction evaluation. Otherwise, this returns nil.

func (*EvalParams) GetIOBudget

func (ep *EvalParams) GetIOBudget() uint64

GetIOBudget returns the current IO budget for the group.

func (*EvalParams) RecordAD

func (ep *EvalParams) RecordAD(gi int, ad transactions.ApplyData)

RecordAD notes ApplyData information that was derived outside of the logic package. For example, after a acfg transaction is processed, the AD created by the acfg is added to the EvalParams this way.

func (*EvalParams) SetIOBudget

func (ep *EvalParams) SetIOBudget(ioBudget uint64)

SetIOBudget sets the IO budget for the group.

type EvalTracer

type EvalTracer interface {
	// BeforeBlock is called once at the beginning of block evaluation. It is passed the block header.
	BeforeBlock(hdr *bookkeeping.BlockHeader)

	// BeforeTxnGroup is called before a transaction group is executed. This includes both top-level
	// and inner transaction groups. The argument ep is the EvalParams object for the group; if the
	// group is an inner group, this is the EvalParams object for the inner group.
	//
	// Each transaction within the group calls BeforeTxn and subsequent hooks, as described in the
	// lifecycle diagram.
	BeforeTxnGroup(ep *EvalParams)

	// AfterTxnGroup is called after a transaction group has been executed. This includes both
	// top-level and inner transaction groups. The argument ep is the EvalParams object for the
	// group; if the group is an inner group, this is the EvalParams object for the inner group.
	// For top-level transaction groups, the deltas argument is the ledgercore.StateDelta changes
	// that occurred because of this transaction group. For inner transaction groups, this argument
	// is nil.
	AfterTxnGroup(ep *EvalParams, deltas *ledgercore.StateDelta, evalError error)

	// BeforeTxn is called before a transaction is executed.
	//
	// groupIndex refers to the index of the transaction in the transaction group that will be executed.
	BeforeTxn(ep *EvalParams, groupIndex int)

	// AfterTxn is called after a transaction has been executed.
	//
	// groupIndex refers to the index of the transaction in the transaction group that was just executed.
	// ad is the ApplyData result of the transaction; prefer using this instead of
	// ep.TxnGroup[groupIndex].ApplyData, since it may not be populated at this point.
	AfterTxn(ep *EvalParams, groupIndex int, ad transactions.ApplyData, evalError error)

	// BeforeProgram is called before an app or LogicSig program is evaluated.
	BeforeProgram(cx *EvalContext)

	// AfterProgram is called after an app or LogicSig program is evaluated.
	AfterProgram(cx *EvalContext, pass bool, evalError error)

	// BeforeOpcode is called before the op is evaluated
	BeforeOpcode(cx *EvalContext)

	// AfterOpcode is called after the op has been evaluated
	AfterOpcode(cx *EvalContext, evalError error)

	// AfterBlock is called after the block has finished evaluation. It will not be called in the event that an evalError
	// stops evaluation of the block.
	AfterBlock(hdr *bookkeeping.BlockHeader)

	// DetailedEvalErrors permits the tracer to enable detailed EvalError messages (including PC with disassembled
	// opcodes) by returning true.
	DetailedEvalErrors() bool
}

EvalTracer functions are called by eval function during AVM program execution, if a tracer is provided.

Refer to the lifecycle graph below for the sequence in which hooks are called.

NOTE: Arguments given to Tracer hooks (EvalParams and EvalContext) are passed by reference, they are not copies. It is therefore the responsibility of the tracer implementation to NOT modify the state of the structs passed to them. Additionally, hooks are responsible for copying the information they need from the argument structs. No guarantees are made that the referenced state will not change between hook calls. This decision was made in an effort to reduce the performance impact of tracers.

LOGICSIG LIFECYCLE GRAPH
┌─────────────────────────┐
│ LogicSig Evaluation     │
├─────────────────────────┤
│ > BeforeProgram         │
│                         │
│  ┌───────────────────┐  │
│  │ Teal Operation    │  │
│  ├───────────────────┤  │
│  │ > BeforeOpcode    │  │
│  │                   │  │
│  │ > AfterOpcode     │  │
│  └───────────────────┘  │
|   ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞   │
│                         │
│ > AfterProgram          │
└─────────────────────────┘

APP LIFECYCLE GRAPH
┌──────────────────────────────────────────────────────┐
│ Transaction Evaluation                               │
├──────────────────────────────────────────────────────┤
│ > BeforeTxnGroup                                     │
│                                                      │
│  ┌────────────────────────────────────────────────┐  │
│  │ > BeforeTxn                                    │  │
│  │                                                │  │
│  │  ┌──────────────────────────────────────────┐  │  │
│  │  │ ? App Call                               │  │  │
│  │  ├──────────────────────────────────────────┤  │  │
│  │  │ > BeforeProgram                          │  │  │
│  │  │                                          │  │  │
│  │  │  ┌────────────────────────────────────┐  │  │  │
│  │  │  │ Teal Operation                     │  │  │  │
│  │  │  ├────────────────────────────────────┤  │  │  │
│  │  │  │ > BeforeOpcode                     │  │  │  │
│  │  │  │  ┌──────────────────────────────┐  │  │  │  │
│  │  │  │  │ ? Inner Transaction Group    │  │  │  │  │
│  │  │  │  ├──────────────────────────────┤  │  │  │  │
│  │  │  │  │ > BeforeTxnGroup             │  │  │  │  │
│  │  │  │  │  ┌────────────────────────┐  │  │  │  │  │
│  │  │  │  │  │ Transaction Evaluation │  │  │  │  │  │
│  │  │  │  │  ├────────────────────────┤  │  │  │  │  │
│  │  │  │  │  │ ...                    │  │  │  │  │  │
│  │  │  │  │  └────────────────────────┘  │  │  │  │  │
│  │  │  │  │    ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞    │  │  │  │  │
│  │  │  │  │                              │  │  │  │  │
│  │  │  │  │ > AfterTxnGroup              │  │  │  │  │
│  │  │  │  └──────────────────────────────┘  │  │  │  │
│  │  │  │ > AfterOpcode                      │  │  │  │
│  │  │  └────────────────────────────────────┘  │  │  │
│  │  │    ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞    │  │  │
│  │  │                                          │  │  │
│  │  │ > AfterProgram                           │  │  │
│  │  └──────────────────────────────────────────┘  │  │
|  |    ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞    │  |
│  │                                                │  │
│  │ > AfterTxn                                     │  │
│  └────────────────────────────────────────────────┘  │
|    ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞  ⁞    |
│                                                      │
│ > AfterTxnGroup                                      │
└──────────────────────────────────────────────────────┘

Block Lifecycle Graph
┌──────────────────────────────────────────────────────┐
│ Block Evaluation                                     │
│  ┌────────────────────────────────────────────────┐  │
│  │ > BeforeBlock                                  │  │
│  │                                                │  │
│  │  ┌──────────────────────────────────────────┐  │  │
│  │  │ > Transaction/LogicSig Lifecycle         │  │  │
│  │  ├──────────────────────────────────────────┤  │  │
│  │  │  ┌────────────────────────────────────┐  │  │  │
│  │  │  │ ...                                │  │  │  │
│  │  │  └────────────────────────────────────┘  │  │  │
│  │  └──────────────────────────────────────────┘  │  │
│  ├────────────────────────────────────────────────│  │
│  │ > AfterBlock                                   │  │
│  └────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────┘

func MakeEvalTracerDebuggerAdaptor

func MakeEvalTracerDebuggerAdaptor(debugger Debugger) EvalTracer

MakeEvalTracerDebuggerAdaptor creates an adaptor that externally adheres to the EvalTracer interface, but drives a Debugger interface

Warning: The output EvalTracer is specifically designed to be invoked under the exact same circumstances that the previous Debugger interface was invoked. This means that it will only work properly if you attach it directly to a logic.EvalParams and execute a program. If you attempt to run this EvalTracer under a different entry point (such as by attaching it to a BlockEvaluator), it WILL NOT work properly.

type FieldGroup

type FieldGroup struct {
	Name  string
	Doc   string
	Names []string
	// contains filtered or unexported fields
}

FieldGroup binds all the info for a field (names, int value, spec access) so they can be attached to opcodes and used by doc generation

func (FieldGroup) Heading

func (fg FieldGroup) Heading() string

Heading returns a documentation heading for this FieldGroup.

func (*FieldGroup) SpecByName

func (fg *FieldGroup) SpecByName(name string) (FieldSpec, bool)

SpecByName returns a FieldsSpec for a name, respecting the "sparseness" of the Names array to hide some names

type FieldSpec

type FieldSpec interface {
	Field() byte
	Type() StackType
	OpVersion() uint64
	Note() string
	Version() uint64
}

FieldSpec unifies the various specs for assembly, disassembly, and doc generation.

type GlobalField

type GlobalField uint64

GlobalField is an enum for `global` opcode

const (
	// MinTxnFee ConsensusParams.MinTxnFee
	MinTxnFee GlobalField = iota
	// MinBalance ConsensusParams.MinBalance
	MinBalance
	// MaxTxnLife ConsensusParams.MaxTxnLife
	MaxTxnLife
	// ZeroAddress [32]byte{0...}
	ZeroAddress
	// GroupSize len(txn group)
	GroupSize

	// LogicSigVersion ConsensusParams.LogicSigVersion
	LogicSigVersion
	// Round basics.Round
	Round
	// LatestTimestamp uint64
	LatestTimestamp
	// CurrentApplicationID uint64
	CurrentApplicationID

	// CreatorAddress [32]byte
	CreatorAddress

	// CurrentApplicationAddress [32]byte
	CurrentApplicationAddress
	// GroupID [32]byte
	GroupID

	// OpcodeBudget The remaining budget available for execution
	OpcodeBudget

	// CallerApplicationID The ID of the caller app, else 0
	CallerApplicationID

	// CallerApplicationAddress The Address of the caller app, else ZeroAddress
	CallerApplicationAddress

	// AssetCreateMinBalance is the additional minimum balance required to
	// create an asset (which also opts an account into that asset)
	AssetCreateMinBalance

	// AssetOptInMinBalance is the additional minimum balance required to opt in to an asset
	AssetOptInMinBalance

	// GenesisHash is the genesis hash for the network
	GenesisHash

	// PayoutsEnabled is whether block proposal payouts are enabled
	PayoutsEnabled

	// PayoutsGoOnlineFee is the fee required in a keyreg transaction to make an account incentive eligible
	PayoutsGoOnlineFee

	// PayoutsPercent is the percentage of transaction fees in a block that can be paid to the block proposer.
	PayoutsPercent

	// PayoutsMinBalance is the minimum algo balance an account must have to receive block payouts (in the agreement round).
	PayoutsMinBalance

	// PayoutsMaxBalance is the maximum algo balance an account can have to receive block payouts (in the agreement round).
	PayoutsMaxBalance
)

func (GlobalField) String

func (i GlobalField) String() string

type JSONRefType

type JSONRefType int

JSONRefType is an enum for the `json_ref` opcode

const (
	// JSONString represents string json value
	JSONString JSONRefType = iota
	// JSONUint64 represents uint64 json value
	JSONUint64
	// JSONObject represents json object
	JSONObject
)

func (JSONRefType) String

func (i JSONRefType) String() string

type LedgerForLogic

type LedgerForLogic interface {
	AccountData(addr basics.Address) (ledgercore.AccountData, error)
	Authorizer(addr basics.Address) (basics.Address, error)
	Round() basics.Round
	PrevTimestamp() int64

	// These are simplifications of the underlying Ledger methods that take a
	// round argument. They implicitly use agreement's BalanceRound (320 back).
	AgreementData(addr basics.Address) (basics.OnlineAccountData, error)
	OnlineStake() (basics.MicroAlgos, error)

	AssetHolding(addr basics.Address, assetIdx basics.AssetIndex) (basics.AssetHolding, error)
	AssetParams(aidx basics.AssetIndex) (basics.AssetParams, basics.Address, error)
	AppParams(aidx basics.AppIndex) (basics.AppParams, basics.Address, error)
	OptedIn(addr basics.Address, appIdx basics.AppIndex) (bool, error)

	GetLocal(addr basics.Address, appIdx basics.AppIndex, key string, accountIdx uint64) (value basics.TealValue, exists bool, err error)
	SetLocal(addr basics.Address, appIdx basics.AppIndex, key string, value basics.TealValue, accountIdx uint64) error
	DelLocal(addr basics.Address, appIdx basics.AppIndex, key string, accountIdx uint64) error

	GetGlobal(appIdx basics.AppIndex, key string) (value basics.TealValue, exists bool, err error)
	SetGlobal(appIdx basics.AppIndex, key string, value basics.TealValue) error
	DelGlobal(appIdx basics.AppIndex, key string) error

	NewBox(appIdx basics.AppIndex, key string, value []byte, appAddr basics.Address) error
	GetBox(appIdx basics.AppIndex, key string) ([]byte, bool, error)
	SetBox(appIdx basics.AppIndex, key string, value []byte) error
	DelBox(appIdx basics.AppIndex, key string, appAddr basics.Address) (bool, error)

	Perform(gi int, ep *EvalParams) error
	Counter() uint64
}

LedgerForLogic represents ledger API for Stateful TEAL program

type LedgerForSignature

type LedgerForSignature interface {
	BlockHdr(basics.Round) (bookkeeping.BlockHeader, error)
	GenesisHash() crypto.Digest
}

LedgerForSignature represents the parts of Ledger that LogicSigs can see. It only exposes things that consensus has already agreed upon, so it is "stateless" for signature purposes.

type MimcConfig

type MimcConfig int

MimcConfig is an enum for the `mimc` opcode

const (
	// BN254Mp110 is the default MiMC configuration for the BN254 curve with Miyaguchi-Preneel mode, 110 rounds, exponent 5, seed "seed"
	BN254Mp110 MimcConfig = iota
	// BLS12_381Mp111 is the default MiMC configuration for the BLS12-381 curve with Miyaguchi-Preneel mode, 111 rounds, exponent 5, seed "seed"
	BLS12_381Mp111
)

func (MimcConfig) String

func (i MimcConfig) String() string

type Msg

type Msg struct {
	ProgramHash crypto.Digest `codec:"p"`
	Data        []byte        `codec:"d"`
	// contains filtered or unexported fields
}

Msg is data meant to be signed and then verified with the ed25519verify opcode.

func (Msg) ToBeHashed

func (msg Msg) ToBeHashed() (protocol.HashID, []byte)

ToBeHashed implements crypto.Hashable

type MultisigProgram

type MultisigProgram struct {
	Addr    crypto.Digest
	Program []byte
}

MultisigProgram is a wrapper for signing programs with multisig addresses.

func (MultisigProgram) ToBeHashed

func (mp MultisigProgram) ToBeHashed() (protocol.HashID, []byte)

ToBeHashed implements crypto.Hashable for MultisigProgram

type NoHeaderLedger

type NoHeaderLedger struct {
}

NoHeaderLedger is intended for debugging TEAL in isolation(no real ledger) in which it is reasonable to preclude the use of `block`, `txn LastValidTime`. Also `global GenesisHash` is just a static value.

func (NoHeaderLedger) BlockHdr

BlockHdr always errors

func (NoHeaderLedger) GenesisHash

func (NoHeaderLedger) GenesisHash() crypto.Digest

GenesisHash returns a fixed value

type NullEvalTracer

type NullEvalTracer struct{}

NullEvalTracer implements EvalTracer, but all of its hook methods do nothing

func (NullEvalTracer) AfterBlock

func (n NullEvalTracer) AfterBlock(hdr *bookkeeping.BlockHeader)

AfterBlock does nothing

func (NullEvalTracer) AfterOpcode

func (n NullEvalTracer) AfterOpcode(cx *EvalContext, evalError error)

AfterOpcode does nothing

func (NullEvalTracer) AfterProgram

func (n NullEvalTracer) AfterProgram(cx *EvalContext, pass bool, evalError error)

AfterProgram does nothing

func (NullEvalTracer) AfterTxn

func (n NullEvalTracer) AfterTxn(ep *EvalParams, groupIndex int, ad transactions.ApplyData, evalError error)

AfterTxn does nothing

func (NullEvalTracer) AfterTxnGroup

func (n NullEvalTracer) AfterTxnGroup(ep *EvalParams, deltas *ledgercore.StateDelta, evalError error)

AfterTxnGroup does nothing

func (NullEvalTracer) BeforeBlock

func (n NullEvalTracer) BeforeBlock(hdr *bookkeeping.BlockHeader)

BeforeBlock does nothing

func (NullEvalTracer) BeforeOpcode

func (n NullEvalTracer) BeforeOpcode(cx *EvalContext)

BeforeOpcode does nothing

func (NullEvalTracer) BeforeProgram

func (n NullEvalTracer) BeforeProgram(cx *EvalContext)

BeforeProgram does nothing

func (NullEvalTracer) BeforeTxn

func (n NullEvalTracer) BeforeTxn(ep *EvalParams, groupIndex int)

BeforeTxn does nothing

func (NullEvalTracer) BeforeTxnGroup

func (n NullEvalTracer) BeforeTxnGroup(ep *EvalParams)

BeforeTxnGroup does nothing

func (NullEvalTracer) DetailedEvalErrors

func (n NullEvalTracer) DetailedEvalErrors() bool

DetailedEvalErrors does nothing

type OnCompletionConstType

type OnCompletionConstType transactions.OnCompletion

OnCompletionConstType is the same as transactions.OnCompletion

func (OnCompletionConstType) String

func (i OnCompletionConstType) String() string

type OpDesc

type OpDesc struct {
	Short      string
	Extra      string
	Immediates []string
	Sugar      string // pseudo calling information
}

OpDesc contains the human readable descriptions of opcodes and their immediate arguments.

func OpDescOf

func OpDescOf(opName string) OpDesc

OpDescOf returns the OpDesc for a mnemonic opcode

type OpDetails

type OpDetails struct {
	Modes RunMode // all modes that opcode can run in. i.e (cx.mode & Modes) != 0 allows

	FullCost   linearCost  // if non-zero, the cost of the opcode, no immediates matter
	Size       int         // if non-zero, the known size of opcode. if 0, check() determines.
	Immediates []immediate // details of each immediate arg to opcode
	// contains filtered or unexported fields
}

OpDetails records details such as non-standard costs, immediate arguments, or dynamic layout controlled by a check function. These objects are mostly built with constructor functions, so it's cleaner to have defaults set here, rather than in line after line of OpSpecs.

func (*OpDetails) Cost

func (d *OpDetails) Cost(program []byte, pc int, stack []stackValue) int

Cost computes the cost of the opcode, given details about how it is used, both static (the program, which can be used to find the immediate values supplied), and dynamic (the stack, which can be used to find the run-time arguments supplied). Cost is used at run-time. docCost returns similar information in human-readable form.

type OpImmediateDetails

type OpImmediateDetails struct {
	Comment   string `json:",omitempty"`
	Encoding  string `json:",omitempty"`
	Name      string `json:",omitempty"`
	Reference string `json:",omitempty"`
}

OpImmediateDetails contains information about the an immediate argument for a given opcode, combining OpSpec details with the extra note in the opcodeImmediateNotes map

func OpImmediateDetailsFromSpec

func OpImmediateDetailsFromSpec(spec OpSpec) []OpImmediateDetails

OpImmediateDetailsFromSpec provides a slice of OpImmediateDetails for a given OpSpec

type OpSpec

type OpSpec struct {
	Opcode byte
	Name   string

	Proto
	Version   uint64 // AVM version opcode introduced
	OpDetails        // Special cost or bytecode layout considerations
	// contains filtered or unexported fields
}

OpSpec defines an opcode

func OpcodesByVersion

func OpcodesByVersion(version uint64) []OpSpec

OpcodesByVersion returns list of opcodes available in a specific version of TEAL by copying v1 opcodes to v2, and then on to v3 to create a full list

func (*OpSpec) AlwaysExits

func (spec *OpSpec) AlwaysExits() bool

AlwaysExits is true iff the opcode always ends the program.

func (*OpSpec) DocCost

func (spec *OpSpec) DocCost(version uint64) string

DocCost returns the cost of the opcode in human-readable form.

type OpStream

type OpStream struct {
	Version  uint64
	Trace    *strings.Builder
	Warnings []sourceError // informational warnings, shouldn't stop assembly
	Errors   []sourceError // errors that should prevent final assembly
	Program  []byte        // Final program bytes. Will stay nil if any errors

	// map opcode offsets to source location
	OffsetToSource map[int]SourceLocation

	HasStatefulOps bool
	// contains filtered or unexported fields
}

OpStream accumulates state, including the final program, during assembly.

func AssembleString

func AssembleString(text string) (*OpStream, error)

AssembleString takes an entire program in a string and assembles it to bytecode using AssemblerDefaultVersion

func AssembleStringWithVersion

func AssembleStringWithVersion(text string, version uint64) (*OpStream, error)

AssembleStringWithVersion takes an entire program in a string and assembles it to bytecode using the assembler version specified. If version is assemblerNoVersion it uses #pragma version or fallsback to AssemblerDefaultVersion. OpStream is returned to allow access to warnings, (multiple) errors, or the PC to source line mapping. Note that AssemblerDefaultVersion is not the latest supported version, and therefore we might need to pass in explicitly a higher version.

func (*OpStream) ReportMultipleErrors

func (ops *OpStream) ReportMultipleErrors(fname string, writer io.Writer)

ReportMultipleErrors issues accumulated warnings and outputs errors to an io.Writer. In the case of exactly 1 error and no warnings, a slightly different format is provided to handle the cases when the original error is or isn't reported elsewhere. In the case of > 10 errors, only the first 10 errors will be reported.

type PCOffset

type PCOffset struct {
	PC     int `codec:"pc"`
	Offset int `codec:"offset"`
}

PCOffset stores the mapping from a program counter value to an offset in the disassembly of the bytecode

type Program

type Program []byte

Program is byte code to be interpreted for validating transactions.

func (Program) ToBeHashed

func (lsl Program) ToBeHashed() (protocol.HashID, []byte)

ToBeHashed implements crypto.Hashable

type ProgramKnowledge

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

ProgramKnowledge tracks statically known information as we assemble

type Proto

type Proto struct {
	Arg    typedList // what gets popped from the stack
	Return typedList // what gets pushed to the stack

	// StackExplain is the pointer to the function used in debugging process during simulation:
	// - on default construction, StackExplain relies on Arg and Return count.
	// - otherwise, we need to explicitly infer from EvalContext, by registering through explain function
	StackExplain debugStackExplain

	// AppStateExplain is the pointer to the function used for debugging in simulation:
	// - for an opcode not touching app's local/global/box state, this pointer is nil.
	// - otherwise, we call this method and check the operation of an opcode on app's state.
	AppStateExplain stateChangeExplain
}

Proto describes the "stack behavior" of an opcode, what it pops as arguments and pushes onto the stack as return values.

type RunMode

type RunMode uint64

RunMode is a bitset of logic evaluation modes. There are currently two such modes: Signature and Application.

const (
	// ModeSig is LogicSig execution
	ModeSig RunMode = 1 << iota

	// ModeApp is application/contract execution
	ModeApp
)

func (RunMode) Any

func (r RunMode) Any() bool

Any checks if this mode bitset represents any evaluation mode

func (RunMode) String

func (r RunMode) String() string

type SourceLocation

type SourceLocation struct {
	// Line is the line number, starting at 0.
	Line int
	// Column is the column number, starting at 0.
	Column int
}

SourceLocation points to a specific location in a source file.

type SourceMap

type SourceMap struct {
	Version    int      `json:"version"`
	File       string   `json:"file,omitempty"`
	SourceRoot string   `json:"sourceRoot,omitempty"`
	Sources    []string `json:"sources"`
	Names      []string `json:"names"`
	Mappings   string   `json:"mappings"`
}

SourceMap contains details from the source to assembly process. Currently, contains the map between TEAL source line to the assembled bytecode position and details about the template variables contained in the source file.

func GetSourceMap

func GetSourceMap(sourceNames []string, offsetToLocation map[int]SourceLocation) SourceMap

GetSourceMap returns a struct containing details about the assembled file and encoded mappings to the source file.

type StackType

type StackType struct {
	Name    string // alias (address, boolean, ...) or derived name [5]byte
	AVMType avmType
	Bound   [2]uint64 // represents max/min value for uint64 or max/min length for byte[]
}

StackType describes the type of a value on the operand stack

func NewStackType

func NewStackType(at avmType, bounds [2]uint64, stname ...string) StackType

NewStackType Initializes a new StackType with fields passed

func (StackType) String

func (st StackType) String() string

func (StackType) Typed

func (st StackType) Typed() bool

Typed tells whether the StackType is a specific concrete type.

type StackTypes

type StackTypes []StackType

StackTypes is an alias for a list of StackType with syntactic sugar

type TxnField

type TxnField int

TxnField is an enum type for `txn` and `gtxn`

const (
	// Sender Transaction.Sender
	Sender TxnField = iota
	// Fee Transaction.Fee
	Fee
	// FirstValid Transaction.FirstValid
	FirstValid
	// FirstValidTime timestamp of block(FirstValid-1)
	FirstValidTime
	// LastValid Transaction.LastValid
	LastValid
	// Note Transaction.Note
	Note
	// Lease Transaction.Lease
	Lease
	// Receiver Transaction.Receiver
	Receiver
	// Amount Transaction.Amount
	Amount
	// CloseRemainderTo Transaction.CloseRemainderTo
	CloseRemainderTo
	// VotePK Transaction.VotePK
	VotePK
	// SelectionPK Transaction.SelectionPK
	SelectionPK
	// VoteFirst Transaction.VoteFirst
	VoteFirst
	// VoteLast Transaction.VoteLast
	VoteLast
	// VoteKeyDilution Transaction.VoteKeyDilution
	VoteKeyDilution
	// Type Transaction.Type
	Type
	// TypeEnum int(Transaction.Type)
	TypeEnum
	// XferAsset Transaction.XferAsset
	XferAsset
	// AssetAmount Transaction.AssetAmount
	AssetAmount
	// AssetSender Transaction.AssetSender
	AssetSender
	// AssetReceiver Transaction.AssetReceiver
	AssetReceiver
	// AssetCloseTo Transaction.AssetCloseTo
	AssetCloseTo
	// GroupIndex i for txngroup[i] == Txn
	GroupIndex
	// TxID Transaction.ID()
	TxID
	// ApplicationID basics.AppIndex
	ApplicationID
	// OnCompletion OnCompletion
	OnCompletion
	// ApplicationArgs  [][]byte
	ApplicationArgs
	// NumAppArgs len(ApplicationArgs)
	NumAppArgs
	// Accounts []basics.Address
	Accounts
	// NumAccounts len(Accounts)
	NumAccounts
	// ApprovalProgram []byte
	ApprovalProgram
	// ClearStateProgram []byte
	ClearStateProgram
	// RekeyTo basics.Address
	RekeyTo
	// ConfigAsset basics.AssetIndex
	ConfigAsset
	// ConfigAssetTotal AssetParams.Total
	ConfigAssetTotal
	// ConfigAssetDecimals AssetParams.Decimals
	ConfigAssetDecimals
	// ConfigAssetDefaultFrozen AssetParams.AssetDefaultFrozen
	ConfigAssetDefaultFrozen
	// ConfigAssetUnitName AssetParams.UnitName
	ConfigAssetUnitName
	// ConfigAssetName AssetParams.AssetName
	ConfigAssetName
	// ConfigAssetURL AssetParams.URL
	ConfigAssetURL
	// ConfigAssetMetadataHash AssetParams.MetadataHash
	ConfigAssetMetadataHash
	// ConfigAssetManager AssetParams.Manager
	ConfigAssetManager
	// ConfigAssetReserve AssetParams.Reserve
	ConfigAssetReserve
	// ConfigAssetFreeze AssetParams.Freeze
	ConfigAssetFreeze
	// ConfigAssetClawback AssetParams.Clawback
	ConfigAssetClawback
	//FreezeAsset  basics.AssetIndex
	FreezeAsset
	// FreezeAssetAccount basics.Address
	FreezeAssetAccount
	// FreezeAssetFrozen bool
	FreezeAssetFrozen
	// Assets []basics.AssetIndex
	Assets
	// NumAssets len(ForeignAssets)
	NumAssets
	// Applications []basics.AppIndex
	Applications
	// NumApplications len(ForeignApps)
	NumApplications

	// GlobalNumUint uint64
	GlobalNumUint
	// GlobalNumByteSlice uint64
	GlobalNumByteSlice
	// LocalNumUint uint64
	LocalNumUint
	// LocalNumByteSlice uint64
	LocalNumByteSlice

	// ExtraProgramPages AppParams.ExtraProgramPages
	ExtraProgramPages

	// Nonparticipation Transaction.Nonparticipation
	Nonparticipation

	// Logs Transaction.ApplyData.EvalDelta.Logs
	Logs

	// NumLogs len(Logs)
	NumLogs

	// CreatedAssetID Transaction.ApplyData.EvalDelta.ConfigAsset
	CreatedAssetID

	// CreatedApplicationID Transaction.ApplyData.EvalDelta.ApplicationID
	CreatedApplicationID

	// LastLog Logs[len(Logs)-1]
	LastLog

	// StateProofPK Transaction.StateProofPK
	StateProofPK

	// ApprovalProgramPages [][]byte
	ApprovalProgramPages

	// NumApprovalProgramPages = len(ApprovalProgramPages) // 4096
	NumApprovalProgramPages

	// ClearStateProgramPages [][]byte
	ClearStateProgramPages

	// NumClearStateProgramPages = len(ClearStateProgramPages) // 4096
	NumClearStateProgramPages

	// RejectVersion uint64
	RejectVersion
)

func (TxnField) String

func (i TxnField) String() string

type UnnamedResourcePolicy

type UnnamedResourcePolicy interface {
	AvailableAccount(addr basics.Address) bool
	AvailableAsset(asset basics.AssetIndex) bool
	AvailableApp(app basics.AppIndex) bool
	AllowsHolding(addr basics.Address, asset basics.AssetIndex) bool
	AllowsLocal(addr basics.Address, app basics.AppIndex) bool
	AvailableBox(app basics.AppIndex, name string, newAppAccess bool, createSize uint64) bool
	IOSurplus(surplus int64) bool
}

UnnamedResourcePolicy is an interface that defines the policy for allowing unnamed resources. This should only be used during simulation or debugging.

type VerCost

type VerCost struct {
	From int
	To   int
	// Cost is a human readable string to describe costs. Simple opcodes are
	// just an integer, but some opcodes have field or stack dependencies.
	Cost string
}

VerCost indicates the cost of an operation over the range of LogicVersions from From to To.

type VoterParamsField

type VoterParamsField int

VoterParamsField is an enum for `voter_params_get` opcode

const (
	// VoterBalance is the balance, with pending rewards, from the balance
	// round.  It is 0 if the account was offline then.
	VoterBalance VoterParamsField = iota

	// VoterIncentiveEligible is whether this account opted into block payouts
	// by paying extra in `keyreg`. Does not reflect eligibility based on
	// balance. The value is returned for the balance round and is _false_ if
	// the account was offline then.
	VoterIncentiveEligible
)

func (VoterParamsField) String

func (i VoterParamsField) String() string

type VrfStandard

type VrfStandard int

VrfStandard is an enum for the `vrf_verify` opcode

const (
	// VrfAlgorand is the built-in VRF of the Algorand chain
	VrfAlgorand VrfStandard = iota
)

func (VrfStandard) String

func (i VrfStandard) String() string

type WebDebugger

type WebDebugger struct {
	URL string
}

WebDebugger represents a connection to tealdbg

func (*WebDebugger) Complete

func (dbg *WebDebugger) Complete(state *DebugState)

Complete sends state to remote debugger

func (*WebDebugger) Register

func (dbg *WebDebugger) Register(state *DebugState)

Register sends state to remote debugger

func (*WebDebugger) Update

func (dbg *WebDebugger) Update(state *DebugState)

Update sends state to remote debugger

type Writer

type Writer interface {
	Write([]byte) (int, error)
	WriteByte(c byte) error
}

Writer is what we want here. Satisfied by bufio.Buffer

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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