Playground
gnomod.toml
module = "gno.land/r/g1pzn6rn8q0pfmq4xje4j8086ncnldavyz8skgp3/idlewatt" gno = "0.9" [addpkg] creator = "g1pzn6rn8q0pfmq4xje4j8086ncnldavyz8skgp3" height = 1359127 max_deposit = "100000000ugnot"
idlewatt.gno
// Package idlewatt is an on-chain registry and dashboard for idle compute
// nodes: home GPU boxes today, and someday parked vehicles, that want to rent
// spare capacity on decentralized compute networks such as Akash.
//
// IMPORTANT: every node, heartbeat and job in this realm is self-reported or
// simulated by its operator. There is no Tesla or Akash integration and no
// hardware attestation; earnings are simulated USD figures, not payments.
package idlewatt
import (
"chain"
"strconv"
"strings"
"time"
"gno.land/p/nt/avl/v0"
)
// Tunables.
const (
maxNodes = 1000
maxNodesPerOperator = 10
minHeartbeatInterval = 10 * time.Second
poolBps = 1400 // 14% of every job feeds the fairness pool (a nod to AtomOne's Nakamoto Bonus)
minBonusEpoch = time.Hour
minOnlineWindow = 5 * time.Minute
maxOnlineWindow = 7 * 24 * time.Hour
)
var (
admin address
paused bool // when true, new registrations are refused
onlineWindow = 30 * time.Minute
nextNodeID = 1
nextJobID = 1
nodes = avl.NewTree() // padID(nodeID) -> *Node
byOperator = avl.NewTree() // operator + "/" + padID -> nodeID
leaderboard = avl.NewTree() // rankKey(total, id) -> nodeID
jobs = avl.NewTree() // padID(jobID) -> *Job
nodeJobs = avl.NewTree() // padID(nodeID) + "/" + padID(jobID) -> jobID
totalGrossCents int64
poolCents int64 // undistributed fairness pool
poolPaidCents int64 // distributed so far
bonusRounds int
lastDistribution time.Time
)
// realmURL is this realm's gnoweb path, e.g. /r/<addr>/idlewatt.
var realmURL string
func init(cur realm) {
admin = cur.Previous().Address()
realmURL = strings.TrimPrefix(cur.PkgPath(), "gno.land")
}
// ---------------------------------------------------------------------------
// Operator actions. Every one of them is a signed transaction, so the
// operator address is authenticated by the chain itself.
// RegisterNode adds a node owned by the caller and returns its ID.
// kind: home-gpu | vehicle | cpu. power: grid | solar | powershare-backup.
// rateCents: asking price in US cents per hour (e.g. 45 = $0.45/h).
func RegisterNode(cur realm, name, kind, hardware, region, power string, rateCents int64) int {
caller := mustCaller(cur)
if paused {
panic("registrations are paused by the realm admin")
}
checkText("name", name, minNameLen, maxNameLen)
checkKind(kind)
checkText("hardware", hardware, minNameLen, maxHardwareLen)
checkText("region", region, minRegionLen, maxRegionLen)
checkPower(power)
checkRate(rateCents)
if nodes.Size() >= maxNodes {
panic("registry is full")
}
if operatorNodeCount(caller) >= maxNodesPerOperator {
panic("an operator can register at most " + strconv.Itoa(maxNodesPerOperator) + " nodes")
}
now := time.Now()
n := &Node{
ID: nextNodeID,
Operator: caller,
Name: name,
Kind: kind,
Hardware: hardware,
Region: region,
Power: power,
RateCents: rateCents,
Mode: ModePaused,
RegisteredAt: now,
}
nextNodeID++
nodes.Set(padID(n.ID), n)
byOperator.Set(caller.String()+"/"+padID(n.ID), n.ID)
leaderboard.Set(rankKey(0, n.ID), n.ID)
chain.Emit("NodeRegistered",
"id", strconv.Itoa(n.ID),
"operator", caller.String(),
"kind", kind,
"region", region,
"power", power,
"rateCents", strconv.FormatInt(rateCents, 10),
)
return n.ID
}
// UpdateNode changes a node's descriptive fields and rate. Only the operator.
func UpdateNode(cur realm, id int, name, hardware, region, power string, rateCents int64) {
caller := mustCaller(cur)
n := mustOwnNode(id, caller)
checkText("name", name, minNameLen, maxNameLen)
checkText("hardware", hardware, minNameLen, maxHardwareLen)
checkText("region", region, minRegionLen, maxRegionLen)
checkPower(power)
checkRate(rateCents)
n.Name = name
n.Hardware = hardware
n.Region = region
n.Power = power
n.RateCents = rateCents
chain.Emit("NodeUpdated", "id", strconv.Itoa(id), "rateCents", strconv.FormatInt(rateCents, 10))
}
// SetRate changes only the hourly asking rate (US cents). Only the operator.
func SetRate(cur realm, id int, rateCents int64) {
caller := mustCaller(cur)
n := mustOwnNode(id, caller)
checkRate(rateCents)
n.RateCents = rateCents
chain.Emit("NodeUpdated", "id", strconv.Itoa(id), "rateCents", strconv.FormatInt(rateCents, 10))
}
// SetAvailability switches a node between available (parked & plugged in),
// driving (vehicles only) and paused. Only the operator.
func SetAvailability(cur realm, id int, mode string) {
caller := mustCaller(cur)
n := mustOwnNode(id, caller)
checkMode(n.Kind, mode)
if n.Mode == mode {
return
}
prev := n.Mode
n.Mode = mode
chain.Emit("AvailabilityChanged", "id", strconv.Itoa(id), "from", prev, "to", mode)
}
// Heartbeat records a signed liveness ping for a node, with an optional
// short status note (e.g. "SoC 82%, 41C"). Only the operator.
func Heartbeat(cur realm, id int, note string) {
caller := mustCaller(cur)
n := mustOwnNode(id, caller)
if note != "" {
checkText("note", note, 1, maxNoteLen)
}
now := time.Now()
if !n.LastHeartbeat.IsZero() {
gap := now.Sub(n.LastHeartbeat)
if gap < minHeartbeatInterval {
panic("heartbeat too frequent: wait at least 10 seconds")
}
if gap > onlineWindow {
n.SessionStart = now // the previous run was broken
}
} else {
n.SessionStart = now
}
n.LastHeartbeat = now
n.HeartbeatCount++
n.LastNote = note
chain.Emit("Heartbeat", "id", strconv.Itoa(id), "count", strconv.Itoa(n.HeartbeatCount))
}
// RecordJob records a completed (simulated) job on a node, e.g. an AI
// inference lease. Earnings are computed by the realm from the node's rate
// and the duration, so operators cannot claim arbitrary amounts. The node
// must be available and online. 14% of the gross goes to the fairness pool.
func RecordJob(cur realm, id int, workload string, minutes int) int {
caller := mustCaller(cur)
n := mustOwnNode(id, caller)
checkText("workload", workload, minNameLen, maxWorkloadLen)
if minutes < 1 || minutes > maxJobMinutes {
panic("minutes must be between 1 and 1440")
}
if n.Mode != ModeAvailable {
panic("node must be available (parked & plugged in) to take jobs")
}
now := time.Now()
if !isOnlineAt(n, now) {
panic("node is offline: send a heartbeat first")
}
gross := n.RateCents * int64(minutes) / 60
pool := gross * poolBps / 10000
op := gross - pool
j := &Job{
ID: nextJobID,
NodeID: n.ID,
NodeName: n.Name,
Workload: workload,
Minutes: minutes,
RateCents: n.RateCents,
GrossCents: gross,
PoolCents: pool,
OperatorCents: op,
CompletedAt: now,
}
nextJobID++
jobs.Set(padID(j.ID), j)
nodeJobs.Set(padID(n.ID)+"/"+padID(j.ID), j.ID)
oldTotal := n.TotalCents()
n.JobCount++
n.JobMinutes += int64(minutes)
n.EarnedCents += op
reRank(n, oldTotal)
totalGrossCents += gross
poolCents += pool
chain.Emit("JobRecorded",
"job", strconv.Itoa(j.ID),
"node", strconv.Itoa(n.ID),
"minutes", strconv.Itoa(minutes),
"grossCents", strconv.FormatInt(gross, 10),
"poolCents", strconv.FormatInt(pool, 10),
"simulated", "true",
)
return j.ID
}
// RemoveNode deletes the caller's node. Its job history stays on the record.
func RemoveNode(cur realm, id int) {
caller := mustCaller(cur)
n := mustOwnNode(id, caller)
removeNode(n)
chain.Emit("NodeRemoved", "id", strconv.Itoa(id), "by", "operator")
}
// DistributeBonus splits the fairness pool equally across every node that is
// online and available right now, regardless of size or earnings, like
// AtomOne's Nakamoto Bonus splits its pool equally across validators.
// Anyone may call it, at most once per hour. Returns how many nodes shared.
func DistributeBonus(cur realm) int {
mustCaller(cur)
now := time.Now()
if !lastDistribution.IsZero() && now.Sub(lastDistribution) < minBonusEpoch {
panic("the bonus can be distributed at most once per hour")
}
if poolCents <= 0 {
panic("the fairness pool is empty")
}
var eligible []*Node
nodes.Iterate("", "", func(_ string, v any) bool {
n := v.(*Node)
if n.Mode == ModeAvailable && isOnlineAt(n, now) {
eligible = append(eligible, n)
}
return false
})
if len(eligible) == 0 {
panic("no node is online and available to share the pool")
}
share := poolCents / int64(len(eligible))
if share == 0 {
panic("the pool is too small to split")
}
for _, n := range eligible {
old := n.TotalCents()
n.BonusCents += share
reRank(n, old)
}
paid := share * int64(len(eligible))
poolCents -= paid // the remainder stays for next round
poolPaidCents += paid
bonusRounds++
lastDistribution = now
chain.Emit("BonusDistributed",
"round", strconv.Itoa(bonusRounds),
"nodes", strconv.Itoa(len(eligible)),
"shareCents", strconv.FormatInt(share, 10),
)
return len(eligible)
}
// ---------------------------------------------------------------------------
// Admin actions (moderation of a public demo registry).
// SetPaused stops or resumes new registrations.
func SetPaused(cur realm, p bool) {
mustAdmin(cur)
paused = p
chain.Emit("PausedChanged", "paused", strconv.FormatBool(p))
}
// SetOnlineWindowMinutes sets how long after its last heartbeat a node still
// counts as online (5 minutes to 7 days).
func SetOnlineWindowMinutes(cur realm, minutes int) {
mustAdmin(cur)
w := time.Duration(minutes) * time.Minute
if w < minOnlineWindow || w > maxOnlineWindow {
panic("online window must be between 5 and 10080 minutes")
}
onlineWindow = w
chain.Emit("OnlineWindowChanged", "minutes", strconv.Itoa(minutes))
}
// AdminRemoveNode removes a spam or abusive node.
func AdminRemoveNode(cur realm, id int) {
mustAdmin(cur)
n := mustGetNode(id)
removeNode(n)
chain.Emit("NodeRemoved", "id", strconv.Itoa(id), "by", "admin")
}
// TransferAdmin hands the admin role to another address.
func TransferAdmin(cur realm, newAdmin address) {
mustAdmin(cur)
if !newAdmin.IsValid() {
panic("invalid address")
}
old := admin
admin = newAdmin
chain.Emit("AdminChanged", "from", old.String(), "to", newAdmin.String())
}
// ---------------------------------------------------------------------------
// Read-only helpers (safe to query with vm/qeval).
// Admin returns the admin address.
func Admin() address { return admin }
// NodeCount returns the number of registered nodes.
func NodeCount() int { return nodes.Size() }
// Stats returns nodes, online nodes, simulated gross earnings (cents) and the
// undistributed fairness pool (cents).
func Stats() (int, int, int64, int64) {
return nodes.Size(), countOnline(time.Now()), totalGrossCents, poolCents
}
// NodeSummary returns a one-line text summary of a node, or "" if unknown.
func NodeSummary(id int) string {
v := nodes.Get(padID(id))
if v == nil {
return ""
}
n := v.(*Node)
return n.Name + " | " + n.Kind + " | " + n.Region + " | " + n.Power + " | " +
fmtUSD(n.RateCents) + "/h | " + statusOf(n, time.Now()) + " | earned " + fmtUSD(n.TotalCents())
}
// ---------------------------------------------------------------------------
// internals
func mustCaller(cur realm) address {
if !cur.IsCurrent() {
panic("spoofed realm")
}
prev := cur.Previous()
if !prev.IsUser() {
panic("only user accounts can call this")
}
return prev.Address()
}
func mustAdmin(cur realm) {
if mustCaller(cur) != admin {
panic("only the admin can do this")
}
}
func mustGetNode(id int) *Node {
v := nodes.Get(padID(id))
if v == nil {
panic("node " + strconv.Itoa(id) + " not found")
}
return v.(*Node)
}
func mustOwnNode(id int, caller address) *Node {
n := mustGetNode(id)
if n.Operator != caller {
panic("only the node's operator can do this")
}
return n
}
func removeNode(n *Node) {
nodes.Remove(padID(n.ID))
byOperator.Remove(n.Operator.String() + "/" + padID(n.ID))
leaderboard.Remove(rankKey(n.TotalCents(), n.ID))
}
func reRank(n *Node, oldTotal int64) {
leaderboard.Remove(rankKey(oldTotal, n.ID))
leaderboard.Set(rankKey(n.TotalCents(), n.ID), n.ID)
}
func operatorNodeCount(op address) int {
count := 0
prefix := op.String() + "/"
byOperator.Iterate(prefix, prefix+"~", func(_ string, _ any) bool {
count++
return false
})
return count
}
func isOnlineAt(n *Node, now time.Time) bool {
if n.LastHeartbeat.IsZero() {
return false
}
return now.Sub(n.LastHeartbeat) <= onlineWindow
}
func countOnline(now time.Time) int {
count := 0
nodes.Iterate("", "", func(_ string, v any) bool {
if isOnlineAt(v.(*Node), now) {
count++
}
return false
})
return count
}
// padID makes IDs sort numerically as avl keys.
func padID(id int) string {
s := strconv.Itoa(id)
for len(s) < 9 {
s = "0" + s
}
return s
}
// rankKey sorts the highest total first, ties broken by lowest node ID.
func rankKey(totalCents int64, id int) string {
const ceiling = int64(999999999999999)
inv := strconv.FormatInt(ceiling-totalCents, 10)
for len(inv) < 15 {
inv = "0" + inv
}
return inv + "/" + padID(id)
}
idlewatt_test.gno
package idlewatt
import (
"strings"
"testing"
"time"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
carol = testutils.TestAddress("carol")
boss = testutils.TestAddress("boss")
who address // the account the next call is signed by
)
// reset puts the realm back to a clean state between tests.
func reset() {
admin = boss
paused = false
onlineWindow = 30 * time.Minute
nextNodeID = 1
nextJobID = 1
nodes = avl.NewTree()
byOperator = avl.NewTree()
leaderboard = avl.NewTree()
jobs = avl.NewTree()
nodeJobs = avl.NewTree()
totalGrossCents = 0
poolCents = 0
poolPaidCents = 0
bonusRounds = 0
lastDistribution = time.Time{}
}
func registerGPU(cur realm, op address, name string, rate int64) int {
who = op
testing.SetRealm(testing.NewUserRealm(who))
return RegisterNode(cross(cur), name, KindHomeGPU, "RTX 4090 24GB", "US-NY Buffalo", PowerGrid, rate)
}
// bringOnline heartbeats a node and makes it available.
func bringOnline(cur realm, op address, id int) {
who = op
testing.SetRealm(testing.NewUserRealm(who))
Heartbeat(cross(cur), id, "")
SetAvailability(cross(cur), id, ModeAvailable)
}
func TestRegisterNode(cur realm, t *testing.T) {
reset()
who = alice
testing.SetRealm(testing.NewUserRealm(who))
id := RegisterNode(cross(cur), "Tonawanda Cybertruck (simulated)", KindVehicle, "AMD Ryzen infotainment + AI4", "US-NY Tonawanda", PowerPowershare, 30)
uassert.Equal(t, 1, id)
uassert.Equal(t, 1, NodeCount())
n := mustGetNode(id)
uassert.Equal(t, alice, n.Operator)
uassert.Equal(t, KindVehicle, n.Kind)
uassert.Equal(t, ModePaused, n.Mode, "new nodes start paused")
uassert.Equal(t, int64(30), n.RateCents)
uassert.True(t, n.LastHeartbeat.IsZero())
uassert.Equal(t, 1, operatorNodeCount(alice))
uassert.Equal(t, 1, leaderboard.Size())
id2 := registerGPU(cur, bob, "Garage 4090", 45)
uassert.Equal(t, 2, id2, "ids are sequential")
}
func TestRegisterValidation(cur realm, t *testing.T) {
reset()
who = alice
testing.SetRealm(testing.NewUserRealm(who))
cases := []struct {
name, kind, hw, region, power string
rate int64
want string
}{
{"ab", KindCPU, "Xeon", "US", PowerGrid, 10, "name must be 3-48 characters"},
{strings.Repeat("x", 49), KindCPU, "Xeon", "US", PowerGrid, 10, "name must be 3-48 characters"},
{" lead", KindCPU, "Xeon", "US", PowerGrid, 10, "name must not start or end with a space"},
{"bad|pipe", KindCPU, "Xeon", "US", PowerGrid, 10, "name contains an unsupported character: only letters, digits, spaces and - . , ( ) ' / + : @ # % & = are allowed"},
{"<script>", KindCPU, "Xeon", "US", PowerGrid, 10, "name contains an unsupported character: only letters, digits, spaces and - . , ( ) ' / + : @ # % & = are allowed"},
{"[link](x)", KindCPU, "Xeon", "US", PowerGrid, 10, "name contains an unsupported character: only letters, digits, spaces and - . , ( ) ' / + : @ # % & = are allowed"},
{"Box", "datacenter", "Xeon", "US", PowerGrid, 10, "kind must be one of: home-gpu, vehicle, cpu"},
{"Box", KindCPU, "Xeon", "US", "coal", 10, "power must be one of: grid, solar, powershare-backup"},
{"Box", KindCPU, "Xeon", "U", PowerGrid, 10, "region must be 2-40 characters"},
{"Box", KindCPU, "X", "US", PowerGrid, 10, "hardware must be 3-80 characters"},
{"Box", KindCPU, "Xeon", "US", PowerGrid, 0, "rate must be between 1 and 100000 US cents per hour"},
{"Box", KindCPU, "Xeon", "US", PowerGrid, 100001, "rate must be between 1 and 100000 US cents per hour"},
}
for _, c := range cases {
urequire.AbortsWithMessage(t, cur, c.want, func() {
testing.SetRealm(testing.NewUserRealm(who))
RegisterNode(cross(cur), c.name, c.kind, c.hw, c.region, c.power, c.rate)
})
}
uassert.Equal(t, 0, NodeCount(), "no invalid node was stored")
}
func TestOperatorLimit(cur realm, t *testing.T) {
reset()
for i := 0; i < maxNodesPerOperator; i++ {
registerGPU(cur, alice, "Node number "+string(rune('A'+i)), 10)
}
who = alice
testing.SetRealm(testing.NewUserRealm(who))
urequire.AbortsWithMessage(t, cur, "an operator can register at most 10 nodes", func() {
testing.SetRealm(testing.NewUserRealm(who))
RegisterNode(cross(cur), "One too many", KindCPU, "Xeon", "US", PowerGrid, 10)
})
// Another operator is unaffected.
registerGPU(cur, bob, "Bob box", 10)
uassert.Equal(t, maxNodesPerOperator+1, NodeCount())
}
func TestAccessControl(cur realm, t *testing.T) {
reset()
id := registerGPU(cur, alice, "Alice box", 40)
who = bob
testing.SetRealm(testing.NewUserRealm(who))
const msg = "only the node's operator can do this"
urequire.AbortsWithMessage(t, cur, msg, func() {
testing.SetRealm(testing.NewUserRealm(who))
Heartbeat(cross(cur), id, "")
})
urequire.AbortsWithMessage(t, cur, msg, func() {
testing.SetRealm(testing.NewUserRealm(who))
SetAvailability(cross(cur), id, ModeAvailable)
})
urequire.AbortsWithMessage(t, cur, msg, func() {
testing.SetRealm(testing.NewUserRealm(who))
SetRate(cross(cur), id, 1)
})
urequire.AbortsWithMessage(t, cur, msg, func() {
testing.SetRealm(testing.NewUserRealm(who))
UpdateNode(cross(cur), id, "Stolen", "RTX", "US", PowerGrid, 1)
})
urequire.AbortsWithMessage(t, cur, msg, func() {
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), id, "steal", 60)
})
urequire.AbortsWithMessage(t, cur, msg, func() {
testing.SetRealm(testing.NewUserRealm(who))
RemoveNode(cross(cur), id)
})
urequire.AbortsWithMessage(t, cur, "node 99 not found", func() {
testing.SetRealm(testing.NewUserRealm(who))
Heartbeat(cross(cur), 99, "")
})
n := mustGetNode(id)
uassert.Equal(t, int64(40), n.RateCents, "bob changed nothing")
uassert.Equal(t, "Alice box", n.Name)
}
func TestUpdateAndRate(cur realm, t *testing.T) {
reset()
id := registerGPU(cur, alice, "Alice box", 40)
who = alice
testing.SetRealm(testing.NewUserRealm(who))
UpdateNode(cross(cur), id, "Alice solar box", "RTX 3090", "US-NY Amherst", PowerSolar, 35)
n := mustGetNode(id)
uassert.Equal(t, "Alice solar box", n.Name)
uassert.Equal(t, PowerSolar, n.Power)
uassert.Equal(t, int64(35), n.RateCents)
SetRate(cross(cur), id, 50)
uassert.Equal(t, int64(50), n.RateCents)
urequire.AbortsWithMessage(t, cur, "rate must be between 1 and 100000 US cents per hour", func() {
testing.SetRealm(testing.NewUserRealm(who))
SetRate(cross(cur), id, -5)
})
}
func TestHeartbeatAndOnline(cur realm, t *testing.T) {
reset()
id := registerGPU(cur, alice, "Alice box", 40)
n := mustGetNode(id)
uassert.False(t, isOnlineAt(n, time.Now()), "no heartbeat yet")
who = alice
testing.SetRealm(testing.NewUserRealm(who))
Heartbeat(cross(cur), id, "GPU 41C")
uassert.True(t, isOnlineAt(n, time.Now()))
uassert.Equal(t, 1, n.HeartbeatCount)
uassert.Equal(t, "GPU 41C", n.LastNote)
urequire.AbortsWithMessage(t, cur, "heartbeat too frequent: wait at least 10 seconds", func() {
testing.SetRealm(testing.NewUserRealm(who))
Heartbeat(cross(cur), id, "")
})
urequire.AbortsContains(t, cur, "note contains an unsupported character", func() {
testing.SetRealm(testing.NewUserRealm(who))
testing.SkipHeights(3)
Heartbeat(cross(cur), id, "<b>")
})
// Steady heartbeats extend the session.
start := n.SessionStart
testing.SkipHeights(60) // 5 minutes
who = alice
testing.SetRealm(testing.NewUserRealm(who))
Heartbeat(cross(cur), id, "")
uassert.True(t, start.Equal(n.SessionStart), "session continues")
uassert.Equal(t, 2, n.HeartbeatCount)
// Silence longer than the online window: offline, and a new session.
testing.SkipHeights(12 * 31) // 31 minutes
uassert.False(t, isOnlineAt(n, time.Now()))
who = alice
testing.SetRealm(testing.NewUserRealm(who))
Heartbeat(cross(cur), id, "")
uassert.True(t, n.SessionStart.After(start), "session restarted")
uassert.True(t, isOnlineAt(n, time.Now()))
}
func TestAvailabilityModes(cur realm, t *testing.T) {
reset()
who = alice
testing.SetRealm(testing.NewUserRealm(who))
truck := RegisterNode(cross(cur), "Truck", KindVehicle, "AI4", "US-NY", PowerPowershare, 20)
gpu := RegisterNode(cross(cur), "Desk GPU", KindHomeGPU, "RTX 4090", "US-NY", PowerGrid, 40)
SetAvailability(cross(cur), truck, ModeDriving)
uassert.Equal(t, ModeDriving, mustGetNode(truck).Mode)
SetAvailability(cross(cur), truck, ModeAvailable)
uassert.Equal(t, ModeAvailable, mustGetNode(truck).Mode)
urequire.AbortsWithMessage(t, cur, "only vehicle nodes can be set to driving", func() {
testing.SetRealm(testing.NewUserRealm(who))
SetAvailability(cross(cur), gpu, ModeDriving)
})
urequire.AbortsWithMessage(t, cur, "mode must be one of: available, driving, paused", func() {
testing.SetRealm(testing.NewUserRealm(who))
SetAvailability(cross(cur), gpu, "sleeping")
})
}
func TestRecordJob(cur realm, t *testing.T) {
reset()
id := registerGPU(cur, alice, "Alice box", 45) // $0.45/h
who = alice
testing.SetRealm(testing.NewUserRealm(who))
urequire.AbortsWithMessage(t, cur, "node must be available (parked & plugged in) to take jobs", func() {
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), id, "inference", 60)
})
SetAvailability(cross(cur), id, ModeAvailable)
urequire.AbortsWithMessage(t, cur, "node is offline: send a heartbeat first", func() {
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), id, "inference", 60)
})
Heartbeat(cross(cur), id, "")
urequire.AbortsWithMessage(t, cur, "minutes must be between 1 and 1440", func() {
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), id, "inference", 0)
})
urequire.AbortsWithMessage(t, cur, "minutes must be between 1 and 1440", func() {
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), id, "inference", 1441)
})
jid := RecordJob(cross(cur), id, "llama-3.3-70b inference", 200) // 200 min at 45c/h = 150c
uassert.Equal(t, 1, jid)
j := jobs.Get(padID(jid)).(*Job)
uassert.Equal(t, int64(150), j.GrossCents)
uassert.Equal(t, int64(21), j.PoolCents) // 14% of 150
uassert.Equal(t, int64(129), j.OperatorCents)
n := mustGetNode(id)
uassert.Equal(t, 1, n.JobCount)
uassert.Equal(t, int64(200), n.JobMinutes)
uassert.Equal(t, int64(129), n.EarnedCents)
uassert.Equal(t, int64(150), totalGrossCents)
uassert.Equal(t, int64(21), poolCents)
// Driving vehicles can't take jobs.
who = alice
testing.SetRealm(testing.NewUserRealm(who))
truck := RegisterNode(cross(cur), "Truck", KindVehicle, "AI4", "US-NY", PowerPowershare, 20)
Heartbeat(cross(cur), truck, "")
SetAvailability(cross(cur), truck, ModeDriving)
urequire.AbortsWithMessage(t, cur, "node must be available (parked & plugged in) to take jobs", func() {
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), truck, "inference", 30)
})
}
func TestLeaderboardOrder(cur realm, t *testing.T) {
reset()
a := registerGPU(cur, alice, "Small", 10)
b := registerGPU(cur, bob, "Big", 100)
c := registerGPU(cur, carol, "Idle", 50)
bringOnline(cur, alice, a)
bringOnline(cur, bob, b)
who = alice
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), a, "batch", 600) // 100c gross
who = bob
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), b, "batch", 600) // 1000c gross
var order []int
leaderboard.Iterate("", "", func(_ string, v any) bool {
order = append(order, v.(int))
return false
})
urequire.Equal(t, 3, len(order), "one leaderboard entry per node")
uassert.Equal(t, b, order[0])
uassert.Equal(t, a, order[1])
uassert.Equal(t, c, order[2])
uassert.Equal(t, 1, rankOf(mustGetNode(b)))
uassert.Equal(t, 3, rankOf(mustGetNode(c)))
// Small overtakes Big with more work; still one entry each.
who = alice
testing.SetRealm(testing.NewUserRealm(who))
for i := 0; i < 12; i++ {
RecordJob(cross(cur), a, "batch", 1440)
}
uassert.Equal(t, 3, leaderboard.Size())
uassert.Equal(t, 1, rankOf(mustGetNode(a)))
}
func TestDistributeBonus(cur realm, t *testing.T) {
reset()
a := registerGPU(cur, alice, "Small", 10)
b := registerGPU(cur, bob, "Big", 1000)
c := registerGPU(cur, carol, "Offline", 50)
bringOnline(cur, alice, a)
bringOnline(cur, bob, b)
who = carol
testing.SetRealm(testing.NewUserRealm(who))
SetAvailability(cross(cur), c, ModeAvailable) // available but never heartbeated
who = carol
testing.SetRealm(testing.NewUserRealm(who))
urequire.AbortsWithMessage(t, cur, "the fairness pool is empty", func() {
testing.SetRealm(testing.NewUserRealm(who))
DistributeBonus(cross(cur))
})
who = bob
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), b, "training", 60) // 1000c gross, 140c to the pool
uassert.Equal(t, int64(140), poolCents)
who = carol
testing.SetRealm(testing.NewUserRealm(who)) // anyone can crank it
shared := DistributeBonus(cross(cur))
uassert.Equal(t, 2, shared, "only online + available nodes share")
uassert.Equal(t, int64(70), mustGetNode(a).BonusCents, "small node gets an equal share")
uassert.Equal(t, int64(70), mustGetNode(b).BonusCents)
uassert.Equal(t, int64(0), mustGetNode(c).BonusCents)
uassert.Equal(t, int64(0), poolCents)
uassert.Equal(t, int64(140), poolPaidCents)
uassert.Equal(t, 1, bonusRounds)
// Rate limited to once per hour.
who = bob
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), b, "training", 1) // 16c gross, 2c pool
urequire.AbortsWithMessage(t, cur, "the bonus can be distributed at most once per hour", func() {
testing.SetRealm(testing.NewUserRealm(who))
DistributeBonus(cross(cur))
})
// After an hour with everyone offline, nobody is eligible.
testing.SkipHeights(12 * 61)
urequire.AbortsWithMessage(t, cur, "no node is online and available to share the pool", func() {
testing.SetRealm(testing.NewUserRealm(who))
DistributeBonus(cross(cur))
})
// A remainder smaller than one cent per node stays in the pool.
bringOnline(cur, alice, a)
bringOnline(cur, bob, b)
who = carol
testing.SetRealm(testing.NewUserRealm(who))
Heartbeat(cross(cur), c, "")
poolCents = 2
urequire.AbortsWithMessage(t, cur, "the pool is too small to split", func() {
testing.SetRealm(testing.NewUserRealm(who))
DistributeBonus(cross(cur))
})
}
func TestRemoveNode(cur realm, t *testing.T) {
reset()
id := registerGPU(cur, alice, "Alice box", 60)
bringOnline(cur, alice, id)
who = alice
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), id, "render", 60)
RemoveNode(cross(cur), id)
uassert.Equal(t, 0, NodeCount())
uassert.Equal(t, 0, leaderboard.Size())
uassert.Equal(t, 0, operatorNodeCount(alice))
uassert.Equal(t, 1, jobs.Size(), "job history is kept")
uassert.Equal(t, "", NodeSummary(id))
}
func TestAdmin(cur realm, t *testing.T) {
reset()
id := registerGPU(cur, alice, "Spam node", 60)
who = alice
testing.SetRealm(testing.NewUserRealm(who))
urequire.AbortsWithMessage(t, cur, "only the admin can do this", func() {
testing.SetRealm(testing.NewUserRealm(who))
SetPaused(cross(cur), true)
})
urequire.AbortsWithMessage(t, cur, "only the admin can do this", func() {
testing.SetRealm(testing.NewUserRealm(who))
AdminRemoveNode(cross(cur), id)
})
urequire.AbortsWithMessage(t, cur, "only the admin can do this", func() {
testing.SetRealm(testing.NewUserRealm(who))
TransferAdmin(cross(cur), alice)
})
urequire.AbortsWithMessage(t, cur, "only the admin can do this", func() {
testing.SetRealm(testing.NewUserRealm(who))
SetOnlineWindowMinutes(cross(cur), 60)
})
who = boss
testing.SetRealm(testing.NewUserRealm(who))
SetPaused(cross(cur), true)
who = bob
testing.SetRealm(testing.NewUserRealm(who))
urequire.AbortsWithMessage(t, cur, "registrations are paused by the realm admin", func() {
testing.SetRealm(testing.NewUserRealm(who))
RegisterNode(cross(cur), "Late", KindCPU, "Xeon", "US", PowerGrid, 5)
})
who = boss
testing.SetRealm(testing.NewUserRealm(who))
SetPaused(cross(cur), false)
AdminRemoveNode(cross(cur), id)
uassert.Equal(t, 0, NodeCount())
urequire.AbortsWithMessage(t, cur, "online window must be between 5 and 10080 minutes", func() {
testing.SetRealm(testing.NewUserRealm(who))
SetOnlineWindowMinutes(cross(cur), 1)
})
SetOnlineWindowMinutes(cross(cur), 120)
uassert.True(t, onlineWindow == 2*time.Hour)
TransferAdmin(cross(cur), carol)
uassert.Equal(t, carol, Admin())
urequire.AbortsWithMessage(t, cur, "only the admin can do this", func() {
testing.SetRealm(testing.NewUserRealm(who))
SetPaused(cross(cur), true)
})
}
func TestStats(cur realm, t *testing.T) {
reset()
a := registerGPU(cur, alice, "A box", 60)
registerGPU(cur, bob, "B box", 60)
bringOnline(cur, alice, a)
who = alice
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), a, "render", 120)
total, online, gross, pool := Stats()
uassert.Equal(t, 2, total)
uassert.Equal(t, 1, online)
uassert.Equal(t, int64(120), gross)
uassert.Equal(t, int64(16), pool)
uassert.True(t, strings.Contains(NodeSummary(a), "A box | home-gpu"))
}
render.gno
package idlewatt
import (
"strconv"
"strings"
"time"
"gno.land/p/moul/txlink/v0"
)
const pageSize = 10
// Render serves the gnoweb dashboard.
//
// "" network summary, live node cards, leaderboard, recent jobs
// "nodes?page=N" every node, paginated
// "node/<id>" one node, its jobs and operator actions
// "operator/<g1addr>" one operator's nodes
// "leaderboard" full ranking
// "jobs?page=N" job history
// "about" what this is, and what it is not
func Render(path string) string {
route, query := path, ""
if i := strings.Index(path, "?"); i >= 0 {
route, query = path[:i], path[i+1:]
}
now := time.Now()
switch {
case route == "":
return renderHome(now)
case route == "nodes":
return renderNodes(now, pageParam(query))
case strings.HasPrefix(route, "node/"):
id, err := strconv.Atoi(strings.TrimPrefix(route, "node/"))
if err != nil {
return notFound()
}
return renderNode(now, id)
case strings.HasPrefix(route, "operator/"):
return renderOperator(now, strings.TrimPrefix(route, "operator/"))
case route == "leaderboard":
return renderLeaderboard(now, 50)
case route == "jobs":
return renderJobs(pageParam(query))
case route == "about":
return renderAbout()
}
return notFound()
}
// ---------------------------------------------------------------------------
// pages
func renderHome(now time.Time) string {
var b strings.Builder
b.WriteString("# <gno-icon name=\"lightning\" /> IdleWatt\n\n")
b.WriteString("*Idle compute, put to work.* An on-chain registry and dashboard for home GPU boxes, CPU nodes and, someday, parked vehicles that want to rent spare capacity on decentralized compute networks like Akash.\n\n")
b.WriteString(navBar())
b.WriteString(disclaimer())
// Network summary cards.
online, available, driving := 0, 0, 0
nodes.Iterate("", "", func(_ string, v any) bool {
n := v.(*Node)
if isOnlineAt(n, now) {
online++
if n.Mode == ModeAvailable {
available++
}
}
if n.Mode == ModeDriving {
driving++
}
return false
})
b.WriteString("## Network\n\n")
b.WriteString("<gno-columns>\n")
b.WriteString(statCard("server", "Nodes", strconv.Itoa(nodes.Size()), strconv.Itoa(driving)+" out driving"))
b.WriteString("<gno-columns-sep>\n")
b.WriteString(statCard("signal", "Online now", strconv.Itoa(online), strconv.Itoa(available)+" ready for work"))
b.WriteString("<gno-columns-sep>\n")
b.WriteString(statCard("coins", "Simulated earnings", fmtUSD(totalGrossCents), strconv.Itoa(jobs.Size())+" jobs recorded"))
b.WriteString("<gno-columns-sep>\n")
b.WriteString(statCard("trophy", "Fairness pool", fmtUSD(poolCents), fmtUSD(poolPaidCents)+" shared so far"))
b.WriteString("</gno-columns>\n\n")
// Node cards, highest earners first.
b.WriteString("## Nodes\n\n")
if nodes.Size() == 0 {
b.WriteString("No nodes yet. Be the first to register one below.\n\n")
} else {
var cards []string
leaderboard.IterateByOffset(0, 6, func(_ string, v any) bool {
nv := nodes.Get(padID(v.(int)))
if nv != nil {
cards = append(cards, nodeCard(nv.(*Node), now))
}
return false
})
b.WriteString(cardGrid(cards, 3))
if nodes.Size() > 6 {
b.WriteString("[See all " + strconv.Itoa(nodes.Size()) + " nodes](" + link("nodes") + ")\n\n")
}
}
b.WriteString("## <gno-icon name=\"trophy\" /> Leaderboard\n\n")
b.WriteString(leaderboardTable(now, 5))
b.WriteString("[Full leaderboard](" + link("leaderboard") + ")\n\n")
b.WriteString("## Recent jobs\n\n")
b.WriteString(jobsTable(0, 5, -1))
b.WriteString("[All jobs](" + link("jobs") + ")\n\n")
b.WriteString(bonusSection(now))
b.WriteString(registerForm())
return b.String()
}
func renderNodes(now time.Time, page int) string {
var b strings.Builder
b.WriteString("# All nodes\n\n")
b.WriteString(navBar())
total := nodes.Size()
if total == 0 {
b.WriteString("No nodes yet.\n")
return b.String()
}
b.WriteString("| # | Node | Type | Region | Power | Rate | Status | Earned |\n")
b.WriteString("|---|---|---|---|---|---|---|---|\n")
nodes.IterateByOffset((page-1)*pageSize, pageSize, func(_ string, v any) bool {
n := v.(*Node)
b.WriteString("| " + strconv.Itoa(n.ID) + " | [" + n.Name + "](" + link("node/"+strconv.Itoa(n.ID)) + ") | " +
kindLabel(n.Kind) + " | " + n.Region + " | " + powerLabel(n.Power) + " | " + fmtUSD(n.RateCents) + "/h | " +
statusOf(n, now) + " | " + fmtUSD(n.TotalCents()) + " |\n")
return false
})
b.WriteString("\n" + pager("nodes", page, total))
return b.String()
}
func renderNode(now time.Time, id int) string {
v := nodes.Get(padID(id))
if v == nil {
return notFound()
}
n := v.(*Node)
var b strings.Builder
b.WriteString("# " + kindIcon(n.Kind) + " " + n.Name + "\n\n")
b.WriteString(navBar())
b.WriteString("<gno-columns>\n<gno-frame>\n")
b.WriteString("### Status\n\n**" + statusOf(n, now) + "**\n\n")
if n.LastHeartbeat.IsZero() {
b.WriteString("No heartbeat yet.\n\n")
} else {
b.WriteString("Last heartbeat " + ago(now.Sub(n.LastHeartbeat)) + " (" + strconv.Itoa(n.HeartbeatCount) + " total)\n\n")
if isOnlineAt(n, now) && n.LastHeartbeat.Sub(n.SessionStart) >= time.Minute {
b.WriteString("Up for " + fmtDuration(n.LastHeartbeat.Sub(n.SessionStart)) + "\n\n")
}
if n.LastNote != "" {
b.WriteString("Note: *" + n.LastNote + "*\n\n")
}
}
b.WriteString("</gno-frame>\n<gno-columns-sep>\n<gno-frame>\n")
b.WriteString("### Specs\n\n")
b.WriteString("- Type: " + kindLabel(n.Kind) + "\n")
b.WriteString("- Hardware: " + n.Hardware + "\n")
b.WriteString("- Region: " + n.Region + "\n")
b.WriteString("- Power: " + powerLabel(n.Power) + "\n")
b.WriteString("- Rate: **" + fmtUSD(n.RateCents) + "/hour**\n\n")
b.WriteString("</gno-frame>\n<gno-columns-sep>\n<gno-frame>\n")
b.WriteString("### Earnings (simulated)\n\n")
b.WriteString("- Jobs: " + strconv.Itoa(n.JobCount) + " (" + fmtDuration(time.Duration(n.JobMinutes)*time.Minute) + " of compute)\n")
b.WriteString("- From jobs: " + fmtUSD(n.EarnedCents) + "\n")
b.WriteString("- Fairness bonus: " + fmtUSD(n.BonusCents) + "\n")
b.WriteString("- **Total: " + fmtUSD(n.TotalCents()) + "**\n")
b.WriteString("- Rank: #" + strconv.Itoa(rankOf(n)) + " of " + strconv.Itoa(nodes.Size()) + "\n\n")
b.WriteString("</gno-frame>\n</gno-columns>\n\n")
b.WriteString("Operator: [" + shortAddr(n.Operator) + "](" + link("operator/"+n.Operator.String()) + ") · registered " + n.RegisteredAt.UTC().Format("Jan 2, 2006") + "\n\n")
b.WriteString("## Operator actions\n\n")
b.WriteString("Only this node's operator (" + shortAddr(n.Operator) + ") can sign these. Each button opens a prefilled transaction form.\n\n")
sid := strconv.Itoa(n.ID)
b.WriteString("<gno-button href=\"" + txlink.NewLink("Heartbeat").AddArgs("id", sid, "note", "").URL() + "\" label=\"Send heartbeat\" />\n")
b.WriteString("<gno-button href=\"" + txlink.NewLink("SetAvailability").AddArgs("id", sid, "mode", ModeAvailable).URL() + "\" label=\"Parked and plugged in\" variant=\"success\" />\n")
if n.Kind == KindVehicle {
b.WriteString("<gno-button href=\"" + txlink.NewLink("SetAvailability").AddArgs("id", sid, "mode", ModeDriving).URL() + "\" label=\"Driving\" variant=\"warning\" />\n")
}
b.WriteString("<gno-button href=\"" + txlink.NewLink("SetAvailability").AddArgs("id", sid, "mode", ModePaused).URL() + "\" label=\"Pause\" variant=\"outline\" />\n")
b.WriteString("<gno-button href=\"" + txlink.NewLink("RecordJob").AddArgs("id", sid, "workload", "llama-3.3-70b inference", "minutes", "60").URL() + "\" label=\"Record a simulated job\" variant=\"info\" />\n")
b.WriteString("<gno-button href=\"" + txlink.NewLink("SetRate").AddArgs("id", sid, "rateCents", strconv.FormatInt(n.RateCents, 10)).URL() + "\" label=\"Change rate\" variant=\"outline\" />\n\n")
b.WriteString("## Job history\n\n")
b.WriteString(jobsTable(0, 20, n.ID))
return b.String()
}
func renderOperator(now time.Time, addr string) string {
var b strings.Builder
b.WriteString("# Operator " + safeAddrText(addr) + "\n\n")
b.WriteString(navBar())
var cards []string
prefix := addr + "/"
byOperator.Iterate(prefix, prefix+"~", func(_ string, v any) bool {
nv := nodes.Get(padID(v.(int)))
if nv != nil {
cards = append(cards, nodeCard(nv.(*Node), now))
}
return false
})
if len(cards) == 0 {
b.WriteString("This address has no nodes.\n")
return b.String()
}
b.WriteString(cardGrid(cards, 3))
return b.String()
}
func renderLeaderboard(now time.Time, limit int) string {
var b strings.Builder
b.WriteString("# <gno-icon name=\"trophy\" /> Leaderboard\n\n")
b.WriteString(navBar())
b.WriteString("Ranked by simulated job earnings plus fairness-pool bonus.\n\n")
b.WriteString(leaderboardTable(now, limit))
return b.String()
}
func renderJobs(page int) string {
var b strings.Builder
b.WriteString("# Job history\n\n")
b.WriteString(navBar())
b.WriteString("> [!NOTE] Simulated\n> Jobs are self-reported by node operators for demo purposes. Earnings are computed by the realm from each node's rate and the job length; no money moves.\n\n")
b.WriteString(jobsTable((page-1)*pageSize*2, pageSize*2, -1))
b.WriteString(pager("jobs", page, (jobs.Size()+1)/2))
return b.String()
}
func renderAbout() string {
var b strings.Builder
b.WriteString("# About IdleWatt\n\n")
b.WriteString(navBar())
b.WriteString("A home with a GPU box, a rooftop of solar, or a truck parked in the driveway all have compute and energy sitting idle most of the day. IdleWatt is a public registry where those nodes announce themselves, prove they are alive with signed heartbeats, flip between *parked & plugged in* and *driving*, and log the jobs they complete, so anyone can see what a neighbourhood-scale compute network would look like.\n\n")
b.WriteString("### How it works\n\n")
b.WriteString("1. **Register** a node with `RegisterNode`: name, type (home-gpu, vehicle, cpu), hardware, region, power source and an hourly rate in US cents.\n")
b.WriteString("2. **Heartbeat** with `Heartbeat`. Every heartbeat is a transaction signed by the operator's key. A node is online for " + fmtDuration(onlineWindow) + " after its last heartbeat.\n")
b.WriteString("3. **Toggle availability** with `SetAvailability`: available, driving (vehicles only) or paused.\n")
b.WriteString("4. **Record jobs** with `RecordJob`. The realm computes earnings from the rate and minutes; operators cannot type in an amount.\n")
b.WriteString("5. **Fairness pool.** 14% of every job goes into a pool that `DistributeBonus` (anyone, at most hourly) splits *equally* across every node that is online and available, big or small, inspired by AtomOne's Nakamoto Bonus.\n\n")
b.WriteString(disclaimer())
b.WriteString("Admin: " + shortAddr(admin) + " · registrations " + boolWord(!paused, "open", "paused") + "\n")
return b.String()
}
// ---------------------------------------------------------------------------
// components
func navBar() string {
return "[Home](" + link("") + ") · [Nodes](" + link("nodes") + ") · [Leaderboard](" + link("leaderboard") + ") · [Jobs](" + link("jobs") + ") · [About](" + link("about") + ")\n\n"
}
func disclaimer() string {
return "> [!WARNING] Simulated data\n> Every node, heartbeat and job here is self-reported by its operator or simulated for this demo. IdleWatt has **no Tesla or Akash integration** and no hardware attestation yet, and the dollar figures are simulated, not payments.\n\n"
}
func statCard(icon, title, value, sub string) string {
return "<gno-frame>\n<gno-icon name=\"" + icon + "\" /> " + title + "\n\n**" + value + "**\n\n" + sub + "\n</gno-frame>\n"
}
func nodeCard(n *Node, now time.Time) string {
var b strings.Builder
b.WriteString("<gno-frame>\n")
b.WriteString("#### " + kindIcon(n.Kind) + " [" + n.Name + "](" + link("node/"+strconv.Itoa(n.ID)) + ")\n\n")
b.WriteString("**" + statusOf(n, now) + "**\n\n")
b.WriteString(n.Hardware + "\n\n")
b.WriteString(n.Region + " · " + powerLabel(n.Power) + "\n\n")
b.WriteString(fmtUSD(n.RateCents) + "/h · " + plural(n.JobCount, "job") + " · **" + fmtUSD(n.TotalCents()) + "** earned\n")
b.WriteString("</gno-frame>\n")
return b.String()
}
// cardGrid lays cards out in rows of perRow columns.
func cardGrid(cards []string, perRow int) string {
var b strings.Builder
for i := 0; i < len(cards); i += perRow {
b.WriteString("<gno-columns>\n")
for j := i; j < i+perRow; j++ {
if j > i {
b.WriteString("<gno-columns-sep>\n")
}
if j < len(cards) {
b.WriteString(cards[j])
} // else: an empty column keeps a short last row aligned
}
b.WriteString("</gno-columns>\n\n")
}
return b.String()
}
func leaderboardTable(now time.Time, limit int) string {
if leaderboard.Size() == 0 {
return "Nobody on the board yet.\n\n"
}
var b strings.Builder
b.WriteString("| Rank | Node | Type | Jobs | From jobs | Bonus | Total |\n")
b.WriteString("|---|---|---|---|---|---|---|\n")
rank := 0
leaderboard.IterateByOffset(0, limit, func(_ string, v any) bool {
nv := nodes.Get(padID(v.(int)))
if nv == nil {
return false
}
n := nv.(*Node)
rank++
b.WriteString("| " + medal(rank) + " | [" + n.Name + "](" + link("node/"+strconv.Itoa(n.ID)) + ") | " + kindLabel(n.Kind) + " | " +
strconv.Itoa(n.JobCount) + " | " + fmtUSD(n.EarnedCents) + " | " + fmtUSD(n.BonusCents) + " | **" + fmtUSD(n.TotalCents()) + "** |\n")
return false
})
b.WriteString("\n")
return b.String()
}
// jobsTable lists jobs newest first. nodeID < 0 means all nodes.
func jobsTable(offset, limit, nodeID int) string {
var rows []*Job
if nodeID < 0 {
jobs.ReverseIterateByOffset(offset, limit, func(_ string, v any) bool {
rows = append(rows, v.(*Job))
return false
})
} else {
prefix := padID(nodeID) + "/"
nodeJobs.ReverseIterate(prefix, prefix+"~", func(_ string, v any) bool {
jv := jobs.Get(padID(v.(int)))
if jv != nil {
rows = append(rows, jv.(*Job))
}
return len(rows) >= limit
})
}
if len(rows) == 0 {
return "No jobs yet.\n\n"
}
var b strings.Builder
if nodeID < 0 {
b.WriteString("| # | Node | Workload | Length | Earned | When (UTC) |\n|---|---|---|---|---|---|\n")
} else {
b.WriteString("| # | Workload | Length | Rate | Earned | To pool | When (UTC) |\n|---|---|---|---|---|---|---|\n")
}
for _, j := range rows {
length := fmtDuration(time.Duration(j.Minutes) * time.Minute)
when := j.CompletedAt.UTC().Format("Jan 2 15:04")
if nodeID < 0 {
b.WriteString("| " + strconv.Itoa(j.ID) + " | [" + j.NodeName + "](" + link("node/"+strconv.Itoa(j.NodeID)) + ") | " + j.Workload + " | " +
length + " | " + fmtUSD(j.GrossCents) + " | " + when + " |\n")
} else {
b.WriteString("| " + strconv.Itoa(j.ID) + " | " + j.Workload + " | " + length + " | " + fmtUSD(j.RateCents) + "/h | " +
fmtUSD(j.GrossCents) + " | " + fmtUSD(j.PoolCents) + " | " + when + " |\n")
}
}
b.WriteString("\n")
return b.String()
}
func bonusSection(now time.Time) string {
var b strings.Builder
b.WriteString("## <gno-icon name=\"coins\" /> Small-node fairness pool\n\n")
b.WriteString("14% of every job feeds this pool. Anyone can trigger a split (at most once an hour); it is shared **equally** by every node that is online and available at that moment, so a CPU box in a garage gets the same share as a datacenter-class GPU. Inspired by AtomOne's Nakamoto Bonus.\n\n")
eligible := 0
nodes.Iterate("", "", func(_ string, v any) bool {
n := v.(*Node)
if n.Mode == ModeAvailable && isOnlineAt(n, now) {
eligible++
}
return false
})
b.WriteString("- Pool now: **" + fmtUSD(poolCents) + "**, " + strconv.Itoa(eligible) + " nodes eligible")
if eligible > 0 && poolCents > 0 {
b.WriteString(" (" + fmtUSD(poolCents/int64(eligible)) + " each)")
}
b.WriteString("\n- Rounds so far: " + strconv.Itoa(bonusRounds) + ", " + fmtUSD(poolPaidCents) + " shared\n")
if !lastDistribution.IsZero() {
b.WriteString("- Last split: " + ago(now.Sub(lastDistribution)) + "\n")
}
b.WriteString("\n<gno-button href=\"" + txlink.NewLink("DistributeBonus").URL() + "\" label=\"Split the pool now\" variant=\"success\" />\n\n")
return b.String()
}
func registerForm() string {
if paused {
return "## Register a node\n\nRegistrations are paused right now.\n\n"
}
return "## <gno-icon name=\"plus\" /> Register a node\n\n" +
"Sign with any gno.land account (testnet). Your node starts *paused*; send a heartbeat and set it to available to take jobs.\n\n" +
"<gno-frame>\n" +
"<gno-form exec=\"RegisterNode\">\n" +
"<gno-input name=\"name\" placeholder=\"Node name, e.g. Garage RTX 4090\" />\n" +
"<gno-input name=\"kind\" type=\"radio\" value=\"home-gpu\" placeholder=\"Home GPU box\" checked=\"true\" />\n" +
"<gno-input name=\"kind\" type=\"radio\" value=\"vehicle\" placeholder=\"Vehicle\" />\n" +
"<gno-input name=\"kind\" type=\"radio\" value=\"cpu\" placeholder=\"CPU-only node\" />\n" +
"<gno-input name=\"hardware\" placeholder=\"Hardware, e.g. RTX 4090 24GB, Ryzen 9 7950X\" />\n" +
"<gno-input name=\"region\" placeholder=\"Region, e.g. US-NY Buffalo\" />\n" +
"<gno-input name=\"power\" type=\"radio\" value=\"grid\" placeholder=\"Grid\" checked=\"true\" />\n" +
"<gno-input name=\"power\" type=\"radio\" value=\"solar\" placeholder=\"Solar\" />\n" +
"<gno-input name=\"power\" type=\"radio\" value=\"powershare-backup\" placeholder=\"Powershare backup\" />\n" +
"<gno-input name=\"rateCents\" type=\"number\" placeholder=\"Rate in US cents per hour, e.g. 45\" />\n" +
"</gno-form>\n" +
"</gno-frame>\n\n"
}
func pager(route string, page, total int) string {
pages := (total + pageSize - 1) / pageSize
if pages <= 1 {
return ""
}
out := "Page " + strconv.Itoa(page) + " of " + strconv.Itoa(pages)
if page > 1 {
out += " · [Previous](" + link(route+"?page="+strconv.Itoa(page-1)) + ")"
}
if page < pages {
out += " · [Next](" + link(route+"?page="+strconv.Itoa(page+1)) + ")"
}
return out + "\n"
}
func notFound() string {
return "# Not found\n\n" + navBar()
}
// ---------------------------------------------------------------------------
// formatting helpers
func link(sub string) string {
if sub == "" {
return realmURL
}
return realmURL + ":" + sub
}
func pageParam(query string) int {
for _, kv := range strings.Split(query, "&") {
if strings.HasPrefix(kv, "page=") {
p, err := strconv.Atoi(strings.TrimPrefix(kv, "page="))
if err == nil && p >= 1 && p <= 100000 {
return p
}
}
}
return 1
}
func statusOf(n *Node, now time.Time) string {
if n.Mode == ModeDriving {
return "Driving"
}
if !isOnlineAt(n, now) {
return "Offline"
}
if n.Mode == ModePaused {
return "Online, paused"
}
if n.Kind == KindVehicle {
return "Parked & plugged in"
}
return "Online, available"
}
func rankOf(n *Node) int {
rank := 1
key := rankKey(n.TotalCents(), n.ID)
leaderboard.Iterate("", key, func(_ string, _ any) bool {
rank++
return false
})
return rank
}
func kindLabel(kind string) string {
switch kind {
case KindHomeGPU:
return "Home GPU"
case KindVehicle:
return "Vehicle"
case KindCPU:
return "CPU"
}
return kind
}
func kindIcon(kind string) string {
switch kind {
case KindVehicle:
return "<gno-icon name=\"battery-charging\" />"
case KindCPU:
return "<gno-icon name=\"server\" />"
}
return "<gno-icon name=\"lightning\" />"
}
func powerLabel(p string) string {
switch p {
case PowerGrid:
return "Grid power"
case PowerSolar:
return "Solar"
case PowerPowershare:
return "Powershare backup"
}
return p
}
func medal(rank int) string {
switch rank {
case 1:
return "🥇"
case 2:
return "🥈"
case 3:
return "🥉"
}
return strconv.Itoa(rank)
}
func boolWord(b bool, yes, no string) string {
if b {
return yes
}
return no
}
// fmtUSD renders cents as $1,234.56.
func fmtUSD(cents int64) string {
neg := cents < 0
if neg {
cents = -cents
}
whole := strconv.FormatInt(cents/100, 10)
frac := strconv.FormatInt(cents%100, 10)
if len(frac) < 2 {
frac = "0" + frac
}
for i := len(whole) - 3; i > 0; i -= 3 {
whole = whole[:i] + "," + whole[i:]
}
out := "$" + whole + "." + frac
if neg {
out = "-" + out
}
return out
}
func fmtDuration(d time.Duration) string {
if d < time.Minute {
return strconv.Itoa(int(d/time.Second)) + "s"
}
mins := int(d / time.Minute)
if mins < 60 {
return strconv.Itoa(mins) + "m"
}
h, m := mins/60, mins%60
if h < 48 {
if m == 0 {
return strconv.Itoa(h) + "h"
}
return strconv.Itoa(h) + "h " + strconv.Itoa(m) + "m"
}
return strconv.Itoa(h/24) + "d " + strconv.Itoa(h%24) + "h"
}
func ago(d time.Duration) string {
if d < 0 {
d = 0
}
return fmtDuration(d) + " ago"
}
func shortAddr(a address) string {
s := a.String()
if len(s) <= 14 {
return s
}
return s[:8] + "…" + s[len(s)-4:]
}
// safeAddrText echoes a user-supplied path segment only if it looks like an
// address, so the page never reflects arbitrary markdown.
func safeAddrText(s string) string {
if address(s).IsValid() {
return shortAddr(address(s))
}
return "(invalid address)"
}
func plural(n int, word string) string {
if n == 1 {
return "1 " + word
}
return strconv.Itoa(n) + " " + word + "s"
}
render_test.gno
package idlewatt
import (
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestFormatting(t *testing.T) {
uassert.Equal(t, "$0.00", fmtUSD(0))
uassert.Equal(t, "$0.05", fmtUSD(5))
uassert.Equal(t, "$1.50", fmtUSD(150))
uassert.Equal(t, "$1,234.56", fmtUSD(123456))
uassert.Equal(t, "$1,000,000.00", fmtUSD(100000000))
uassert.Equal(t, "-$2.00", fmtUSD(-200))
uassert.Equal(t, "000000042", padID(42))
uassert.True(t, rankKey(500, 1) < rankKey(100, 1), "higher totals sort first")
uassert.True(t, rankKey(100, 1) < rankKey(100, 2), "ties go to the older node")
uassert.Equal(t, 1, pageParam(""))
uassert.Equal(t, 3, pageParam("page=3"))
uassert.Equal(t, 1, pageParam("page=-1"))
uassert.Equal(t, 1, pageParam("page=abc"))
}
func TestRenderEmpty(cur realm, t *testing.T) {
reset()
out := Render("")
uassert.True(t, strings.Contains(out, "# <gno-icon name=\"lightning\" /> IdleWatt"))
uassert.True(t, strings.Contains(out, "no Tesla or Akash integration"), "disclaimer is always shown")
uassert.True(t, strings.Contains(out, "No nodes yet"))
uassert.True(t, strings.Contains(out, "<gno-form exec=\"RegisterNode\">"))
}
func TestRenderPages(cur realm, t *testing.T) {
reset()
who = alice
testing.SetRealm(testing.NewUserRealm(who))
truck := RegisterNode(cross(cur), "Tonawanda Cybertruck (simulated)", KindVehicle, "AI4 + AMD Ryzen", "US-NY Tonawanda", PowerPowershare, 30)
gpu := registerGPU(cur, bob, "Garage RTX 4090", 45)
bringOnline(cur, bob, gpu)
who = bob
testing.SetRealm(testing.NewUserRealm(who))
RecordJob(cross(cur), gpu, "llama-3.3-70b inference", 120)
who = alice
testing.SetRealm(testing.NewUserRealm(who))
SetAvailability(cross(cur), truck, ModeDriving)
home := Render("")
for _, want := range []string{
"Tonawanda Cybertruck (simulated)",
"Garage RTX 4090",
"<gno-columns>",
"<gno-frame>",
"Fairness pool",
"1 out driving",
"$0.90", // 120 min at 45c/h
"Driving",
"Online, available",
"Split the pool now",
"llama-3.3-70b inference",
} {
uassert.True(t, strings.Contains(home, want), "home page missing: "+want)
}
// Leaderboard puts the earner first.
uassert.True(t, strings.Index(home, "🥇 | [Garage RTX 4090]") > 0, "gpu should rank first")
page := Render("node/" + itoa(truck))
uassert.True(t, strings.Contains(page, "# <gno-icon name=\"battery-charging\" /> Tonawanda Cybertruck (simulated)"))
uassert.True(t, strings.Contains(page, "label=\"Driving\""), "vehicles get a driving button")
uassert.True(t, strings.Contains(page, "$help&func=Heartbeat"), "action links open prefilled tx forms")
uassert.True(t, strings.Contains(page, "No jobs yet"))
gpage := Render("node/" + itoa(gpu))
uassert.False(t, strings.Contains(gpage, "label=\"Driving\""), "no driving button for a GPU box")
uassert.True(t, strings.Contains(gpage, "Rank: #1 of 2"))
uassert.True(t, strings.Contains(Render("nodes"), "| 2 | [Garage RTX 4090]"))
uassert.True(t, strings.Contains(Render("leaderboard"), "Garage RTX 4090"))
uassert.True(t, strings.Contains(Render("jobs"), "Simulated"))
uassert.True(t, strings.Contains(Render("about"), "Nakamoto Bonus"))
uassert.True(t, strings.Contains(Render("operator/"+alice.String()), "Tonawanda Cybertruck"))
uassert.True(t, strings.Contains(Render("operator/[evil](x)"), "(invalid address)"))
uassert.True(t, strings.HasPrefix(Render("node/999"), "# Not found"))
uassert.True(t, strings.HasPrefix(Render("node/abc"), "# Not found"))
uassert.True(t, strings.HasPrefix(Render("nope"), "# Not found"))
}
func TestRenderPagination(cur realm, t *testing.T) {
reset()
ops := []address{alice, bob, carol}
for i := 0; i < 25; i++ {
registerGPU(cur, ops[i%3], "Node "+itoa(i+1), int64(10+i))
}
p1 := Render("nodes")
uassert.True(t, strings.Contains(p1, "Page 1 of 3"))
uassert.True(t, strings.Contains(p1, "[Next]"))
p3 := Render("nodes?page=3")
uassert.True(t, strings.Contains(p3, "| 25 | [Node 25]"))
uassert.False(t, strings.Contains(p3, "| 1 | [Node 1]"))
uassert.True(t, strings.Contains(Render(""), "See all 25 nodes"))
}
func itoa(i int) string {
s := ""
if i == 0 {
return "0"
}
for i > 0 {
s = string(rune('0'+i%10)) + s
i /= 10
}
return s
}
types.gno
package idlewatt
import "time"
// Node kinds.
const (
KindHomeGPU = "home-gpu"
KindVehicle = "vehicle"
KindCPU = "cpu"
)
// Power sources.
const (
PowerGrid = "grid"
PowerSolar = "solar"
PowerPowershare = "powershare-backup"
)
// Availability modes.
const (
ModeAvailable = "available" // parked & plugged in, ready for work
ModeDriving = "driving" // vehicle in use, not renting compute
ModePaused = "paused" // operator paused the node
)
// Node is one idle-compute node registered by an operator.
// All figures are self-reported by the operator; nothing here is verified
// by Akash, Tesla or any hardware attestation (yet).
type Node struct {
ID int
Operator address
Name string
Kind string
Hardware string
Region string
Power string
RateCents int64 // asking price, USD cents per hour
Mode string
RegisteredAt time.Time
LastHeartbeat time.Time // zero if never
SessionStart time.Time // start of the current unbroken heartbeat run
HeartbeatCount int
LastNote string
JobCount int
JobMinutes int64
EarnedCents int64 // operator share of simulated job earnings
BonusCents int64 // share of the small-node fairness pool
}
// TotalCents is what the leaderboard ranks on.
func (n *Node) TotalCents() int64 {
return n.EarnedCents + n.BonusCents
}
// Job is one simulated (self-reported) lease / job completion.
type Job struct {
ID int
NodeID int
NodeName string // snapshot, survives node removal
Workload string
Minutes int
RateCents int64
GrossCents int64 // rate x duration
PoolCents int64 // part sent to the fairness pool
OperatorCents int64
CompletedAt time.Time
}
validate.gno
package idlewatt
import "strconv"
// Input limits.
const (
minNameLen = 3
maxNameLen = 48
maxHardwareLen = 80
minRegionLen = 2
maxRegionLen = 40
maxWorkloadLen = 60
maxNoteLen = 60
maxRateCents = 100000 // $1,000/hour sanity cap
maxJobMinutes = 24 * 60
)
// isSafeChar is the character whitelist for every free-text field. It keeps
// operator-supplied strings from injecting markdown, HTML, gnoweb tags or
// table pipes into Render output, and keeps them single-line.
func isSafeChar(c rune) bool {
switch {
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':
return true
}
switch c {
case ' ', '-', '.', ',', '(', ')', '\'', '/', '+', ':', '@', '#', '%', '&', '=':
return true
}
return false
}
// checkText validates a free-text field and panics with a readable message.
func checkText(field, s string, minLen, maxLen int) {
if len(s) < minLen || len(s) > maxLen {
panic(field + " must be " + strconv.Itoa(minLen) + "-" + strconv.Itoa(maxLen) + " characters")
}
if s[0] == ' ' || s[len(s)-1] == ' ' {
panic(field + " must not start or end with a space")
}
for _, c := range s {
if !isSafeChar(c) {
panic(field + " contains an unsupported character: only letters, digits, spaces and - . , ( ) ' / + : @ # % & = are allowed")
}
}
}
func checkKind(kind string) {
switch kind {
case KindHomeGPU, KindVehicle, KindCPU:
return
}
panic("kind must be one of: home-gpu, vehicle, cpu")
}
func checkPower(power string) {
switch power {
case PowerGrid, PowerSolar, PowerPowershare:
return
}
panic("power must be one of: grid, solar, powershare-backup")
}
func checkRate(rate int64) {
if rate < 1 || rate > maxRateCents {
panic("rate must be between 1 and " + strconv.Itoa(maxRateCents) + " US cents per hour")
}
}
func checkMode(kind, mode string) {
switch mode {
case ModeAvailable, ModePaused:
return
case ModeDriving:
if kind != KindVehicle {
panic("only vehicle nodes can be set to driving")
}
return
}
panic("mode must be one of: available, driving, paused")
}