Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

codec.gno

package vmkit

import "errors"

// ErrTruncated is returned by every Reader method that runs past the end of
// the buffer. A snapshot is consensus state, so a short read is always a hard
// error and never a zero value.
var ErrTruncated = errors.New("vmkit: truncated snapshot")

// ErrBadSnapshot is returned when a snapshot is well-formed but not for this
// machine: wrong magic, wrong version, or a field outside its legal range.
var ErrBadSnapshot = errors.New("vmkit: snapshot is not for this machine")

// Writer builds a snapshot. Every integer is fixed-width big-endian and every
// byte slice is length-prefixed, so the encoding is canonical: the same
// machine state always produces the same bytes, on every node.
//
// Machines are not required to use it, but a machine that invents its own
// layout owes the zoo an explanation, because the cross-VM snapshot cost
// comparison only means something when the encodings match.
type Writer struct {
	buf []byte
}

// NewWriter returns a Writer with room for n bytes reserved up front.
func NewWriter(n int) *Writer {
	if n < 0 {
		n = 0
	}
	return &Writer{buf: make([]byte, 0, n)}
}

// Byte appends one byte.
func (w *Writer) Byte(b byte) { w.buf = append(w.buf, b) }

// Uint32 appends a 4-byte big-endian value.
func (w *Writer) Uint32(v uint32) {
	w.buf = append(w.buf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}

// Uint64 appends an 8-byte big-endian value.
func (w *Writer) Uint64(v uint64) {
	w.buf = append(w.buf,
		byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32),
		byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}

// Int appends a signed value, zig-zag encoded into a Uint64 so that small
// negative numbers do not cost eight 0xff bytes.
func (w *Writer) Int(v int64) {
	u := uint64(v) << 1
	if v < 0 {
		u = ^u
	}
	w.Uint64(u)
}

// Bytes appends a length-prefixed byte slice.
func (w *Writer) Bytes(p []byte) {
	w.Uint32(uint32(len(p)))
	w.buf = append(w.buf, p...)
}

// String appends a length-prefixed string.
func (w *Writer) String(s string) { w.Bytes([]byte(s)) }

// Out returns the encoded bytes.
func (w *Writer) Out() []byte { return w.buf }

// Reader consumes a snapshot written by [Writer].
//
// It latches the first error it hits: a caller may decode a whole struct and
// check [Reader.Err] once at the end, instead of after every field. Every
// method returns a zero value once the Reader is in error.
type Reader struct {
	buf []byte
	pos int
	err error
}

// NewReader returns a Reader over b.
func NewReader(b []byte) *Reader { return &Reader{buf: b} }

// Err returns the first error hit, or nil.
func (r *Reader) Err() error { return r.err }

// Remaining reports how many bytes are left unread.
func (r *Reader) Remaining() int {
	if r.pos > len(r.buf) {
		return 0
	}
	return len(r.buf) - r.pos
}

// Fail latches err, so a machine can reject a field its own rules forbid and
// have it surface through [Reader.Err] like any decoding failure.
func (r *Reader) Fail(err error) {
	if r.err == nil {
		r.err = err
	}
}

func (r *Reader) take(n int) []byte {
	if r.err != nil {
		return nil
	}
	if n < 0 || r.pos+n > len(r.buf) {
		r.err = ErrTruncated
		return nil
	}
	out := r.buf[r.pos : r.pos+n]
	r.pos += n
	return out
}

// Byte reads one byte.
func (r *Reader) Byte() byte {
	p := r.take(1)
	if p == nil {
		return 0
	}
	return p[0]
}

// Uint32 reads a 4-byte big-endian value.
func (r *Reader) Uint32() uint32 {
	p := r.take(4)
	if p == nil {
		return 0
	}
	return uint32(p[0])<<24 | uint32(p[1])<<16 | uint32(p[2])<<8 | uint32(p[3])
}

// Uint64 reads an 8-byte big-endian value.
func (r *Reader) Uint64() uint64 {
	p := r.take(8)
	if p == nil {
		return 0
	}
	return uint64(p[0])<<56 | uint64(p[1])<<48 | uint64(p[2])<<40 | uint64(p[3])<<32 |
		uint64(p[4])<<24 | uint64(p[5])<<16 | uint64(p[6])<<8 | uint64(p[7])
}

// Int reads a zig-zag encoded signed value written by [Writer.Int].
func (r *Reader) Int() int64 {
	u := r.Uint64()
	v := int64(u >> 1)
	if u&1 != 0 {
		v = ^v
	}
	return v
}

// Bytes reads a length-prefixed byte slice. The result is a copy, so a
// machine can keep it without aliasing the snapshot it was handed.
func (r *Reader) Bytes() []byte {
	n := int(r.Uint32())
	p := r.take(n)
	if p == nil {
		return nil
	}
	out := make([]byte, n)
	copy(out, p)
	return out
}

// String reads a length-prefixed string.
func (r *Reader) String() string {
	p := r.take(int(r.Uint32()))
	if p == nil {
		return ""
	}
	return string(p)
}

fuel.gno

package vmkit

// Unmetered is the fuel value that disables the budget: a [Meter] built with
// it never reports exhaustion. It exists so a benchmark can measure the
// dispatch loop without the meter in it, and so a trusted caller can run a
// program to completion in one slice. Gas remains the real backstop.
const Unmetered int64 = -1

// Meter is a fuel budget being spent. It allocates nothing after
// construction, because it sits in the hot path of every guest instruction.
type Meter struct {
	budget int64 // Unmetered, or the number of units this slice may spend
	used   int64
}

// NewMeter returns a meter good for `budget` units, or an unmetered one when
// budget is [Unmetered]. A budget of zero is a meter with nothing to spend,
// which is a legitimate way to ask "is this instance still runnable".
func NewMeter(budget int64) *Meter {
	if budget < 0 {
		budget = Unmetered
	}
	return &Meter{budget: budget}
}

// Charge spends n units and reports whether they were available. On false
// nothing is spent, so the caller can stop before executing the instruction
// it could not pay for. That ordering is what makes a resumed machine
// re-execute exactly the instruction it stopped at, and no other.
func (m *Meter) Charge(n int64) bool {
	if m.budget == Unmetered {
		m.used += n
		return true
	}
	if m.used+n > m.budget {
		return false
	}
	m.used += n
	return true
}

// Used reports how much fuel has been spent.
func (m *Meter) Used() int64 { return m.used }

// Remaining reports what is left, or [Unmetered].
func (m *Meter) Remaining() int64 {
	if m.budget == Unmetered {
		return Unmetered
	}
	return m.budget - m.used
}

// Exhausted reports whether the next single unit would fail.
func (m *Meter) Exhausted() bool { return !m.affordable(1) }

func (m *Meter) affordable(n int64) bool {
	return m.budget == Unmetered || m.used+n <= m.budget
}

gnomod.toml

module = "gno.land/p/nym-moultest123/x/vm/vmkit/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186406
  max_deposit = "15000000ugnot"

host.gno

package vmkit

import "errors"

// ErrNotGranted is returned by a [Host] for a capability the instance was
// never given. A guest that ignores the error and keeps going is a guest bug;
// a machine should turn it into a [Trapped] status.
var ErrNotGranted = errors.New("vmkit: capability not granted")

// Host is everything a guest program can reach outside its own memory.
//
// It is deliberately small, and deliberately handed in rather than looked up:
// a guest has exactly the authority its [Host] carries. Gno realm code has
// ambient authority through the realm frame, so the guest is where the
// capability-secure version can actually be tried.
//
// Every method must be deterministic across replays of the same block. Now
// and Height come from the chain, never from a wall clock.
type Host interface {
	// Caller is the address that called the realm running this guest.
	Caller() address
	// Origin is the address that signed the transaction.
	Origin() address
	// Now is block time in Unix seconds, never wall time.
	Now() int64
	// Height is the block height.
	Height() int64

	// Get reads from storage scoped to this instance. A miss is nil.
	Get(key []byte) []byte
	// Set writes to storage scoped to this instance.
	Set(key, val []byte)

	// Input is the immutable call input for this slice of execution: the
	// guest's calldata, argv, or stdin depending on the machine. A machine
	// tracks its own read cursor, in its snapshot, so that resuming reads
	// the byte it had not read yet.
	Input() []byte
	// Output appends to the guest's output buffer.
	Output(p []byte)

	// Emit writes a chain event. kv is a flat list of alternating keys and
	// values; an odd trailing element is dropped.
	Emit(typ string, kv ...string)
	// Send transfers amount ugnot to `to`, and returns [ErrNotGranted]
	// unless the deploying realm funded this instance with a budget.
	Send(to address, amount int64) error
	// Log records a diagnostic line. Never consensus-relevant.
	Log(msg string)
}

instance.gno

package vmkit

import (
	"errors"

	"gno.land/p/nt/avl/v0"
)

// ErrNoInstance is returned when an id names nothing.
var ErrNoInstance = errors.New("vmkit: no such instance")

// ErrBudgetExhausted is returned when an instance has already spent its total
// fuel budget, so there is nothing left to step.
var ErrBudgetExhausted = errors.New("vmkit: instance fuel budget exhausted")

// Instance is one guest program as a realm stores it: the code, the machine
// state between slices, and the accounting that survives the transaction.
//
// It holds a snapshot rather than a [Machine], on purpose. A realm keeps
// bytes; the machine is rebuilt for the slice that needs it and thrown away
// after. That is what makes the storage cost of a paused program measurable,
// which is the whole kill criterion for continuations: if resuming costs more
// than re-running, continuations are theater.
type Instance struct {
	ID    string
	Owner address
	VM    string // which guest machine the Program is for

	Program  []byte
	Snapshot []byte

	Status Status
	Trap   string

	// FuelUsed is the total across every slice run so far.
	FuelUsed int64
	// FuelBudget caps FuelUsed across the instance's whole life, or is
	// [Unmetered] for no cap.
	FuelBudget int64

	// Slices counts how many transactions have stepped this instance.
	Slices int64

	Output []byte
}

// NewInstance returns an instance ready for its first slice.
func NewInstance(id string, owner address, vm string, program []byte, budget int64) *Instance {
	if budget < 0 {
		budget = Unmetered
	}
	prog := make([]byte, len(program))
	copy(prog, program)
	return &Instance{
		ID:         id,
		Owner:      owner,
		VM:         vm,
		Program:    prog,
		Status:     Running,
		FuelBudget: budget,
	}
}

// Remaining reports the fuel left in the instance's total budget, or
// [Unmetered].
func (i *Instance) Remaining() int64 {
	if i.FuelBudget == Unmetered {
		return Unmetered
	}
	left := i.FuelBudget - i.FuelUsed
	if left < 0 {
		return 0
	}
	return left
}

// Slice returns how much fuel the next call to [Instance.Run] may spend when
// the caller asks for `want`: `want` clamped to what the budget still allows.
func (i *Instance) Slice(want int64) int64 {
	left := i.Remaining()
	if left == Unmetered {
		return want
	}
	if want == Unmetered || want > left {
		return left
	}
	return want
}

// Run steps m for one slice of at most `fuel` units and folds the result back
// into the instance: the new snapshot, the status, the fuel spent, and
// anything the guest wrote to h.
//
// m must be a fresh machine loaded from i.Program; Run restores i.Snapshot
// into it when there is one, so the caller never has to remember the order.
// The instance is left untouched when Restore fails, which means a snapshot
// that cannot be decoded costs the caller gas but never corrupts the stored
// program.
func (i *Instance) Run(m Machine, h Host, fuel int64) error {
	if i.Status.Done() && i.Status != Running {
		return ErrBudgetExhausted
	}
	if len(i.Snapshot) > 0 {
		if err := m.Restore(i.Snapshot); err != nil {
			return err
		}
	}
	slice := i.Slice(fuel)
	if slice == 0 {
		i.Status = OutOfFuel
		return ErrBudgetExhausted
	}

	used, status := m.Step(h, slice)

	i.FuelUsed += used
	i.Slices++
	i.Snapshot = m.Snapshot()
	i.Status = status
	i.Trap = TrapReason(m)
	if status == Running && i.Remaining() == 0 {
		i.Status = OutOfFuel
	}
	return nil
}

// Store is the avl-backed set of instances a realm owns, keyed by id.
type Store struct {
	tree *avl.Tree
}

// NewStore returns an empty store.
func NewStore() *Store { return &Store{tree: avl.NewTree()} }

// Set writes an instance, replacing any instance with the same id.
func (s *Store) Set(i *Instance) {
	if i == nil {
		return
	}
	s.tree.Set(i.ID, i)
}

// Get returns the instance with this id, or nil.
func (s *Store) Get(id string) *Instance {
	v := s.tree.Get(id)
	if v == nil {
		return nil
	}
	inst, ok := v.(*Instance)
	if !ok {
		return nil
	}
	return inst
}

// Remove deletes an instance and reports whether it existed.
func (s *Store) Remove(id string) bool {
	_, removed := s.tree.Remove(id)
	return removed
}

// Size returns how many instances are stored.
func (s *Store) Size() int { return s.tree.Size() }

// Iterate walks every instance in key order, stopping early when fn returns
// true.
func (s *Store) Iterate(fn func(*Instance) bool) {
	s.tree.Iterate("", "", func(_ string, v any) bool {
		inst, ok := v.(*Instance)
		if !ok {
			return false
		}
		return fn(inst)
	})
}

// ReverseIterate walks every instance in descending key order, which is how a
// realm renders newest-first when ids are zero-padded and ascending.
func (s *Store) ReverseIterate(fn func(*Instance) bool) {
	s.tree.ReverseIterate("", "", func(_ string, v any) bool {
		inst, ok := v.(*Instance)
		if !ok {
			return false
		}
		return fn(inst)
	})
}

machine.gno

// Package vmkit is the host ABI shared by every guest virtual machine that
// runs inside a gno realm: a stepping contract with an explicit fuel budget,
// a capability-scoped [Host], and a snapshot format that lets a guest program
// outlive the transaction that started it.
//
// A guest VM implements [Machine]. Everything else in this package is the
// machinery a VM should not have to write twice: the [Meter], the [Codec] the
// snapshots are built from, an in-memory [TestHost], and the avl-backed
// [Store] a realm keeps its instances in.
//
// The three things the ABI exists to fix:
//
//   - Fuel is the interface, not the backstop. Running out of fuel yields
//     [OutOfFuel] plus a machine that can be snapshotted, never a panic. Gas
//     still bounds the transaction, but a guest that stops is a normal outcome.
//   - Continuations. Snapshot and Restore mean a program runs across blocks.
//     The realm stores the bytes, and the next caller pays for the next slice.
//     Gno realm code itself cannot pause; a guest can.
//   - Capabilities, not ambient authority. A guest gets exactly the [Host] it
//     was handed. No Send without a grant, no storage outside its own scope.
//
// Live demo: [r/moul/x/vm/bfdemo](/r/nym-moultest123/x/vm/bfdemo/v0), running the
// [p/moul/x/vm/bf](/p/nym-moultest123/x/vm/bf/v0) guest.
package vmkit

// Status is the outcome of a call to [Machine.Step].
type Status int

const (
	// Running means the machine stopped because it ran out of the fuel
	// handed to this slice, but the program has not finished. It is
	// resumable: snapshot it, and step it again later.
	Running Status = iota

	// Halted means the program reached its end. Terminal.
	Halted

	// Trapped means the guest did something the machine refuses to do:
	// an invalid instruction, an out-of-range access, a capability it was
	// not granted. Terminal.
	Trapped

	// OutOfFuel means the instance exhausted its total budget, not just the
	// fuel for this slice. Terminal unless the owner raises the budget.
	OutOfFuel
)

// String renders the status as the lowercase word used in realm output.
func (s Status) String() string {
	switch s {
	case Running:
		return "running"
	case Halted:
		return "halted"
	case Trapped:
		return "trapped"
	case OutOfFuel:
		return "out of fuel"
	}
	return "unknown"
}

// Done reports whether the status is terminal, i.e. stepping again is
// pointless without operator intervention.
func (s Status) Done() bool { return s != Running }

// Machine is one guest virtual machine, mid-execution.
//
// Step runs until the program halts, traps, or burns `fuel` units, whichever
// comes first, and reports how much fuel it actually used. A Machine must
// charge at least one unit per guest instruction so that a fuel budget is a
// real bound on work; beyond that the unit is the VM's own business, and
// [r/moul/x/vm/bfdemo](/r/nym-moultest123/x/vm/bfdemo/v0) compares them by measurement
// rather than by trusting the number.
//
// Snapshot must round-trip through Restore: a machine stepped to exhaustion,
// snapshotted, restored and stepped again must produce exactly what the same
// machine stepped in one go would have. That property is what makes a guest
// program a contract instead of a function call.
type Machine interface {
	Step(h Host, fuel int64) (used int64, status Status)
	Snapshot() []byte
	Restore(b []byte) error
}

// Trapper is an optional refinement of [Machine]: a machine that can explain
// why it trapped. Kept out of [Machine] so the core ABI stays three methods.
type Trapper interface {
	// Trap returns the reason for a [Trapped] status, or "" when the
	// machine has not trapped.
	Trap() string
}

// TrapReason returns m's trap reason when m implements [Trapper], else "".
func TrapReason(m Machine) string {
	if t, ok := m.(Trapper); ok {
		return t.Trap()
	}
	return ""
}

testhost.gno

package vmkit

import "gno.land/p/nt/avl/v0"

// TestHost is a deterministic in-memory [Host] for unit tests and for
// measuring a machine without a chain under it.
//
// Nothing here reads the chain, so a test that uses it produces the same
// numbers on every host. Storage is an avl tree rather than a map because gno
// map iteration order is unspecified, and [TestHost.Keys] has to be stable for
// a test to assert on it.
//
// Send is denied unless [TestHost.Grant] funded a budget, which is how the
// capability rule gets tested: a guest that tries to send without a grant must
// come back [Trapped], not silently succeed.
type TestHost struct {
	caller address
	origin address
	now    int64
	height int64

	store *avl.Tree // hex key -> []byte

	in     []byte
	out    []byte
	events []string
	logs   []string

	sendBudget int64
	sends      []Transfer
}

// Transfer records one successful [TestHost.Send].
type Transfer struct {
	To     address
	Amount int64
}

// NewTestHost returns a host with no capabilities granted, height 1, time 0,
// and empty input.
func NewTestHost() *TestHost {
	return &TestHost{
		height: 1,
		store:  avl.NewTree(),
	}
}

// WithCaller sets the address the guest sees as its caller and origin.
func (h *TestHost) WithCaller(a address) *TestHost {
	h.caller, h.origin = a, a
	return h
}

// WithOrigin overrides the origin separately from the caller.
func (h *TestHost) WithOrigin(a address) *TestHost { h.origin = a; return h }

// WithTime sets the block time in Unix seconds.
func (h *TestHost) WithTime(t int64) *TestHost { h.now = t; return h }

// WithHeight sets the block height.
func (h *TestHost) WithHeight(n int64) *TestHost { h.height = n; return h }

// WithInput sets the guest's call input.
func (h *TestHost) WithInput(p []byte) *TestHost {
	h.in = make([]byte, len(p))
	copy(h.in, p)
	return h
}

// Grant funds the send capability with a budget in ugnot. Without it, Send
// returns [ErrNotGranted].
func (h *TestHost) Grant(budget int64) *TestHost { h.sendBudget = budget; return h }

func (h *TestHost) Caller() address { return h.caller }
func (h *TestHost) Origin() address { return h.origin }
func (h *TestHost) Now() int64      { return h.now }
func (h *TestHost) Height() int64   { return h.height }
func (h *TestHost) Input() []byte   { return h.in }

func (h *TestHost) Get(key []byte) []byte {
	v := h.store.Get(hexKey(key))
	if v == nil {
		return nil
	}
	stored := v.([]byte)
	out := make([]byte, len(stored))
	copy(out, stored)
	return out
}

func (h *TestHost) Set(key, val []byte) {
	cp := make([]byte, len(val))
	copy(cp, val)
	h.store.Set(hexKey(key), cp)
}

func (h *TestHost) Output(p []byte) { h.out = append(h.out, p...) }

func (h *TestHost) Emit(typ string, kv ...string) {
	line := typ
	for i := 0; i+1 < len(kv); i += 2 {
		line += " " + kv[i] + "=" + kv[i+1]
	}
	h.events = append(h.events, line)
}

func (h *TestHost) Send(to address, amount int64) error {
	if amount <= 0 || amount > h.sendBudget {
		return ErrNotGranted
	}
	h.sendBudget -= amount
	h.sends = append(h.sends, Transfer{To: to, Amount: amount})
	return nil
}

func (h *TestHost) Log(msg string) { h.logs = append(h.logs, msg) }

// Out returns everything the guest has written, as bytes.
func (h *TestHost) Out() []byte { return h.out }

// OutString returns everything the guest has written, as a string.
func (h *TestHost) OutString() string { return string(h.out) }

// ResetOut discards the output buffer, so one host can measure several runs.
func (h *TestHost) ResetOut() { h.out = nil }

// Events returns the rendered events, in emission order.
func (h *TestHost) Events() []string { return h.events }

// Logs returns the diagnostic lines, in emission order.
func (h *TestHost) Logs() []string { return h.logs }

// Sends returns the transfers that succeeded, in order.
func (h *TestHost) Sends() []Transfer { return h.sends }

// Keys returns every storage key the guest wrote, hex-encoded, in sorted
// order.
func (h *TestHost) Keys() []string {
	out := []string{}
	h.store.Iterate("", "", func(k string, _ any) bool {
		out = append(out, k)
		return false
	})
	return out
}

const hexDigits = "0123456789abcdef"

// hexKey encodes a raw key as hex so that arbitrary bytes, including a zero
// byte, survive being used as an avl key.
func hexKey(key []byte) string {
	out := make([]byte, 0, len(key)*2)
	for _, c := range key {
		out = append(out, hexDigits[c>>4], hexDigits[c&0x0f])
	}
	return string(out)
}

vmkit_test.gno

package vmkit

import (
	"testing"

	"gno.land/p/nt/uassert/v0"
)

// counter is a toy [Machine] used to test the kit itself without dragging in
// a real guest VM: it writes one byte per step and halts after `total` of
// them. Anything that works here is a property of the ABI, not of brainfuck.
type counter struct {
	total int64
	done  int64
	trap  string
}

func (c *counter) Step(h Host, fuel int64) (int64, Status) {
	m := NewMeter(fuel)
	var used int64
	for c.done < c.total {
		if !m.Charge(1) {
			return used, Running
		}
		used++
		c.done++
		h.Output([]byte{byte('a' + (c.done-1)%26)})
	}
	return used, Halted
}

func (c *counter) Snapshot() []byte {
	w := NewWriter(24)
	w.Int(c.total)
	w.Int(c.done)
	w.String(c.trap)
	return w.Out()
}

func (c *counter) Restore(b []byte) error {
	r := NewReader(b)
	total := r.Int()
	done := r.Int()
	trap := r.String()
	if err := r.Err(); err != nil {
		return err
	}
	c.total, c.done, c.trap = total, done, trap
	return nil
}

func (c *counter) Trap() string { return c.trap }

func TestStatusString(t *testing.T) {
	cases := []struct {
		s    Status
		want string
		done bool
	}{
		{Running, "running", false},
		{Halted, "halted", true},
		{Trapped, "trapped", true},
		{OutOfFuel, "out of fuel", true},
		{Status(99), "unknown", true},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, tc.s.String())
		uassert.Equal(t, tc.done, tc.s.Done())
	}
}

func TestMeterCharge(t *testing.T) {
	m := NewMeter(10)
	uassert.True(t, m.Charge(4))
	uassert.Equal(t, int64(4), m.Used())
	uassert.Equal(t, int64(6), m.Remaining())

	// A charge that does not fit spends nothing, so the caller can stop
	// before the instruction it cannot pay for.
	uassert.False(t, m.Charge(7))
	uassert.Equal(t, int64(4), m.Used())

	uassert.True(t, m.Charge(6))
	uassert.True(t, m.Exhausted())
	uassert.False(t, m.Charge(1))
}

func TestMeterUnmetered(t *testing.T) {
	m := NewMeter(Unmetered)
	uassert.True(t, m.Charge(1 << 40))
	uassert.False(t, m.Exhausted())
	uassert.Equal(t, Unmetered, m.Remaining())
}

func TestMeterZeroBudget(t *testing.T) {
	m := NewMeter(0)
	uassert.True(t, m.Exhausted())
	uassert.False(t, m.Charge(1))
	uassert.Equal(t, int64(0), m.Used())
}

func TestCodecRoundTrip(t *testing.T) {
	w := NewWriter(0)
	w.Byte(0xab)
	w.Uint32(0xdeadbeef)
	w.Uint64(0x0102030405060708)
	w.Int(-1234567)
	w.Int(0)
	w.Int(1234567)
	w.Bytes([]byte{0, 1, 2, 255})
	w.String("gno.land")

	r := NewReader(w.Out())
	uassert.Equal(t, uint64(0xab), uint64(r.Byte()))
	uassert.Equal(t, uint64(0xdeadbeef), uint64(r.Uint32()))
	uassert.Equal(t, uint64(0x0102030405060708), r.Uint64())
	uassert.Equal(t, int64(-1234567), r.Int())
	uassert.Equal(t, int64(0), r.Int())
	uassert.Equal(t, int64(1234567), r.Int())
	uassert.Equal(t, 4, len(r.Bytes()))
	uassert.Equal(t, "gno.land", r.String())
	uassert.NoError(t, r.Err())
	uassert.Equal(t, 0, r.Remaining())
}

func TestCodecIsCanonical(t *testing.T) {
	// The same state must always produce the same bytes: a snapshot is
	// consensus state, so two nodes encoding it differently is a fork.
	build := func() []byte {
		w := NewWriter(0)
		w.Int(-7)
		w.String("x")
		w.Uint32(9)
		return w.Out()
	}
	uassert.Equal(t, string(build()), string(build()))
}

func TestCodecTruncated(t *testing.T) {
	r := NewReader([]byte{1, 2})
	r.Uint64()
	uassert.ErrorIs(t, r.Err(), ErrTruncated)
	// Once latched, every later read is a zero value and the error stands.
	uassert.Equal(t, "", r.String())
	uassert.ErrorIs(t, r.Err(), ErrTruncated)
}

func TestCodecBytesAreCopied(t *testing.T) {
	w := NewWriter(0)
	w.Bytes([]byte{1, 2, 3})
	buf := w.Out()
	r := NewReader(buf)
	got := r.Bytes()
	buf[len(buf)-1] = 99 // mutate the snapshot under the reader
	uassert.Equal(t, 3, len(got))
	uassert.Equal(t, uint64(3), uint64(got[2]))
}

func TestTestHostStorage(t *testing.T) {
	h := NewTestHost()
	uassert.Equal(t, 0, len(h.Get([]byte("missing"))))

	h.Set([]byte{0, 1}, []byte("zero-prefixed"))
	h.Set([]byte("k"), []byte("v"))
	uassert.Equal(t, "zero-prefixed", string(h.Get([]byte{0, 1})))
	uassert.Equal(t, "v", string(h.Get([]byte("k"))))

	// Keys are hex so a zero byte survives, and sorted so a test can pin
	// them.
	keys := h.Keys()
	uassert.Equal(t, 2, len(keys))
	uassert.Equal(t, "0001", keys[0])
	uassert.Equal(t, "6b", keys[1])
}

func TestTestHostStorageIsCopied(t *testing.T) {
	h := NewTestHost()
	val := []byte("abc")
	h.Set([]byte("k"), val)
	val[0] = 'z'
	uassert.Equal(t, "abc", string(h.Get([]byte("k"))))

	got := h.Get([]byte("k"))
	got[0] = 'z'
	uassert.Equal(t, "abc", string(h.Get([]byte("k"))))
}

func TestTestHostSendNeedsAGrant(t *testing.T) {
	to := address("g1manfred47kzduec920z88wfr64ylksmdcedlf5")

	h := NewTestHost()
	uassert.ErrorIs(t, h.Send(to, 100), ErrNotGranted)
	uassert.Equal(t, 0, len(h.Sends()))

	h.Grant(150)
	uassert.NoError(t, h.Send(to, 100))
	uassert.Equal(t, 1, len(h.Sends()))
	uassert.Equal(t, int64(100), h.Sends()[0].Amount)

	// The grant is a budget, not a switch.
	uassert.ErrorIs(t, h.Send(to, 100), ErrNotGranted)
	uassert.NoError(t, h.Send(to, 50))
}

func TestTestHostEventsAndInput(t *testing.T) {
	h := NewTestHost().WithInput([]byte("hi")).WithHeight(42).WithTime(1700000000)
	uassert.Equal(t, "hi", string(h.Input()))
	uassert.Equal(t, int64(42), h.Height())
	uassert.Equal(t, int64(1700000000), h.Now())

	h.Emit("run", "id", "1", "status", "halted")
	h.Emit("odd", "dangling")
	uassert.Equal(t, 2, len(h.Events()))
	uassert.Equal(t, "run id=1 status=halted", h.Events()[0])
	uassert.Equal(t, "odd", h.Events()[1]) // odd trailing element dropped
}

func TestInstanceRunsToCompletion(t *testing.T) {
	inst := NewInstance("1", address("g1x"), "counter", []byte("5"), Unmetered)
	h := NewTestHost()
	uassert.NoError(t, inst.Run(&counter{total: 5}, h, Unmetered))
	uassert.Equal(t, "halted", inst.Status.String())
	uassert.Equal(t, int64(5), inst.FuelUsed)
	uassert.Equal(t, int64(1), inst.Slices)
	uassert.Equal(t, "abcde", h.OutString())
}

func TestInstanceResumesAcrossSlices(t *testing.T) {
	// The property that makes a guest program a contract: five slices of
	// one unit must equal one slice of five.
	inst := NewInstance("1", address("g1x"), "counter", []byte("5"), Unmetered)
	h := NewTestHost()
	for i := 0; i < 5; i++ {
		// A realm holds bytes, not a machine: every slice loads a fresh
		// one from the program and lets Restore carry the state over.
		uassert.NoError(t, inst.Run(&counter{total: 5}, h, 1))
	}
	uassert.Equal(t, "halted", inst.Status.String())
	uassert.Equal(t, int64(5), inst.FuelUsed)
	uassert.Equal(t, int64(5), inst.Slices)
	uassert.Equal(t, "abcde", h.OutString())
}

func TestInstanceStopsAtItsBudget(t *testing.T) {
	inst := NewInstance("1", address("g1x"), "counter", []byte("10"), 3)
	h := NewTestHost()
	uassert.NoError(t, inst.Run(&counter{total: 10}, h, Unmetered))
	uassert.Equal(t, "out of fuel", inst.Status.String())
	uassert.Equal(t, int64(3), inst.FuelUsed)
	uassert.Equal(t, int64(0), inst.Remaining())
	uassert.Equal(t, "abc", h.OutString())

	// A second call has nothing to spend and says so instead of looping.
	uassert.ErrorIs(t, inst.Run(&counter{}, h, Unmetered), ErrBudgetExhausted)
}

func TestInstanceSliceClamps(t *testing.T) {
	inst := NewInstance("1", address("g1x"), "counter", nil, 10)
	inst.FuelUsed = 7
	uassert.Equal(t, int64(3), inst.Slice(100))
	uassert.Equal(t, int64(2), inst.Slice(2))
	uassert.Equal(t, int64(3), inst.Slice(Unmetered))

	open := NewInstance("2", address("g1x"), "counter", nil, Unmetered)
	uassert.Equal(t, int64(5), open.Slice(5))
	uassert.Equal(t, Unmetered, open.Slice(Unmetered))
}

func TestInstanceRejectsABadSnapshot(t *testing.T) {
	inst := NewInstance("1", address("g1x"), "counter", []byte("5"), Unmetered)
	inst.Snapshot = []byte{1, 2, 3} // too short for the counter's three fields
	err := inst.Run(&counter{}, NewTestHost(), Unmetered)
	uassert.ErrorIs(t, err, ErrTruncated)
	// The instance is untouched: a snapshot that cannot be decoded costs
	// gas but never corrupts the stored program.
	uassert.Equal(t, int64(0), inst.Slices)
	uassert.Equal(t, "5", string(inst.Program))
}

func TestStore(t *testing.T) {
	s := NewStore()
	uassert.Equal(t, 0, s.Size())
	uassert.Equal(t, true, s.Get("nope") == nil)

	s.Set(NewInstance("001", address("g1a"), "counter", nil, Unmetered))
	s.Set(NewInstance("002", address("g1b"), "counter", nil, Unmetered))
	s.Set(NewInstance("003", address("g1c"), "counter", nil, Unmetered))
	uassert.Equal(t, 3, s.Size())
	uassert.Equal(t, "002", s.Get("002").ID)

	ids := ""
	s.Iterate(func(i *Instance) bool { ids += i.ID + " "; return false })
	uassert.Equal(t, "001 002 003 ", ids)

	rev := ""
	s.ReverseIterate(func(i *Instance) bool { rev += i.ID + " "; return false })
	uassert.Equal(t, "003 002 001 ", rev)

	// Early stop.
	first := ""
	s.Iterate(func(i *Instance) bool { first = i.ID; return true })
	uassert.Equal(t, "001", first)

	uassert.True(t, s.Remove("002"))
	uassert.False(t, s.Remove("002"))
	uassert.Equal(t, 2, s.Size())
}

func TestTrapReason(t *testing.T) {
	uassert.Equal(t, "boom", TrapReason(&counter{trap: "boom"}))
	uassert.Equal(t, "", TrapReason(&counter{}))
}