txvm

package
v0.0.0-...-ff6bfbe Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2019 License: Apache-2.0 Imports: 13 Imported by: 2

Documentation

Overview

Package txvm implements Chain Protocol transactions.

A transaction is a program (as a bytecode string) that is executed by the stack-based txvm virtual machine.

Central to the operation of the virtual machine are two concepts: "values" and "contracts."

A value is an amount of some asset type. The rules of the virtual machine limit the ways in which values may be manipulated, ensuring that no unbalanced transaction can ever be a valid txvm program.

A contract is a txvm subroutine plus some associated state, in the form of a stack. When a contract runs, it manipulates the items on its stack. It may suspend execution with the yield instruction, with processing to continue later in the same transaction, or with the output instruction, with processing to continue in a later transaction via the input instruction.

During execution, value-manipulating structures are produced as side-effects:

  • Issuances: new units of a caller-defined asset type are created.
  • Outputs: units of an asset are "locked" by specifying the conditions needed to unlock and spend them. An output is simply a contract that has suspended itself with the output instruction and that contains some value on its stack.
  • Inputs: previously locked value is unlocked by satisfying an output's conditions.
  • Retirements: units of an asset type are permanently removed from circulation.

Significant events during processing, including the creation of the above-named structures, cause relevant entries to accumulate in the virtual machine's "transaction log." The log may be inspected to discover the transaction's effects (especially to find the IDs of inputs and outputs for removing from the utxo set and adding to it, respectively). The log is hashed to get the overall transaction ID.

Index

Constants

View Source
const (
	InputCode           byte = 'I'
	OutputCode          byte = 'O'
	LogCode             byte = 'L'
	TimerangeCode       byte = 'R'
	NonceCode           byte = 'N'
	IssueCode           byte = 'A'
	RetireCode          byte = 'X'
	FinalizeCode        byte = 'F'
	ValueCode           byte = 'V'
	ContractCode        byte = 'C'
	WrappedContractCode byte = 'W'
)

Type codes for inspected entries and for log items.

View Source
const (
	IntCode   byte = 'Z'
	BytesCode byte = 'S'
	TupleCode byte = 'T'
)

Type codes for inspected data items.

Variables

View Source
var (
	// ErrNonEmpty is returned when a contract completes execution
	// with a non-empty stack.
	ErrNonEmpty = errorf("contract ended with non-empty stack")

	// ErrUnportable is returned when a contract calls output or wrap
	// with unportable items on its stack.
	ErrUnportable = errorf("contract contains unportable stack items")

	// ErrPrv is returned when prv is called.
	ErrPrv = errorf("prv called")
)
View Source
var (
	// ErrVerifyFail is the error produced by a verify that fails.
	ErrVerifyFail = errorf("verify fail")

	// ErrJump is returned when the jump destination for a jumpif
	// is not within the bounds of the program.
	ErrJump = errorf("invalid jump destination")
)
View Source
var (
	// ErrSigSize is returned when checksig is called with a
	// signature length that is invalid for the scheme.
	ErrSigSize = errorf("bad signature length")

	// ErrPubSize is returned when checksig is called with a
	// public key length that is invalid for the scheme.
	ErrPubSize = errorf("bad public key length")

	// ErrSignature is returned when checksig is called with a
	// non-empty signature that fails the check.
	ErrSignature = errorf("invalid non-empty signature")
)
View Source
var (
	// ErrNegAmount is returned when issue or split is called
	// with a negative amount.
	ErrNegAmount = errorf("cannot create negative amounts")

	// ErrSplit is returned when split is called with an amount
	// greater than contained in the value.
	ErrSplit = errorf("not enough value to split")

	// ErrMergeAsset is returned when merge is called with values
	// that have two different assets.
	ErrMergeAsset = errorf("cannot merge different assets")

	// ErrAnchorVal is returned when a non-zero amount value
	// is used for an op that requires an anchor.
	ErrAnchorVal = errorf("value is non-zero and cannot be used as anchor")
)
View Source
var (
	// ErrResidue is produced by Validate when execution leaves the
	// argument stack or current contract stack non-empty.
	ErrResidue = errorf("residue on stack(s)")

	// ErrRunlimit indicates that the available runlimit has been exhausted.
	ErrRunlimit = errorf("runlimit exhausted")

	// ErrVersion means Validate was called with a version less than 3.
	ErrVersion = errorf("transaction version cannot be less than 3")

	// ErrStackRange means an op tried to access a location that was out of
	// range for the stack it was accessing.
	ErrStackRange = errorf("index out of stack range")

	// ErrRange is returned when an op tries to access a location that
	// is out of range for the value it was accessing.
	ErrRange = errorf("index out of range")

	// ErrType is returned when a stack item has a different type
	// than was expected.
	ErrType = errorf("invalid item type")

	// ErrFields is returned when a struct has different fields than
	// was expected. Is returned during an uninspect function call.
	ErrFields = errorf("invalid struct fields")

	// ErrUnderflow is returned when an op pops or peeks an item
	// on the stack and the stack is not deep enough.
	ErrUnderflow = errorf("stack underflow")

	// ErrIntOverflow is returned when any arithmetic exceeds the
	// range of int64.
	ErrIntOverflow = vmError(checked.ErrOverflow)

	// ErrExt is returned when extension operations are performed
	// and the extension flag is false.
	ErrExt = errorf("extension flag is false")
)
View Source
var EnableExtension = Option{
	// contains filtered or unexported fields
}

EnableExtension can be passed as an option to Validate. It sets the extension flag of the VM to true, enabling the ext opcode to be called and extensions to be called.

View Source
var ErrBitLen = errorf("mismatched byte lengths for binary bitwise op")

ErrBitLen is returned when a binary bitwise op is called on byte strings of different lengths.

View Source
var ErrFinalized = errorf("cannot add to tx log after finalize")

ErrFinalized is returned when an op that logs an item is called after finalize has been called.

View Source
var ErrInt = errorf("invalid varint")

ErrInt is returned when int is called on a byte string that is not a valid encoding of a varint.

View Source
var ErrSliceRange = errorf("bad slice range")

ErrSliceRange is returned when slice is called with a range that is invalid.

View Source
var ErrUnfinalized = errorf("cannot be called until after finalize")

ErrUnfinalized is returned when txid is called before finalize.

View Source
var StopAfterFinalize = Option{
	// contains filtered or unexported fields
}

StopAfterFinalize can be passed as an option to Validate. It causes execution to terminate after a "finalize" instruction, without causing an ErrResidue error if the stacks are non-empty. It is useful for computing the transaction ID of a yet-unsigned transaction.

Functions

func AssetID

func AssetID(contractSeed, tag []byte) [32]byte

AssetID produces the ID for the asset whose issuing contract has the given ID, and that has the given optional asset tag.

func ContractSeed

func ContractSeed(prog []byte) [32]byte

ContractSeed computes the seed of a contract whose initial program is prog.

func Encode

func Encode(v Data) []byte

Encode serializes an arbitrary data type in a program, which, when executed, produces that data.

func NonceHash

func NonceHash(nonce Tuple) [32]byte

NonceHash computes the hash of a nonce tuple.

func VMHash

func VMHash(f string, x []byte) (hash [32]byte)

VMHash computes the hash of the "function" f applied to the byte string x.

Types

type Bytes

type Bytes []byte

Bytes is a stack item containing a sequence of bytes.

func (Bytes) String

func (b Bytes) String() string

type Data

type Data interface {
	Item
	// contains filtered or unexported methods
}

Data is an interface for plain-old-data stack items.

type Entry

type Entry interface {
	Item
	// contains filtered or unexported methods
}

Entry is the interface for txvm stack items that are not plain data.

type Int

type Int int64

Int is a stack item containing a 64-bit signed integer.

func (Int) String

func (i Int) String() string

type Item

type Item interface {
	String() string
	// contains filtered or unexported methods
}

Item is an interface for all txvm stack items.

type Option

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

Option is the type of a function that can be passed as an option to Validate.

func AfterStep

func AfterStep(h ...func(*VM)) Option

AfterStep can be passed as an option to Validate. It adds a callback to be invoked after each instruction is executed.

func BeforeStep

func BeforeStep(h ...func(*VM)) Option

BeforeStep can be passed as an option to Validate. It adds a callback to be invoked just before each instruction is executed.

func GetRunlimit

func GetRunlimit(runlimit *int64) Option

GetRunlimit causes the vm to write its ending runlimit to the given pointer on exit.

func OnFinalize

func OnFinalize(h ...func(*VM)) Option

OnFinalize can be passed as an option to Validate. It adds a callback to be invoked when "finalize" is executed.

func OnLog

func OnLog(h ...func(*VM)) Option

OnLog can be passed as an option to Validate. It adds a callback to be invoked when data is added to the transaction log.

func Resumer

func Resumer(f *func(rest []byte) error) Option

Resumer can be passed as an option to Validate. It acts like StopAfterFinalize, but additionally writes a function to the given pointer that can be used to pick up execution after the finalize step. This function can be called only once, since calling it will affect the VM state.

func Trace

func Trace(w io.Writer) Option

Trace can be passed as an option to Validate. It causes a textual execution trace to be written to the given io.Writer.

type Tuple

type Tuple []Data

Tuple is a stack item containing a sequence of zero or more Data items.

func NonceTuple

func NonceTuple(callerSeed, selfSeed, blockID []byte, expTimeMS int64) Tuple

NonceTuple computes a nonce tuple suitable for logging (with vm.log(nonce...)) or hashing (with NonceHash).

func (Tuple) String

func (t Tuple) String() string

type VM

type VM struct {

	// TxID is the unique id of the transaction. It is only set if
	// Finalized is true.
	TxID [32]byte

	// Log is the record of the transaction's effects.
	Log []Tuple

	// Finalized is true if and only if the finalize instruction was
	// executed.
	Finalized bool
	// contains filtered or unexported fields
}

VM is a virtual machine for executing Chain Protocol transactions.

func Validate

func Validate(prog []byte, txVersion, runlimit int64, o ...Option) (*VM, error)

Validate is the main entrypoint to txvm. It runs the given program, producing its transaction ID if it gets as far as a "finalize" instruction. Other runtime information can be inspected via callbacks, which are supplied via the Option arguments.

func (*VM) OpCode

func (vm *VM) OpCode() byte

OpCode returns the current opcode in the VM. Use it in BeforeStep and AfterStep callbacks to discover the instruction being executed.

func (*VM) Program

func (vm *VM) Program() []byte

Program returns the program bytecode of the VM's current contract.

func (*VM) Runlimit

func (vm *VM) Runlimit() int64

Runlimit returns the current remaining runlimit in the VM.

func (*VM) Seed

func (vm *VM) Seed() []byte

Seed returns the contract seed of the VM's current contract.

func (*VM) StackItem

func (vm *VM) StackItem(i int) Data

StackItem returns an "inspected" copy of an item on the VM's current contract stack, by position. Position 0 is the bottom of the stack and StackLen()-1 is the top.

func (*VM) StackLen

func (vm *VM) StackLen() int

StackLen returns the length of the stack of the VM's current contract.

func (*VM) Version

func (vm *VM) Version() int64

Version returns the current transaction version.

Directories

Path Synopsis
Package asm provides an assembler and disassembler for txvm bytecode.
Package asm provides an assembler and disassembler for txvm bytecode.
Package op assigns human-readable names to numeric opcodes.
Package op assigns human-readable names to numeric opcodes.
Package txvmutil defines a "fluent" builder type for constructing TxVM programs.
Package txvmutil defines a "fluent" builder type for constructing TxVM programs.

Jump to

Keyboard shortcuts

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