board.gno
10.79 Kb · 420 lines
1package gauntlet
2
3import (
4 "crypto/sha256"
5 "encoding/binary"
6 "encoding/hex"
7 "errors"
8 "strconv"
9 "strings"
10 "time"
11
12 "gno.land/p/nt/avl/v0"
13)
14
15// Status of a challenge.
16type Status int
17
18const (
19 Open Status = iota // accepting commits until the deadline
20 Won // paid out to the earliest passing commit
21 Closed // nobody passed; reward returned to the poster
22)
23
24func (s Status) String() string {
25 switch s {
26 case Open:
27 return "open"
28 case Won:
29 return "won"
30 case Closed:
31 return "closed"
32 }
33 return "unknown"
34}
35
36// State of an attempt.
37type State int
38
39const (
40 Pending State = iota // committed, not yet revealed
41 Passed // revealed and passed every test
42 Failed // revealed and failed a test
43 Expired // not revealed in time; bond forfeited
44 Refunded // challenge ended before it was revealed; bond returned
45)
46
47func (s State) String() string {
48 switch s {
49 case Pending:
50 return "pending"
51 case Passed:
52 return "passed"
53 case Failed:
54 return "failed"
55 case Expired:
56 return "expired"
57 case Refunded:
58 return "refunded"
59 }
60 return "unknown"
61}
62
63// Attempt is one solver's commit, and its result once revealed.
64type Attempt struct {
65 Seq uint64 // global order of commits on the board
66 Solver address
67 Hash string
68 CommittedAt time.Time
69 State State
70 PkgPath string // the solution realm, set on reveal
71 RevealedAt time.Time
72 Report Report
73}
74
75// Challenge is one bounty.
76type Challenge struct {
77 ID uint64
78 Title string
79 Spec string // markdown
80 Poster address
81 Reward int64 // escrowed by the hosting realm
82 Bond int64 // required with every commit, refunded on reveal
83 Created time.Time
84 Deadline time.Time // last moment to commit
85 Window time.Duration // time allowed between commit and reveal
86
87 Cases []Case // fixed tests, may be empty if Judge is set
88 Judge *Judge
89 JudgePath string // package path of the judge's code, for display
90
91 Status Status
92 Winner *Attempt
93 Attempts []*Attempt
94 Forfeited int64 // expired bonds, added to the reward
95 Boosts int64 // reward added after posting
96}
97
98// Pot is what the winner (or, if nobody wins, the poster) receives.
99func (c *Challenge) Pot() int64 { return c.Reward + c.Forfeited }
100
101// Payout is an instruction for the hosting realm to send coins.
102type Payout struct {
103 To address
104 Amount int64
105 Reason string
106}
107
108// PostParams describes a new challenge.
109type PostParams struct {
110 Title string
111 Spec string
112 Poster address
113 Reward int64
114 Bond int64
115 Deadline time.Time
116 Window time.Duration
117 Cases []Case
118 Judge *Judge
119 JudgePath string
120}
121
122const (
123 MaxTitleLen = 120
124 MaxSpecLen = 8000
125 MaxAttempts = 256
126 MinWindow = time.Minute
127 MaxWindow = 7 * 24 * time.Hour
128 MaxPostLength = 90 * 24 * time.Hour
129)
130
131var (
132 ErrNotFound = errors.New("gauntlet: challenge not found")
133 ErrNotOpen = errors.New("gauntlet: challenge is not open")
134 ErrPastDeadline = errors.New("gauntlet: commits are closed for this challenge")
135 ErrBadTitle = errors.New("gauntlet: title must be 1-120 characters")
136 ErrBadSpec = errors.New("gauntlet: spec is too long")
137 ErrBadReward = errors.New("gauntlet: reward must be positive")
138 ErrBadBond = errors.New("gauntlet: bond cannot be negative")
139 ErrBadDeadline = errors.New("gauntlet: deadline must be in the future and within 90 days")
140 ErrBadWindow = errors.New("gauntlet: reveal window must be between 1 minute and 7 days")
141 ErrNoTests = errors.New("gauntlet: a challenge needs test cases or a judge")
142 ErrBadHash = errors.New("gauntlet: hash must be 64 hex characters")
143 ErrWrongBond = errors.New("gauntlet: wrong bond amount")
144 ErrHasPending = errors.New("gauntlet: you already have a pending commit on this challenge")
145 ErrDuplicateHash = errors.New("gauntlet: this hash was already committed")
146 ErrFull = errors.New("gauntlet: too many attempts on this challenge")
147 ErrNoCommit = errors.New("gauntlet: no pending commit matches this package path and salt")
148 ErrRevealTooLate = errors.New("gauntlet: reveal window has passed for this commit")
149 ErrNotRealm = errors.New("gauntlet: solutions must be revealed from a deployed /r/ realm")
150 ErrBadBoostAmount = errors.New("gauntlet: boost must be positive")
151)
152
153// Board is a set of challenges. The zero value is ready to use.
154type Board struct {
155 challenges avl.Tree // key(id) -> *Challenge
156 lastID uint64
157 seq uint64
158}
159
160func key(id uint64) string {
161 s := strconv.FormatUint(id, 10)
162 return strings.Repeat("0", 20-len(s)) + s
163}
164
165// HashSolution is the commitment a solver posts: sha256(pkgPath + ":" + salt)
166// as lowercase hex.
167func HashSolution(pkgPath, salt string) string {
168 sum := sha256.Sum256([]byte(pkgPath + ":" + salt))
169 return hex.EncodeToString(sum[:])
170}
171
172// Post adds a challenge. The caller must already hold p.Reward in escrow.
173func (b *Board) Post(p PostParams, now time.Time) (*Challenge, error) {
174 if len(p.Title) == 0 || len(p.Title) > MaxTitleLen {
175 return nil, ErrBadTitle
176 }
177 if len(p.Spec) > MaxSpecLen {
178 return nil, ErrBadSpec
179 }
180 if p.Reward <= 0 {
181 return nil, ErrBadReward
182 }
183 if p.Bond < 0 {
184 return nil, ErrBadBond
185 }
186 if !p.Deadline.After(now) || p.Deadline.Sub(now) > MaxPostLength {
187 return nil, ErrBadDeadline
188 }
189 if p.Window < MinWindow || p.Window > MaxWindow {
190 return nil, ErrBadWindow
191 }
192 if len(p.Cases) == 0 && p.Judge == nil {
193 return nil, ErrNoTests
194 }
195 if len(p.Cases) > MaxCases {
196 return nil, ErrTooManyCase
197 }
198 b.lastID++
199 c := &Challenge{
200 ID: b.lastID,
201 Title: p.Title,
202 Spec: p.Spec,
203 Poster: p.Poster,
204 Reward: p.Reward,
205 Bond: p.Bond,
206 Created: now,
207 Deadline: p.Deadline,
208 Window: p.Window,
209 Cases: p.Cases,
210 Judge: p.Judge,
211 JudgePath: p.JudgePath,
212 Status: Open,
213 }
214 b.challenges.Set(key(c.ID), c)
215 return c, nil
216}
217
218// Get returns a challenge or nil.
219func (b *Board) Get(id uint64) *Challenge {
220 v := b.challenges.Get(key(id))
221 if v == nil {
222 return nil
223 }
224 return v.(*Challenge)
225}
226
227// Size is the number of challenges ever posted.
228func (b *Board) Size() int { return b.challenges.Size() }
229
230// Iterate visits challenges newest first. Return true to stop.
231func (b *Board) Iterate(cb func(c *Challenge) bool) {
232 b.challenges.ReverseIterate("", "", func(_ string, v any) bool {
233 return cb(v.(*Challenge))
234 })
235}
236
237// Commit records a solver's place in line.
238func (b *Board) Commit(id uint64, solver address, hash string, bond int64, now time.Time) (*Attempt, error) {
239 c := b.Get(id)
240 if c == nil {
241 return nil, ErrNotFound
242 }
243 if c.Status != Open {
244 return nil, ErrNotOpen
245 }
246 if !now.Before(c.Deadline) {
247 return nil, ErrPastDeadline
248 }
249 if bond != c.Bond {
250 return nil, ErrWrongBond
251 }
252 if !isHexHash(hash) {
253 return nil, ErrBadHash
254 }
255 if len(c.Attempts) >= MaxAttempts {
256 return nil, ErrFull
257 }
258 for _, a := range c.Attempts {
259 if a.Hash == hash {
260 return nil, ErrDuplicateHash
261 }
262 if a.Solver == solver && a.State == Pending {
263 return nil, ErrHasPending
264 }
265 }
266 b.seq++
267 a := &Attempt{
268 Seq: b.seq,
269 Solver: solver,
270 Hash: hash,
271 CommittedAt: now,
272 State: Pending,
273 }
274 c.Attempts = append(c.Attempts, a)
275 return a, nil
276}
277
278// Reveal grades a solution. pkgPath must be the package path of the realm
279// that is calling, as reported by the runtime, never a value a user typed.
280func (b *Board) Reveal(id uint64, pkgPath, salt string, solve Solver, now time.Time) (*Attempt, []Payout, error) {
281 c := b.Get(id)
282 if c == nil {
283 return nil, nil, ErrNotFound
284 }
285 if !strings.Contains(pkgPath, "/r/") {
286 return nil, nil, ErrNotRealm
287 }
288 hash := HashSolution(pkgPath, salt)
289 var a *Attempt
290 for _, x := range c.Attempts {
291 if x.Hash == hash {
292 a = x
293 break
294 }
295 }
296 if a == nil || a.State != Pending {
297 return nil, nil, ErrNoCommit
298 }
299 if now.After(a.CommittedAt.Add(c.Window)) {
300 return nil, nil, ErrRevealTooLate
301 }
302
303 a.PkgPath = pkgPath
304 a.RevealedAt = now
305 if c.Judge != nil {
306 a.Report = GradeJudge(c.Judge, seedFor(hash, salt, now), solve)
307 } else {
308 a.Report = GradeCases(c.Cases, solve)
309 }
310 // A judged challenge with fixed cases runs both.
311 if c.Judge != nil && len(c.Cases) > 0 && a.Report.OK() {
312 fixed := GradeCases(c.Cases, solve)
313 fixed.Passed += a.Report.Passed
314 fixed.Total += a.Report.Total
315 a.Report = fixed
316 }
317 if a.Report.OK() {
318 a.State = Passed
319 } else {
320 a.State = Failed
321 }
322
323 var payouts []Payout
324 if c.Bond > 0 {
325 payouts = append(payouts, Payout{To: a.Solver, Amount: c.Bond, Reason: "bond refund"})
326 }
327 payouts = append(payouts, b.settle(c, now)...)
328 return a, payouts, nil
329}
330
331// Settle moves a challenge forward: it expires late commits and, when the
332// result is certain, pays the winner or returns the reward to the poster.
333// Anyone may call it; it is also run after every reveal.
334func (b *Board) Settle(id uint64, now time.Time) ([]Payout, error) {
335 c := b.Get(id)
336 if c == nil {
337 return nil, ErrNotFound
338 }
339 return b.settle(c, now), nil
340}
341
342func (b *Board) settle(c *Challenge, now time.Time) []Payout {
343 if c.Status != Open {
344 return nil
345 }
346 var winner *Attempt
347 for _, a := range c.Attempts { // already in commit order
348 if a.State == Pending && now.After(a.CommittedAt.Add(c.Window)) {
349 a.State = Expired
350 c.Forfeited += c.Bond
351 }
352 switch a.State {
353 case Pending:
354 return nil // an earlier commit may still win; wait for it
355 case Passed:
356 winner = a
357 }
358 if winner != nil {
359 break
360 }
361 }
362
363 var payouts []Payout
364 if winner != nil {
365 c.Status = Won
366 c.Winner = winner
367 payouts = append(payouts, Payout{To: winner.Solver, Amount: c.Pot(), Reason: "bounty won"})
368 } else if !now.Before(c.Deadline) {
369 c.Status = Closed
370 payouts = append(payouts, Payout{To: c.Poster, Amount: c.Pot(), Reason: "no winner, reward returned"})
371 } else {
372 return nil
373 }
374 // Later commits did nothing wrong: return their bonds.
375 for _, a := range c.Attempts {
376 if a.State == Pending {
377 a.State = Refunded
378 if c.Bond > 0 {
379 payouts = append(payouts, Payout{To: a.Solver, Amount: c.Bond, Reason: "bond refund, challenge ended"})
380 }
381 }
382 }
383 return payouts
384}
385
386// Boost adds to the reward of an open challenge.
387func (b *Board) Boost(id uint64, amount int64, now time.Time) error {
388 c := b.Get(id)
389 if c == nil {
390 return ErrNotFound
391 }
392 if c.Status != Open || !now.Before(c.Deadline) {
393 return ErrNotOpen
394 }
395 if amount <= 0 {
396 return ErrBadBoostAmount
397 }
398 c.Reward += amount
399 c.Boosts += amount
400 return nil
401}
402
403func isHexHash(s string) bool {
404 if len(s) != 64 {
405 return false
406 }
407 for i := 0; i < len(s); i++ {
408 ch := s[i]
409 if !(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'f') {
410 return false
411 }
412 }
413 return true
414}
415
416// seedFor derives the judge seed from values fixed only at reveal time.
417func seedFor(hash, salt string, now time.Time) uint64 {
418 sum := sha256.Sum256([]byte(hash + ":" + salt + ":" + strconv.FormatInt(now.UnixNano(), 10)))
419 return binary.BigEndian.Uint64(sum[:8])
420}