Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ the template's covenant, by arkd's signer for a leaf naming `<OPERATOR_KEY:fn>`
[emulator](https://github.com/arkade-os/emulator) for a leaf naming `<EMULATOR_KEY:fn>`. One daemon
serves both behind `ports.Emulator`, a router choosing by the leaf a transaction spends: keep the
application free of branches on which one signs. The default templates are registered at startup:
`renew` and `board` (non-interactive boarding) from [`templates/`](templates) for arkd and, when
`EXECUTOR_EMULATOR_URL` is set, those in [`templates/emulator/`](templates/emulator) for the
standalone emulator, the VHTLC claim stream `claim` among them. An onchain template is registered
by its document like any other: the daemon watches its input addresses, and arkd cosigns and
broadcasts the spend or the standalone emulator cosigns it and the daemon broadcasts. Port 7080 is
the public API, 7081 the admin API and UI: keep it private. Treat signing, forfeit, sweep and fee
code as code that moves money. When your Ark knowledge disagrees with the repo, trust the code but
if you think the code is buggy and conflicts with repo intentions then ask a human. For terms like
VTXO, batch, intent, forfeit or boarding, see the
[Arkade glossary](https://docs.arkadeos.com/learn/glossary).
`renew`, `board` (non-interactive boarding), `htlc` and `htlc_onchain` (the receiver's claim of an
HTLC, virtual or onchain) from [`templates/`](templates) for arkd and, when `EXECUTOR_EMULATOR_URL`
is set, those in [`templates/emulator/`](templates/emulator) for the standalone emulator, the VHTLC
claim stream `claim` among them. An onchain template is registered by its document like any other:
the daemon watches its input addresses, and arkd cosigns and broadcasts the spend or the standalone
emulator cosigns it and the daemon broadcasts. Port 7080 is the public API, 7081 the admin API and
UI: keep it private. Treat signing, forfeit, sweep and fee code as code that moves money. When your
Ark knowledge disagrees with the repo, trust the code but if you think the code is buggy and
conflicts with repo intentions then ask a human. For terms like VTXO, batch, intent, forfeit or
boarding, see the [Arkade glossary](https://docs.arkadeos.com/learn/glossary).

## Repository layout

Expand Down
17 changes: 13 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ a delegation on the addresses of its template inputs; every spend is co-signed o
the template's covenant, by arkd's signer or by a standalone
[emulator](https://github.com/arkade-os/emulator).

The default templates are registered at startup: `renew`, `board` (non-interactive boarding) and,
when `EXECUTOR_EMULATOR_URL` is set, `claim` (VHTLC claim stream).
The default templates are registered at startup: `renew`, `board` (non-interactive boarding), `htlc`
and `htlc_onchain` (the receiver's claim of an HTLC, virtual or onchain) and, when
`EXECUTOR_EMULATOR_URL` is set, `claim` (VHTLC claim stream).

## Emulation

Expand All @@ -34,15 +35,23 @@ A delegation whose spent leaves name both tweaked keys is refused. The two sets
different addresses: a wallet moves to the leaves arkd emulates by registering a delegation of
the new template and spending its coins to the new address, while its old delegations keep
renewing as long as `EXECUTOR_EMULATOR_URL` stays set. The `claim` stream ships for the standalone
emulator only: its leaf is the one of the VHTLC the swap creates.
emulator only: its leaf is the one of the VHTLC the swap creates. `htlc` and `htlc_onchain` ship for
arkd only: they spend the `nonInteractiveClaim` leaf of an HTLC locked as a VTXO or as a bitcoin
output. The receiver registers a delegation with the terms of the HTLC and its preimage sealed to
the daemon's sealing key and the template id, and the daemon claims the coin to `receiver_program`
once it is funded, onchain after one confirmation and for a fee of at most `claim_fee_cap_sat`. They
leave alone a coin arkd would refuse to claim: one below `min_claim_sat` or holding less than
`min_asset_amount` of the asset, and onchain one below `min_claim_sat` plus `claim_fee_cap_sat` or
locked with a `min_asset_amount`.

## Compiler artifacts

An artifact the [Arkade compiler](https://github.com/arkade-os/compiler) writes registers as it
is: `POST /v1/artifact` takes the JSON `arkadec` produces. The compiler names arkd's signer only,
so arkd runs the covenants of a compiled contract and a standalone emulator does not. The default
contracts arkd emulates are compiled from the `.ark` sources in
[`templates/artifacts/`](templates/artifacts): `make artifacts` compiles them again.
[`templates/artifacts/`](templates/artifacts): `make artifacts` compiles them again. `htlc.json` has
no `.ark` next to it: the artifact holds its source.

- `<OPERATOR_EXIT_DELAY>`, the `operatorExitDelay` of a contract, is arkd's unilateral exit delay,
read from arkd at startup: it is part of the address, like arkd's signer key.
Expand Down
4 changes: 1 addition & 3 deletions pkg/template/internal/asm/expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
var (
forbiddenPrefixes = []string{
"OP_INSPECTOUTPUT", "OP_INSPECTOUTASSET", "OP_INSPECTASSETGROUP", "OP_INSPECTINPUTARKADE",
"OP_INSPECTINASSET",
}
forbiddenOps = []string{
"OP_INSPECTNUMOUTPUTS", "OP_TUNNEL", "OP_INSPECTPACKET", "OP_INSPECTNUMASSETGROUPS",
Expand All @@ -40,7 +39,7 @@ func init() {
func ContextFree(tokens []string) bool {
return !slices.ContainsFunc(tokens, func(tok string) bool {
return forbidden(tok) || strings.HasPrefix(tok, "OP_INSPECTINPUT") ||
slices.Contains(contextOps, tok)
strings.HasPrefix(tok, "OP_INSPECTINASSET") || slices.Contains(contextOps, tok)
})
}

Expand Down Expand Up @@ -122,7 +121,6 @@ func CheckScript(script []byte, contextFree bool) error {
return nil
}

// forbidden reports whether tok observes outputs, assets or signatures.
func forbidden(tok string) bool {
return slices.Contains(forbiddenOps, tok) ||
slices.ContainsFunc(
Expand Down
8 changes: 6 additions & 2 deletions pkg/template/internal/asm/expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func TestCheckExpression(t *testing.T) {
"OP_INSPECTOUTPUTVALUE", "OP_INSPECTOUTPUTSCRIPTPUBKEY", "OP_INSPECTNUMOUTPUTS", "OP_TUNNEL", "OP_INSPECTPACKET",
"OP_INSPECTNUMASSETGROUPS", "OP_FINDASSETGROUPBYASSETID", "OP_INSPECTINPUTARKADESCRIPTHASH", "OP_INSPECTINTENTMESSAGE",
"OP_TXID", "OP_TXWEIGHT", "OP_SIGHASH", "OP_CHECKSIG", "OP_CHECKSIGVERIFY", "OP_CHECKSIGADD",
"OP_INSPECTINASSETCOUNT", "OP_INSPECTOUTASSETCOUNT",
"OP_INSPECTOUTASSETCOUNT", "OP_INSPECTOUTASSETLOOKUP",
} {
require.ErrorIs(t, CheckExpression([]string{op}), ErrBadExpression, op)
}
Expand All @@ -32,9 +32,13 @@ func TestCheckExpression(t *testing.T) {
strings.Fields("2 OP_PUSHCURRENTINPUTINDEX OP_INSPECTINPUTPACKET OP_VERIFY"),
),
)
require.NoError(
t, CheckExpression(strings.Fields("0 <txid> <gidx> OP_INSPECTINASSETLOOKUP OP_DROP")),
)
require.True(t, ContextFree([]string{"<preimage>", "OP_HASH160"}))
for _, op := range []string{"OP_INSPECTINPUTPACKET", "OP_PUSHCURRENTINPUTINDEX", "OP_INSPECTINPUTVALUE", "OP_PUSHEXPIRY", "OP_CHECKTIME", "OP_INSPECTVERSION", "OP_INSPECTLOCKTIME",
"OP_CHECKLOCKTIMEVERIFY", "OP_NOP2", "OP_CHECKSEQUENCEVERIFY", "OP_NOP3"} {
"OP_CHECKLOCKTIMEVERIFY", "OP_NOP2", "OP_CHECKSEQUENCEVERIFY", "OP_NOP3",
"OP_INSPECTINASSETLOOKUP", "OP_INSPECTINASSETCOUNT", "OP_INSPECTINASSETAT"} {
require.False(t, ContextFree([]string{op}), op)
}
}
Expand Down
38 changes: 23 additions & 15 deletions pkg/template/internal/version/v1/assets.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,28 @@ func (i *Instance) issueGroup(
func assetGroup(
t *Template, sources []*model.Source, a *allocation, id string,
) (*asset.AssetGroup, error) {
ins, err := assetInputs(sources, id)
if err != nil {
return nil, err
}
var outs []asset.AssetOutput
for k, o := range t.outputs {
if n := a.assets[k][id]; n > 0 {
out, err := asset.NewAssetOutput(o.index, n)
if err != nil {
return nil, err
}
outs = append(outs, *out)
}
}
aid, err := asset.NewAssetIdFromString(id)
if err != nil {
return nil, err
}
return asset.NewAssetGroup(aid, nil, ins, outs, nil)
}

func assetInputs(sources []*model.Source, id string) ([]asset.AssetInput, error) {
var ins []asset.AssetInput
for slot, s := range sources {
held := uint64(0)
Expand All @@ -377,19 +399,5 @@ func assetGroup(
}
ins = append(ins, *in)
}
var outs []asset.AssetOutput
for k, o := range t.outputs {
if n := a.assets[k][id]; n > 0 {
out, err := asset.NewAssetOutput(o.index, n)
if err != nil {
return nil, err
}
outs = append(outs, *out)
}
}
aid, err := asset.NewAssetIdFromString(id)
if err != nil {
return nil, err
}
return asset.NewAssetGroup(aid, nil, ins, outs, nil)
return ins, nil
}
41 changes: 41 additions & 0 deletions pkg/template/internal/version/v1/draft.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package v1

import (
"encoding/hex"
"errors"
"fmt"
"maps"
"slices"

"github.com/arkade-os/executor/pkg/template/internal/model"

"github.com/arkade-os/arkd/pkg/ark-lib/asset"
"github.com/arkade-os/emulator/pkg/arkade"
"github.com/arkade-os/executor/pkg/template/internal/asm"
"github.com/arkade-os/executor/pkg/template/internal/failure"
Expand Down Expand Up @@ -85,6 +88,11 @@ func (d *draft) eval(tokens []string, input int, lookup asm.Lookup) ([]byte, err
if src != nil && !src.Expiry.IsZero() {
arkade.WithExpiry(src.Expiry.Unix())(vm)
}
held, err := d.heldAssets()
if err != nil {
return nil, fmt.Errorf("%w: expression: %v", failure.ErrIneligible, err)
}
vm.SetAssetPacket(held)
for done := false; !done; {
if done, err = vm.Step(); err != nil {
return nil, fmt.Errorf("%w: expression: %s", failure.ErrIneligible, vmError(err))
Expand All @@ -101,6 +109,39 @@ func (d *draft) eval(tokens []string, input int, lookup asm.Lookup) ([]byte, err
return stack[0], nil
}

func (d *draft) heldAssets() (asset.Packet, error) {
sources := d.sources
if len(sources) > 0 && sources[0] == nil {
sources = sources[1:]
}
ids := map[string]bool{}
for _, s := range sources {
for _, as := range s.Assets {
ids[hex.EncodeToString(as.ID)] = true
}
}
packet := asset.Packet{}
for _, id := range slices.Sorted(maps.Keys(ids)) {
ins, err := assetInputs(sources, id)
if err != nil {
return nil, err
}
if len(ins) == 0 {
continue
}
aid, err := asset.NewAssetIdFromString(id)
if err != nil {
return nil, err
}
group, err := asset.NewAssetGroup(aid, nil, ins, nil, nil)
if err != nil {
return nil, err
}
packet = append(packet, *group)
}
return packet, nil
}

// source is nil for an intent's message input; false when op is unknown or refused.
func (d *draft) source(op wire.OutPoint) (*model.Source, bool) {
i := slices.IndexFunc(d.tx.TxIn, func(in *wire.TxIn) bool { return in.PreviousOutPoint == op })
Expand Down
48 changes: 48 additions & 0 deletions pkg/template/internal/version/v1/draft_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package v1

import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"strings"
"testing"

Expand All @@ -29,6 +31,52 @@ func TestEvalReadsSourcePacket(t *testing.T) {
require.Equal(t, owner, got)
}

func TestEvalReadsHeldAssets(t *testing.T) {
first, second := sourceWith(t, 100_000), sourceWith(t, 50_000)
first.Assets = []model.Asset{{ID: assetID(9), Amount: 21}}
second.Assets = []model.Asset{{ID: assetID(9), Amount: 5}, {ID: assetID(8), Amount: 7}}
lookup := func(input int, id []byte) string {
return fmt.Sprintf(
"%d 0x%x %d OP_INSPECTINASSETLOOKUP OP_DROP", input, id[:32],
binary.LittleEndian.Uint16(id[32:]),
)
}
fixtures := []struct {
name string
sources []*model.Source
expr string
expected int64
}{
{
name: "the amount an input holds", sources: []*model.Source{first, second},
expr: lookup(1, assetID(9)), expected: 5,
},
{
name: "an asset the input lacks", sources: []*model.Source{first, second},
expr: lookup(0, assetID(8)),
},
{
name: "an input without assets", sources: []*model.Source{sourceWith(t, 100_000)},
expr: lookup(0, assetID(9)),
},
{
name: "the number of assets of an input", sources: []*model.Source{first, second},
expr: "1 OP_INSPECTINASSETCOUNT", expected: 2,
},
{
name: "an asset of an input by its position", sources: []*model.Source{first, second},
expr: "1 0 OP_INSPECTINASSETAT OP_NIP OP_NIP", expected: 7,
},
}
for _, f := range fixtures {
t.Run(f.name, func(t *testing.T) {
got, err := newDraft(model.Virtual, f.sources).eval(strings.Fields(f.expr), 0, nil)
require.NoError(t, err)
require.Equal(t, asm.ScriptNum(f.expected), got)
})
}
}

func TestEvalCounter(t *testing.T) {
src := sourceWith(t, 100_000, packets.Raw(packets.TypeState, []byte{5, 0, 0, 0, 0, 0, 0, 0}))
d := newDraft(model.Proof, []*model.Source{src})
Expand Down
Loading
Loading