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
129 changes: 129 additions & 0 deletions cmd/ternchain/scan_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package main

import (
"context"
"fmt"
"path/filepath"
"testing"

netscan "github.com/nenkoru/tern/internal/scan"
)

// The scanner (internal/scan, examples/scanner) reads a network's names,
// cards, payments, locks, swaps, claims and mail volume from its events alone,
// and a second run picks up only what is new.
func TestScanNetwork(t *testing.T) {
w := newWorld(t)
alice, _ := w.owner("alice")
bob, _ := w.owner("bob")
carol, _ := w.owner("carol")
ai := w.agent(alice, "ai", coins(3), `{"free_pay":"0.3"}`)
w.must(alice.deposit(coins(10)))
w.must(bob.deposit(coins(10)))
w.must(alice.setCard(`{"offer":"proofreading"}`))
w.must(alice.pay("bob", coins(1.5), "thanks"))

// An escrow ruled 70/30, and one left open.
open := func(args ...string) uint64 {
m := lockOut(t, func() error { return runLockOpen(alice, args, lockFlags{prim: primFlags{days: 30}}) })
return uint64(m["lock"].(float64))
}
esc := open("escrow", "bob", "carol", "1", "translate", "the", "site")
lockOut(t, func() error { return runLockDecide(carol, []string{fmt.Sprint(esc), "7000", "partly", "done"}) })
lockOut(t, func() error { return runLockSettle(bob, []string{fmt.Sprint(esc)}) })
pending := open("escrow", "bob", "carol", "0.5", "logo")

w.must(alice.attest("bob", "review", "on time", 0))
if _, err := ai.send(SendOpts{To: "alice", Intent: "inform", Text: "hello from your agent"}); err != nil {
t.Fatal(err)
}

net := netscan.Net{Network: "test", ChainID: w.ch.chainID.Int64(), Contracts: w.ch.dep.Contracts, Block: w.ch.dep.Block, Schema: w.ch.dep.Schema}
if net.Schema == "" {
net.Schema = alice.schema().Hex()
}
cache := filepath.Join(t.TempDir(), "scan.json")
ctx := context.Background()
s := netscan.Load(cache, net)
update := func() {
t.Helper()
if err := s.Update(ctx, w.sim.Client(), net, netscan.Options{Save: func(s *netscan.State) error { return s.Save(cache) }}); err != nil {
t.Fatal(err)
}
}
update()

if n := s.Names["alice"]; n == nil || n.Kind != "owner" || n.Card != `{"offer":"proofreading"}` || len(n.Agents) != 1 || n.Agents[0] != "ai.alice" {
t.Fatalf("alice: %+v", n)
}
if a := s.Names["ai.alice"]; a == nil || a.Kind != "agent" || a.Owner != "alice" || a.Limits[netscan.Coin] != coins(3).String() {
t.Fatalf("ai.alice: %+v", a)
}
var paid bool
for _, p := range s.Payments {
if p.From == "alice" && p.To == "bob" && p.Amount == "1.5" && p.Token == netscan.Coin {
paid = true
}
}
if !paid {
t.Fatalf("alice's payment to bob is missing: %+v", s.Payments)
}
l := lockByID(s, esc)
if l == nil || l.Kind != "escrow" || l.Decider != "carol" || l.From != "alice" || l.Payee != "bob" || l.Status != "split" ||
l.Paid != "0.7" || l.Refunded != "0.3" {
t.Fatalf("the ruled escrow: %+v", l)
}
if l := lockByID(s, pending); l == nil || l.Status != "open" || l.Total != "0.5" {
t.Fatalf("the open escrow: %+v", l)
}
var reviewed bool
for _, c := range s.Claims {
if c.Attester == "alice" && c.Subject == "bob" && c.Kind == "review" && c.Data == "on time" {
reviewed = true
}
}
if !reviewed {
t.Fatalf("alice's claim about bob is missing: %+v", s.Claims)
}
if mailCount(s) == 0 {
t.Fatal("no mail counted")
}

// A second run from the cache adds only what is new: an item sold for coins (a swap).
before := len(s.Payments) + len(s.Locks)
sword, err := alice.createItem("ipfs://sword.json", 10, false)
w.must(err)
w.must(alice.mintItem(sword, "alice", 2))
offer, err := alice.offerItem(sword, 1, coins(2), "", "")
w.must(err)
_, err = bob.buyItem(offer)
w.must(err)
s = netscan.Load(cache, net)
update()
if len(s.Swaps) != 1 {
t.Fatalf("swaps: %+v", s.Swaps)
}
item, coin := lockByID(s, s.Swaps[0].Offer), lockByID(s, s.Swaps[0].Answer)
if item == nil || coin == nil || item.Item != fmt.Sprint(sword) || item.Total != "1" || coin.Total != "2" || item.Status != "paid" || coin.Status != "paid" {
t.Fatalf("the swap's locks: %+v %+v", item, coin)
}
if got := len(s.Payments) + len(s.Locks); got != before+2 {
t.Fatalf("the second run counted %d new payments and locks, want 2 (the swap's locks)", got-before)
}
}

func lockByID(s *netscan.State, id uint64) *netscan.Lock {
for _, l := range s.Locks {
if l.ID == id {
return l
}
}
return nil
}

func mailCount(s *netscan.State) (n uint64) {
for _, m := range s.Mail {
n += m.Envelopes
}
return n
}
68 changes: 68 additions & 0 deletions examples/scanner/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Scanner: what is happening on the network

A block explorer shows transactions and addresses. This shows tern: who has a name and which agents, what their cards offer, who paid whom, which deals are open and how the closed ones ended, what was swapped and at what price, who said what about whom, and how much mail goes through.

It only reads the chain's public events (and a few view calls): no key, no name, no faucet, nothing sent. Mail is sealed, so it counts envelopes and bytes per day and nothing else.

Built from: the events of Registry, Bank, SwapCondition, EAS and Inbox, the ABIs the binary already embeds, and `net.json`. The code is `internal/scan` (the scan) and `main.go` here (the views). No new contracts.

## Try it

From the repository's root:

```sh
go run ./examples/scanner
```

The first run reads the network from the block its contracts were deployed in, 10,000 blocks per request (`log_range` in `net.json`), and keeps what it read in your cache directory (`ternscan/`). Later runs read only the new blocks. An interrupted scan goes on where it stopped. A request that fails (public RPCs drop one now and then) is tried again a few times; an RPC that keeps failing is replaced by the next one in `net.json` (`rpcs`), which goes on from the last block read. `--rpc URL` uses that one only.

```text
scanner [COMMAND] [flags]

(none) the summary
names every name: owners, their agents, cards
name NAME one name: its agents, card, payments, deals, claims
deals every lock (escrow, bond, swap, subscription…) and how it ended
payments every payment
swaps swaps, with the price when one side is money
claims claims (reviews, ratings, rulings…)
mail envelopes and bytes per day
serve a web page with all of it, scanned again every --every
```

Flags: `--net FILE` (default `$TERNCHAIN_NET`, then `~/tern/net.json`, then `networks/tern-base-sepolia-1/net.json`), `--rpc URL`, `--json`, `--offline` (only the cache), `--limit N` (rows, newest first; default 50, 0 for all), `--confirmations N` (stay N blocks behind the head; default 3), `--cache DIR`, and for `serve`: `--listen ADDR` (default `127.0.0.1:8080`) and `--every D` (default `1m`).

`--json` prints the same thing for programs. With no command it prints everything scanned: names, payments, locks, swaps, claims, mail per day and the tokens seen. Amounts are given in whole units and, in the `*_raw` fields, as integers in the token's smallest unit.

## The web page

```sh
go run ./examples/scanner serve
```

Open http://127.0.0.1:8080/. One page, nothing loaded from elsewhere: an overview (counts, recent activity, mail per day), then names, deals, payments, swaps, claims and mail, each filterable. A name links to its page (`#name=alice`): its agents, card, deals, payments and claims. The server reads new blocks every `--every` and the page fetches them; `--offline` serves the cache as it is. If the chain can't be read, the page keeps showing the cache and says why.

The page fetches `/state.json`: the same as `--json`, plus `order` (owners, each followed by its agents), `swap_rows` (both sides and the price) and `every_seconds`.

Everything on the page was written by someone on the network (names, cards, claims). The page puts it in as text, never as markup, and its Content-Security-Policy lets nothing load or run from elsewhere. It listens on 127.0.0.1 by default; put it behind a reverse proxy to share it.

## What it reads, and what it can't tell

| Shown | From |
|---|---|
| names, agents, agents' daily limits, revocations, cards | `Registry`: `OwnerRegistered`, `AgentGranted`, `AgentRevoked`, `CardSet`; `Bank`: `TokenLimitSet` |
| payments | `Bank`: `Paid`, `TokenPaid` |
| deals | `Bank`: `Locked` (its kind from the condition and, for `AttestationCondition`, the demand: escrow, bond, bounty; a lock held by `TernJobs` is an ERC-8183 job), `Claimed`, `Released`, `Refunded`, `GivenBack`; the token and item from `Bank.locks` and `Bank.itemOf` |
| swaps | `SwapCondition`: `Swapped`, with both sides' locks |
| claims | `EAS`: `Attested` with tern's claim schema, read with `getAttestation`; `Revoked` |
| mail | `Inbox`: `Posted`, `Committed` (envelopes and bytes) |

- **Who is behind a payment.** Payments and locks name owner and agent ids, so they show as names. A split or a deal subject shows as a short hash. A claim's issuer is an address; it shows as a name when that address is a name's controller or agent key.
- **Times** are interpolated between each range's first and last block: exact on Base (a block every 2 seconds), close elsewhere.
- **"past its refund time"** is a lock nobody settled or refunded yet after its refund time: its payer can take it back.
- **Mail volume** counts envelopes as the Inbox saw them, whoever sent them. Group posts, receipts and votes are envelopes too.

## Make it yours

- **A price feed.** `swaps --json` gives every settled swap with both sides. A price for a token or an item is an average over a window of these, from distinct owners, above a minimum volume (one trade with yourself must not move it).
- **Alerts.** Run it from cron with `--json` and compare: a new card with a word you care about, a deal of yours past its refund time, a claim about you.
Loading