Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

maintenance.gno

13.79 Kb · 407 lines
  1// Package maintenance resolves milestones with a configurable reviewer quorum.
  2package maintenance
  3
  4import (
  5	"chain"
  6	"chain/runtime"
  7	"chain/runtime/unsafe"
  8	"strconv"
  9	"strings"
 10
 11	"gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v3"
 12	"gno.land/p/moul/txlink/v0"
 13	"gno.land/p/nt/avl/v0"
 14	"gno.land/r/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/treasury/v4"
 15)
 16
 17type Roles struct {
 18	Lane        string
 19	Coordinator address
 20	Reviewers   []address
 21	Quorum      int
 22}
 23
 24type milestone struct {
 25	digest string
 26	votes  []string
 27	voters []address
 28}
 29
 30type laneConfig struct {
 31	roles      Roles
 32	milestones *avl.Tree
 33}
 34
 35type MilestoneView struct {
 36	Evidence    string
 37	Votes       []string
 38	Voters      []address
 39	Reservation treasury.ReservationView
 40	Pruned      bool
 41}
 42
 43var (
 44	realmPath = unsafe.CurrentRealm().PkgPath()
 45	lanes     = avl.NewTree()
 46)
 47
 48func PolicyPath() string {
 49	return realmPath
 50}
 51
 52func Configure(cur realm, programID int64, lane string, coordinator address, reviewersCSV string, quorum int) {
 53	if callerAddress(cur) != treasury.GetProgram(programID).Sponsor {
 54		panic("only the program sponsor can configure maintenance")
 55	}
 56	parts := strings.SplitN(reviewersCSV, ",", 8)
 57	if len(parts) < 2 || len(parts) > 7 || quorum < 2 || quorum > len(parts) {
 58		panic("maintenance requires 2 to 7 reviewers and a quorum of 2 to the reviewer count")
 59	}
 60	reviewers := make([]address, len(parts))
 61	for i, part := range parts {
 62		reviewers[i] = address(strings.TrimSpace(part))
 63	}
 64	roles := Roles{Lane: lane, Coordinator: coordinator, Reviewers: reviewers, Quorum: quorum}
 65	requireRoles(roles)
 66	treasury.RegisterPolicy(cross(cur), programID, lane)
 67	lanes.Set(budget.PolicyLaneKey(programID, lane), &laneConfig{roles: roles, milestones: avl.NewTree()})
 68	chain.Emit("MaintenanceConfigured", "program", number(programID), "lane", lane,
 69		"coordinator", string(coordinator), "quorum", strconv.Itoa(quorum))
 70}
 71
 72func SubmitMilestone(cur realm, programID int64, lane string, recipient address, amount, holdBlocks int64, proofDigest, memo string) (int64, int64) {
 73	caller := callerAddress(cur)
 74	p := mustLane(programID, lane)
 75	if caller != p.roles.Coordinator {
 76		panic("only the maintenance coordinator can submit")
 77	}
 78	item := &milestone{votes: make([]string, len(p.roles.Reviewers)), voters: make([]address, len(p.roles.Reviewers))}
 79	if item.deadlocked(p.roles, recipient) {
 80		panic("milestone recipient leaves too few eligible reviewers for quorum")
 81	}
 82	budget.RequireDigest(proofDigest)
 83	budget.RequirePositive(holdBlocks)
 84	deadline := budget.Add(runtime.ChainHeight(), holdBlocks)
 85	itemID, available := treasury.Reserve(cross(cur), programID, lane, recipient, amount, deadline, memo)
 86	evidence := budget.EvidenceCommitment(programID, lane, itemID, proofDigest)
 87	item.digest = evidence
 88	p.milestones.Set(number(itemID), item)
 89	chain.Emit("MilestoneSubmitted", "program", number(programID), "lane", lane, "item", number(itemID),
 90		"actor", string(caller), "evidence", evidence)
 91	return itemID, available
 92}
 93
 94func Vote(cur realm, programID int64, lane string, itemID int64, evidence string, approve bool) string {
 95	caller := callerAddress(cur)
 96	p := mustLane(programID, lane)
 97	index := p.reviewerIndex(caller)
 98	item := p.mustMilestone(itemID)
 99	reservation := openReservation(programID, lane, itemID)
100	if item.digest != evidence {
101		panic("milestone evidence does not match")
102	}
103	if item.deadlocked(p.roles, reservation.Recipient) {
104		releaseDeadlock(cur, programID, lane, itemID)
105		return treasury.Rejected
106	}
107	if caller == reservation.Recipient {
108		panic("recipient cannot review their own milestone")
109	}
110	if item.voted(caller) {
111		panic("reviewer already voted")
112	}
113	if item.votes[index] != "" {
114		panic("reviewer seat already voted on this milestone")
115	}
116	vote := treasury.Rejected
117	if approve {
118		vote = treasury.Approved
119	}
120	item.votes[index], item.voters[index] = vote, caller
121	chain.Emit("MilestoneVote", "program", number(programID), "lane", lane, "item", number(itemID),
122		"reviewer", string(caller), "decision", vote, "evidence", evidence)
123	approvals, rejections, remaining := item.tally(p.roles.Reviewers, reservation.Recipient)
124	switch {
125	case approvals >= p.roles.Quorum:
126		treasury.Approve(cross(cur), programID, lane, itemID)
127		return treasury.Approved
128	case rejections >= p.roles.Quorum:
129		treasury.Reject(cross(cur), programID, lane, itemID)
130		return treasury.Rejected
131	case approvals+remaining < p.roles.Quorum && rejections+remaining < p.roles.Quorum:
132		releaseDeadlock(cur, programID, lane, itemID)
133		return treasury.Rejected
134	}
135	return treasury.Reserved
136}
137
138// ResolveDeadlock releases an open milestone when neither decision can reach quorum.
139func ResolveDeadlock(cur realm, programID int64, lane string, itemID int64) {
140	callerAddress(cur)
141	p := mustLane(programID, lane)
142	item := p.mustMilestone(itemID)
143	if !item.deadlocked(p.roles, openReservation(programID, lane, itemID).Recipient) {
144		panic("milestone can still reach quorum")
145	}
146	releaseDeadlock(cur, programID, lane, itemID)
147}
148
149func releaseDeadlock(cur realm, programID int64, lane string, itemID int64) {
150	treasury.Reject(cross(cur), programID, lane, itemID)
151	chain.Emit("MilestoneDeadlocked", "program", number(programID), "lane", lane, "item", number(itemID))
152}
153
154func openReservation(programID int64, lane string, itemID int64) treasury.ReservationView {
155	reservation := treasury.GetReservation(programID, lane, itemID)
156	if reservation.Status != treasury.Reserved || reservation.ExpiredAtHeight {
157		panic("milestone is no longer open for review")
158	}
159	return reservation
160}
161
162func CancelMilestone(cur realm, programID int64, lane string, itemID int64) {
163	caller := callerAddress(cur)
164	p := mustLane(programID, lane)
165	if caller != p.roles.Coordinator {
166		panic("only the maintenance coordinator can cancel")
167	}
168	if p.mustMilestone(itemID).hasVotes() {
169		panic("milestone can only be canceled before a vote")
170	}
171	treasury.Cancel(cross(cur), programID, lane, itemID)
172}
173
174func RotateReviewer(cur realm, programID int64, lane string, index int, newReviewer address) {
175	caller := callerAddress(cur)
176	if treasury.GetProgram(programID).Sponsor != caller {
177		panic("only the program sponsor can rotate reviewers")
178	}
179	p := mustLane(programID, lane)
180	if index < 0 || index >= len(p.roles.Reviewers) {
181		panic("reviewer index is out of range")
182	}
183	roles := GetRoles(programID, lane)
184	old := roles.Reviewers[index]
185	roles.Reviewers[index] = newReviewer
186	requireRoles(roles)
187	p.roles = roles
188	chain.Emit("ReviewerRotated", "program", number(programID), "lane", roles.Lane,
189		"index", strconv.Itoa(index), "old_reviewer", string(old), "reviewer", string(newReviewer))
190}
191
192func RotateCoordinator(cur realm, programID int64, lane string, newCoordinator address) {
193	if callerAddress(cur) != treasury.GetProgram(programID).Sponsor {
194		panic("only the program sponsor can rotate the coordinator")
195	}
196	p := mustLane(programID, lane)
197	roles := p.roles
198	roles.Coordinator = newCoordinator
199	requireRoles(roles)
200	p.roles.Coordinator = newCoordinator
201	chain.Emit("CoordinatorRotated", "program", number(programID), "lane", lane, "coordinator", string(newCoordinator))
202}
203
204func PruneClosed(cur realm, programID int64, lane string) int64 {
205	caller := callerAddress(cur)
206	program := treasury.GetProgram(programID)
207	if caller != program.Sponsor {
208		panic("only the program sponsor can prune maintenance")
209	}
210	p := mustLane(programID, lane)
211	if program.Status != treasury.Closed || program.Balance.Claimable != 0 ||
212		program.ActiveReservations != 0 || p.milestones == nil {
213		panic("pruning requires an unpruned closed lane with no unpaid claims or pending reservations")
214	}
215	count := int64(p.milestones.Size())
216	p.milestones = nil
217	chain.Emit("MaintenancePruned", "program", number(programID), "lane", lane, "items", number(count))
218	return count
219}
220
221func GetRoles(programID int64, lane string) Roles {
222	roles := mustLane(programID, lane).roles
223	roles.Reviewers = append([]address(nil), roles.Reviewers...)
224	return roles
225}
226
227func GetMilestone(programID int64, lane string, itemID int64) MilestoneView {
228	p := mustLane(programID, lane)
229	if p.milestones == nil || treasury.GetProgram(programID).Pruned {
230		return MilestoneView{Pruned: true}
231	}
232	item := p.mustMilestone(itemID)
233	return MilestoneView{Evidence: item.digest, Votes: append([]string(nil), item.votes...),
234		Voters: append([]address(nil), item.voters...), Reservation: treasury.GetReservation(programID, lane, itemID)}
235}
236
237func Render(path string) string {
238	program, names, itemID := treasury.PolicyRenderRoute(path, realmPath)
239	if len(names) == 0 {
240		return "# Maintenance\n\nOpen a configured lane with `:programID/lane` or a milestone with `:programID/lane/itemID`."
241	}
242	if len(names) > 1 {
243		return "# Maintenance lanes\n\n" + budget.PolicyLaneLinks(realmPath, program.ID, names)
244	}
245	id, lane := program.ID, names[0]
246	p := mustLane(id, lane)
247	tx := txlink.Realm(realmPath)
248	args := []string{"programID", number(id), "lane", lane}
249	if itemID == 0 {
250		var page strings.Builder
251		page.WriteString("# Maintenance · Program " + number(id) + "\n\n**Lane** " + budget.MarkdownText(p.roles.Lane) +
252			" · **Quorum** " + strconv.Itoa(p.roles.Quorum) + " of " + strconv.Itoa(len(p.roles.Reviewers)) + " reviewers\n\n| Role | Address |\n| --- | --- |\n| Coordinator | " + string(p.roles.Coordinator) + " |\n")
253		for i, reviewer := range p.roles.Reviewers {
254			page.WriteString("| Reviewer " + strconv.Itoa(i+1) + " | " + string(reviewer) + " |\n")
255		}
256		page.WriteString("\n[Rotate a reviewer](" + tx.Call("RotateReviewer", args...) + ") · [Rotate coordinator](" +
257			tx.Call("RotateCoordinator", args...) + ")")
258		if program.Status == treasury.Active {
259			page.WriteString(" · [Submit a milestone](" + tx.Call("SubmitMilestone", args...) + ")")
260		}
261		if program.Status == treasury.Closed && program.Balance.Claimable == 0 && p.milestones != nil {
262			page.WriteString("\n[Prune milestones](" + tx.Call("PruneClosed", args...) + ")")
263		}
264		return page.String() + "\n"
265	}
266	if program.Pruned || p.milestones == nil {
267		return "# Maintenance\n\nMilestone records were pruned."
268	}
269	item := p.milestone(itemID)
270	if item == nil {
271		return "# Maintenance\n\nMilestone not found."
272	}
273	m := GetMilestone(id, lane, itemID)
274	var page strings.Builder
275	page.WriteString("# Milestone " + number(itemID) + "\n\n**Status** " + m.Reservation.Status +
276		" · **Amount** " + budget.MarkdownText(program.FormatAmount(m.Reservation.Amount)) +
277		"\n\n**Memo** " + budget.MarkdownText(m.Reservation.Memo) +
278		"\n\n**Evidence** `" + m.Evidence + "`\n\n| Reviewer seat | Current address | Vote | Signed by |\n| --- | --- | --- | --- |\n")
279	for i, reviewer := range p.roles.Reviewers {
280		vote, signer := m.Votes[i], m.Voters[i]
281		if vote == "" {
282			vote = "—"
283			if reviewer == m.Reservation.Recipient {
284				vote = "Recipient · ineligible"
285			} else if item.voted(reviewer) {
286				vote = "Already voted"
287			}
288		}
289		page.WriteString("| " + strconv.Itoa(i+1) + " | " + string(reviewer) + " | " + vote + " | " + string(signer) + " |\n")
290	}
291	if m.Reservation.Status == treasury.Reserved && !m.Reservation.ExpiredAtHeight {
292		args = append(args, "itemID", number(itemID))
293		if item.deadlocked(p.roles, m.Reservation.Recipient) {
294			page.WriteString("\n[Resolve deadlock](" + tx.Call("ResolveDeadlock", args...) + ")\n")
295			return page.String()
296		}
297		if !item.hasVotes() {
298			page.WriteString("\n[Cancel milestone](" + tx.Call("CancelMilestone", args...) + ")\n")
299		}
300		args = append(args, "evidence", m.Evidence)
301		page.WriteString("\n[Vote to approve](" + tx.Call("Vote", append(args, "approve", "true")...) +
302			") · [Vote to reject](" + tx.Call("Vote", append(args, "approve", "false")...) + ")\n")
303	}
304	return page.String()
305}
306
307func requireRoles(roles Roles) {
308	budget.RequireAddress(roles.Coordinator)
309	for i, reviewer := range roles.Reviewers {
310		budget.RequireAddress(reviewer)
311		if reviewer == roles.Coordinator {
312			panic("coordinator cannot be a reviewer")
313		}
314		for _, previous := range roles.Reviewers[:i] {
315			if reviewer == previous {
316				panic("reviewers must be distinct")
317			}
318		}
319	}
320}
321
322func (item *milestone) hasVotes() bool {
323	for _, vote := range item.votes {
324		if vote != "" {
325			return true
326		}
327	}
328	return false
329}
330
331func (item *milestone) voted(caller address) bool {
332	for _, voter := range item.voters {
333		if voter == caller {
334			return true
335		}
336	}
337	return false
338}
339
340// Votes belong to their signer and occupy a seat even if its reviewer changes.
341func (item *milestone) tally(reviewers []address, recipient address) (approvals, rejections, remaining int) {
342	for i, vote := range item.votes {
343		switch vote {
344		case treasury.Approved:
345			approvals++
346		case treasury.Rejected:
347			rejections++
348		default:
349			if reviewers[i] != recipient && !item.voted(reviewers[i]) {
350				remaining++
351			}
352		}
353	}
354	return
355}
356
357func (item *milestone) deadlocked(roles Roles, recipient address) bool {
358	approvals, rejections, remaining := item.tally(roles.Reviewers, recipient)
359	return approvals+remaining < roles.Quorum && rejections+remaining < roles.Quorum
360}
361
362func mustLane(programID int64, lane string) *laneConfig {
363	p, _ := lanes.Get(budget.PolicyLaneKey(programID, lane)).(*laneConfig)
364	if p == nil {
365		panic("maintenance lane is not configured")
366	}
367	return p
368}
369
370func (p *laneConfig) milestone(itemID int64) *milestone {
371	if p.milestones == nil {
372		return nil
373	}
374	item, _ := p.milestones.Get(number(itemID)).(*milestone)
375	return item
376}
377
378func (p *laneConfig) mustMilestone(itemID int64) *milestone {
379	item := p.milestone(itemID)
380	if item == nil {
381		panic("milestone not found")
382	}
383	return item
384}
385
386func (p *laneConfig) reviewerIndex(caller address) int {
387	for i, reviewer := range p.roles.Reviewers {
388		if reviewer == caller {
389			return i
390		}
391	}
392	panic("only a registered maintenance reviewer can vote")
393}
394
395func callerAddress(cur realm) address {
396	if !cur.IsCurrent() || cur.PkgPath() != realmPath {
397		panic("invalid maintenance context")
398	}
399	if len(unsafe.OriginSend()) != 0 {
400		panic("unexpected attached coins")
401	}
402	return cur.Previous().Address()
403}
404
405func number(n int64) string {
406	return strconv.FormatInt(n, 10)
407}