idlewatt.gno
12.75 Kb · 452 lines
1// Package idlewatt is an on-chain registry and dashboard for idle compute
2// nodes: home GPU boxes today, and someday parked vehicles, that want to rent
3// spare capacity on decentralized compute networks such as Akash.
4//
5// IMPORTANT: every node, heartbeat and job in this realm is self-reported or
6// simulated by its operator. There is no Tesla or Akash integration and no
7// hardware attestation; earnings are simulated USD figures, not payments.
8package idlewatt
9
10import (
11 "chain"
12 "strconv"
13 "strings"
14 "time"
15
16 "gno.land/p/nt/avl/v0"
17)
18
19// Tunables.
20const (
21 maxNodes = 1000
22 maxNodesPerOperator = 10
23 minHeartbeatInterval = 10 * time.Second
24 poolBps = 1400 // 14% of every job feeds the fairness pool (a nod to AtomOne's Nakamoto Bonus)
25 minBonusEpoch = time.Hour
26 minOnlineWindow = 5 * time.Minute
27 maxOnlineWindow = 7 * 24 * time.Hour
28)
29
30var (
31 admin address
32 paused bool // when true, new registrations are refused
33 onlineWindow = 30 * time.Minute
34
35 nextNodeID = 1
36 nextJobID = 1
37
38 nodes = avl.NewTree() // padID(nodeID) -> *Node
39 byOperator = avl.NewTree() // operator + "/" + padID -> nodeID
40 leaderboard = avl.NewTree() // rankKey(total, id) -> nodeID
41 jobs = avl.NewTree() // padID(jobID) -> *Job
42 nodeJobs = avl.NewTree() // padID(nodeID) + "/" + padID(jobID) -> jobID
43
44 totalGrossCents int64
45 poolCents int64 // undistributed fairness pool
46 poolPaidCents int64 // distributed so far
47 bonusRounds int
48 lastDistribution time.Time
49)
50
51// realmURL is this realm's gnoweb path, e.g. /r/<addr>/idlewatt.
52var realmURL string
53
54func init(cur realm) {
55 admin = cur.Previous().Address()
56 realmURL = strings.TrimPrefix(cur.PkgPath(), "gno.land")
57}
58
59// ---------------------------------------------------------------------------
60// Operator actions. Every one of them is a signed transaction, so the
61// operator address is authenticated by the chain itself.
62
63// RegisterNode adds a node owned by the caller and returns its ID.
64// kind: home-gpu | vehicle | cpu. power: grid | solar | powershare-backup.
65// rateCents: asking price in US cents per hour (e.g. 45 = $0.45/h).
66func RegisterNode(cur realm, name, kind, hardware, region, power string, rateCents int64) int {
67 caller := mustCaller(cur)
68 if paused {
69 panic("registrations are paused by the realm admin")
70 }
71 checkText("name", name, minNameLen, maxNameLen)
72 checkKind(kind)
73 checkText("hardware", hardware, minNameLen, maxHardwareLen)
74 checkText("region", region, minRegionLen, maxRegionLen)
75 checkPower(power)
76 checkRate(rateCents)
77 if nodes.Size() >= maxNodes {
78 panic("registry is full")
79 }
80 if operatorNodeCount(caller) >= maxNodesPerOperator {
81 panic("an operator can register at most " + strconv.Itoa(maxNodesPerOperator) + " nodes")
82 }
83
84 now := time.Now()
85 n := &Node{
86 ID: nextNodeID,
87 Operator: caller,
88 Name: name,
89 Kind: kind,
90 Hardware: hardware,
91 Region: region,
92 Power: power,
93 RateCents: rateCents,
94 Mode: ModePaused,
95 RegisteredAt: now,
96 }
97 nextNodeID++
98 nodes.Set(padID(n.ID), n)
99 byOperator.Set(caller.String()+"/"+padID(n.ID), n.ID)
100 leaderboard.Set(rankKey(0, n.ID), n.ID)
101
102 chain.Emit("NodeRegistered",
103 "id", strconv.Itoa(n.ID),
104 "operator", caller.String(),
105 "kind", kind,
106 "region", region,
107 "power", power,
108 "rateCents", strconv.FormatInt(rateCents, 10),
109 )
110 return n.ID
111}
112
113// UpdateNode changes a node's descriptive fields and rate. Only the operator.
114func UpdateNode(cur realm, id int, name, hardware, region, power string, rateCents int64) {
115 caller := mustCaller(cur)
116 n := mustOwnNode(id, caller)
117 checkText("name", name, minNameLen, maxNameLen)
118 checkText("hardware", hardware, minNameLen, maxHardwareLen)
119 checkText("region", region, minRegionLen, maxRegionLen)
120 checkPower(power)
121 checkRate(rateCents)
122
123 n.Name = name
124 n.Hardware = hardware
125 n.Region = region
126 n.Power = power
127 n.RateCents = rateCents
128 chain.Emit("NodeUpdated", "id", strconv.Itoa(id), "rateCents", strconv.FormatInt(rateCents, 10))
129}
130
131// SetRate changes only the hourly asking rate (US cents). Only the operator.
132func SetRate(cur realm, id int, rateCents int64) {
133 caller := mustCaller(cur)
134 n := mustOwnNode(id, caller)
135 checkRate(rateCents)
136 n.RateCents = rateCents
137 chain.Emit("NodeUpdated", "id", strconv.Itoa(id), "rateCents", strconv.FormatInt(rateCents, 10))
138}
139
140// SetAvailability switches a node between available (parked & plugged in),
141// driving (vehicles only) and paused. Only the operator.
142func SetAvailability(cur realm, id int, mode string) {
143 caller := mustCaller(cur)
144 n := mustOwnNode(id, caller)
145 checkMode(n.Kind, mode)
146 if n.Mode == mode {
147 return
148 }
149 prev := n.Mode
150 n.Mode = mode
151 chain.Emit("AvailabilityChanged", "id", strconv.Itoa(id), "from", prev, "to", mode)
152}
153
154// Heartbeat records a signed liveness ping for a node, with an optional
155// short status note (e.g. "SoC 82%, 41C"). Only the operator.
156func Heartbeat(cur realm, id int, note string) {
157 caller := mustCaller(cur)
158 n := mustOwnNode(id, caller)
159 if note != "" {
160 checkText("note", note, 1, maxNoteLen)
161 }
162 now := time.Now()
163 if !n.LastHeartbeat.IsZero() {
164 gap := now.Sub(n.LastHeartbeat)
165 if gap < minHeartbeatInterval {
166 panic("heartbeat too frequent: wait at least 10 seconds")
167 }
168 if gap > onlineWindow {
169 n.SessionStart = now // the previous run was broken
170 }
171 } else {
172 n.SessionStart = now
173 }
174 n.LastHeartbeat = now
175 n.HeartbeatCount++
176 n.LastNote = note
177 chain.Emit("Heartbeat", "id", strconv.Itoa(id), "count", strconv.Itoa(n.HeartbeatCount))
178}
179
180// RecordJob records a completed (simulated) job on a node, e.g. an AI
181// inference lease. Earnings are computed by the realm from the node's rate
182// and the duration, so operators cannot claim arbitrary amounts. The node
183// must be available and online. 14% of the gross goes to the fairness pool.
184func RecordJob(cur realm, id int, workload string, minutes int) int {
185 caller := mustCaller(cur)
186 n := mustOwnNode(id, caller)
187 checkText("workload", workload, minNameLen, maxWorkloadLen)
188 if minutes < 1 || minutes > maxJobMinutes {
189 panic("minutes must be between 1 and 1440")
190 }
191 if n.Mode != ModeAvailable {
192 panic("node must be available (parked & plugged in) to take jobs")
193 }
194 now := time.Now()
195 if !isOnlineAt(n, now) {
196 panic("node is offline: send a heartbeat first")
197 }
198
199 gross := n.RateCents * int64(minutes) / 60
200 pool := gross * poolBps / 10000
201 op := gross - pool
202
203 j := &Job{
204 ID: nextJobID,
205 NodeID: n.ID,
206 NodeName: n.Name,
207 Workload: workload,
208 Minutes: minutes,
209 RateCents: n.RateCents,
210 GrossCents: gross,
211 PoolCents: pool,
212 OperatorCents: op,
213 CompletedAt: now,
214 }
215 nextJobID++
216 jobs.Set(padID(j.ID), j)
217 nodeJobs.Set(padID(n.ID)+"/"+padID(j.ID), j.ID)
218
219 oldTotal := n.TotalCents()
220 n.JobCount++
221 n.JobMinutes += int64(minutes)
222 n.EarnedCents += op
223 reRank(n, oldTotal)
224
225 totalGrossCents += gross
226 poolCents += pool
227
228 chain.Emit("JobRecorded",
229 "job", strconv.Itoa(j.ID),
230 "node", strconv.Itoa(n.ID),
231 "minutes", strconv.Itoa(minutes),
232 "grossCents", strconv.FormatInt(gross, 10),
233 "poolCents", strconv.FormatInt(pool, 10),
234 "simulated", "true",
235 )
236 return j.ID
237}
238
239// RemoveNode deletes the caller's node. Its job history stays on the record.
240func RemoveNode(cur realm, id int) {
241 caller := mustCaller(cur)
242 n := mustOwnNode(id, caller)
243 removeNode(n)
244 chain.Emit("NodeRemoved", "id", strconv.Itoa(id), "by", "operator")
245}
246
247// DistributeBonus splits the fairness pool equally across every node that is
248// online and available right now, regardless of size or earnings, like
249// AtomOne's Nakamoto Bonus splits its pool equally across validators.
250// Anyone may call it, at most once per hour. Returns how many nodes shared.
251func DistributeBonus(cur realm) int {
252 mustCaller(cur)
253 now := time.Now()
254 if !lastDistribution.IsZero() && now.Sub(lastDistribution) < minBonusEpoch {
255 panic("the bonus can be distributed at most once per hour")
256 }
257 if poolCents <= 0 {
258 panic("the fairness pool is empty")
259 }
260 var eligible []*Node
261 nodes.Iterate("", "", func(_ string, v any) bool {
262 n := v.(*Node)
263 if n.Mode == ModeAvailable && isOnlineAt(n, now) {
264 eligible = append(eligible, n)
265 }
266 return false
267 })
268 if len(eligible) == 0 {
269 panic("no node is online and available to share the pool")
270 }
271 share := poolCents / int64(len(eligible))
272 if share == 0 {
273 panic("the pool is too small to split")
274 }
275 for _, n := range eligible {
276 old := n.TotalCents()
277 n.BonusCents += share
278 reRank(n, old)
279 }
280 paid := share * int64(len(eligible))
281 poolCents -= paid // the remainder stays for next round
282 poolPaidCents += paid
283 bonusRounds++
284 lastDistribution = now
285 chain.Emit("BonusDistributed",
286 "round", strconv.Itoa(bonusRounds),
287 "nodes", strconv.Itoa(len(eligible)),
288 "shareCents", strconv.FormatInt(share, 10),
289 )
290 return len(eligible)
291}
292
293// ---------------------------------------------------------------------------
294// Admin actions (moderation of a public demo registry).
295
296// SetPaused stops or resumes new registrations.
297func SetPaused(cur realm, p bool) {
298 mustAdmin(cur)
299 paused = p
300 chain.Emit("PausedChanged", "paused", strconv.FormatBool(p))
301}
302
303// SetOnlineWindowMinutes sets how long after its last heartbeat a node still
304// counts as online (5 minutes to 7 days).
305func SetOnlineWindowMinutes(cur realm, minutes int) {
306 mustAdmin(cur)
307 w := time.Duration(minutes) * time.Minute
308 if w < minOnlineWindow || w > maxOnlineWindow {
309 panic("online window must be between 5 and 10080 minutes")
310 }
311 onlineWindow = w
312 chain.Emit("OnlineWindowChanged", "minutes", strconv.Itoa(minutes))
313}
314
315// AdminRemoveNode removes a spam or abusive node.
316func AdminRemoveNode(cur realm, id int) {
317 mustAdmin(cur)
318 n := mustGetNode(id)
319 removeNode(n)
320 chain.Emit("NodeRemoved", "id", strconv.Itoa(id), "by", "admin")
321}
322
323// TransferAdmin hands the admin role to another address.
324func TransferAdmin(cur realm, newAdmin address) {
325 mustAdmin(cur)
326 if !newAdmin.IsValid() {
327 panic("invalid address")
328 }
329 old := admin
330 admin = newAdmin
331 chain.Emit("AdminChanged", "from", old.String(), "to", newAdmin.String())
332}
333
334// ---------------------------------------------------------------------------
335// Read-only helpers (safe to query with vm/qeval).
336
337// Admin returns the admin address.
338func Admin() address { return admin }
339
340// NodeCount returns the number of registered nodes.
341func NodeCount() int { return nodes.Size() }
342
343// Stats returns nodes, online nodes, simulated gross earnings (cents) and the
344// undistributed fairness pool (cents).
345func Stats() (int, int, int64, int64) {
346 return nodes.Size(), countOnline(time.Now()), totalGrossCents, poolCents
347}
348
349// NodeSummary returns a one-line text summary of a node, or "" if unknown.
350func NodeSummary(id int) string {
351 v := nodes.Get(padID(id))
352 if v == nil {
353 return ""
354 }
355 n := v.(*Node)
356 return n.Name + " | " + n.Kind + " | " + n.Region + " | " + n.Power + " | " +
357 fmtUSD(n.RateCents) + "/h | " + statusOf(n, time.Now()) + " | earned " + fmtUSD(n.TotalCents())
358}
359
360// ---------------------------------------------------------------------------
361// internals
362
363func mustCaller(cur realm) address {
364 if !cur.IsCurrent() {
365 panic("spoofed realm")
366 }
367 prev := cur.Previous()
368 if !prev.IsUser() {
369 panic("only user accounts can call this")
370 }
371 return prev.Address()
372}
373
374func mustAdmin(cur realm) {
375 if mustCaller(cur) != admin {
376 panic("only the admin can do this")
377 }
378}
379
380func mustGetNode(id int) *Node {
381 v := nodes.Get(padID(id))
382 if v == nil {
383 panic("node " + strconv.Itoa(id) + " not found")
384 }
385 return v.(*Node)
386}
387
388func mustOwnNode(id int, caller address) *Node {
389 n := mustGetNode(id)
390 if n.Operator != caller {
391 panic("only the node's operator can do this")
392 }
393 return n
394}
395
396func removeNode(n *Node) {
397 nodes.Remove(padID(n.ID))
398 byOperator.Remove(n.Operator.String() + "/" + padID(n.ID))
399 leaderboard.Remove(rankKey(n.TotalCents(), n.ID))
400}
401
402func reRank(n *Node, oldTotal int64) {
403 leaderboard.Remove(rankKey(oldTotal, n.ID))
404 leaderboard.Set(rankKey(n.TotalCents(), n.ID), n.ID)
405}
406
407func operatorNodeCount(op address) int {
408 count := 0
409 prefix := op.String() + "/"
410 byOperator.Iterate(prefix, prefix+"~", func(_ string, _ any) bool {
411 count++
412 return false
413 })
414 return count
415}
416
417func isOnlineAt(n *Node, now time.Time) bool {
418 if n.LastHeartbeat.IsZero() {
419 return false
420 }
421 return now.Sub(n.LastHeartbeat) <= onlineWindow
422}
423
424func countOnline(now time.Time) int {
425 count := 0
426 nodes.Iterate("", "", func(_ string, v any) bool {
427 if isOnlineAt(v.(*Node), now) {
428 count++
429 }
430 return false
431 })
432 return count
433}
434
435// padID makes IDs sort numerically as avl keys.
436func padID(id int) string {
437 s := strconv.Itoa(id)
438 for len(s) < 9 {
439 s = "0" + s
440 }
441 return s
442}
443
444// rankKey sorts the highest total first, ties broken by lowest node ID.
445func rankKey(totalCents int64, id int) string {
446 const ceiling = int64(999999999999999)
447 inv := strconv.FormatInt(ceiling-totalCents, 10)
448 for len(inv) < 15 {
449 inv = "0" + inv
450 }
451 return inv + "/" + padID(id)
452}