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.

prooftrail.gno

11.83 Kb · 400 lines
  1package prooftrail
  2
  3import (
  4	"chain/runtime/unsafe"
  5	"strconv"
  6	"strings"
  7	"time"
  8)
  9
 10const (
 11	StatusPending  = "pending"
 12	StatusAccepted = "accepted"
 13	StatusRejected = "rejected"
 14	TaskOpen       = "open"
 15	TaskClosed     = "closed"
 16)
 17
 18type Community struct {
 19	id          int
 20	name        string
 21	description string
 22	admin       address
 23	reviewers   []address
 24	createdAt   int64
 25}
 26
 27type Task struct {
 28	id           int
 29	communityID  int
 30	title        string
 31	description  string
 32	requirements string
 33	status       string
 34	createdBy    address
 35	createdAt    int64
 36}
 37
 38type Submission struct {
 39	id           int
 40	taskID       int
 41	communityID  int
 42	contributor  address
 43	evidenceURL  string
 44	evidenceHash string // SHA-256 (hex) of the evidence, computed by the contributor. Proves integrity only.
 45	notes        string
 46	status       string
 47	reviewer     address
 48	reviewReason string
 49	submittedAt  int64
 50	reviewedAt   int64
 51}
 52
 53type Event struct {
 54	seq     int
 55	kind    string
 56	actor   address
 57	subject int
 58	detail  string
 59	at      int64
 60}
 61
 62var (
 63	communities []*Community
 64	tasks       []*Task
 65	submissions []*Submission
 66	audit       []*Event // append-only: no function edits or removes entries
 67)
 68
 69// ---------- helpers ----------
 70
 71func now() int64 { return time.Now().Unix() }
 72
 73func logEvent(kind string, actor address, subject int, detail string) {
 74	audit = append(audit, &Event{seq: len(audit) + 1, kind: kind, actor: actor, subject: subject, detail: detail, at: now()})
 75}
 76
 77func checkText(field, s string, min, max int, multiline bool) {
 78	if len(s) < min {
 79		panic(field + " is too short")
 80	}
 81	if len(s) > max {
 82		panic(field + " is too long")
 83	}
 84	for i := 0; i < len(s); i++ {
 85		c := s[i]
 86		if c < 32 && !(multiline && (c == '\n' || c == '\t')) {
 87			panic(field + " contains invalid characters")
 88		}
 89		if c == 127 {
 90			panic(field + " contains invalid characters")
 91		}
 92	}
 93}
 94
 95// Evidence URLs are untrusted: https only, no spaces, no markup characters.
 96func checkURL(s string) {
 97	checkText("evidenceURL", s, 12, 300, false)
 98	if !strings.HasPrefix(s, "https://") {
 99		panic("evidenceURL must start with https://")
100	}
101	if strings.ContainsAny(s, " \"'<>`\\") {
102		panic("evidenceURL contains forbidden characters")
103	}
104}
105
106func checkHash(h string) {
107	if len(h) != 64 {
108		panic("evidenceHash must be 64 hex characters (SHA-256)")
109	}
110	for i := 0; i < len(h); i++ {
111		c := h[i]
112		if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) {
113			panic("evidenceHash must be lowercase hex")
114		}
115	}
116}
117
118func getCommunity(id int) *Community {
119	if id < 1 || id > len(communities) {
120		panic("community not found")
121	}
122	return communities[id-1]
123}
124
125func getTask(id int) *Task {
126	if id < 1 || id > len(tasks) {
127		panic("task not found")
128	}
129	return tasks[id-1]
130}
131
132func getSubmission(id int) *Submission {
133	if id < 1 || id > len(submissions) {
134		panic("submission not found")
135	}
136	return submissions[id-1]
137}
138
139func (c *Community) isReviewer(a address) bool {
140	for _, r := range c.reviewers {
141		if r == a {
142			return true
143		}
144	}
145	return false
146}
147
148func requireAdmin(c *Community, caller address) {
149	if c.admin != caller {
150		panic("only the community administrator can do this")
151	}
152}
153
154// ---------- transactions (crossing functions) ----------
155
156func CreateCommunity(cur realm, name, description string) int {
157	caller := unsafe.PreviousRealm().Address()
158	checkText("name", name, 3, 60, false)
159	checkText("description", description, 0, 500, true)
160	id := len(communities) + 1
161	communities = append(communities, &Community{id: id, name: name, description: description, admin: caller, reviewers: []address{caller}, createdAt: now()})
162	logEvent("community_created", caller, id, name)
163	return id
164}
165
166func AddReviewer(cur realm, communityID int, reviewer address) {
167	caller := unsafe.PreviousRealm().Address()
168	c := getCommunity(communityID)
169	requireAdmin(c, caller)
170	if !reviewer.IsValid() {
171		panic("invalid reviewer address")
172	}
173	if c.isReviewer(reviewer) {
174		panic("already a reviewer")
175	}
176	c.reviewers = append(c.reviewers, reviewer)
177	logEvent("reviewer_added", caller, communityID, reviewer.String())
178}
179
180func RemoveReviewer(cur realm, communityID int, reviewer address) {
181	caller := unsafe.PreviousRealm().Address()
182	c := getCommunity(communityID)
183	requireAdmin(c, caller)
184	if !c.isReviewer(reviewer) {
185		panic("not a reviewer")
186	}
187	out := []address{}
188	for _, r := range c.reviewers {
189		if r != reviewer {
190			out = append(out, r)
191		}
192	}
193	c.reviewers = out
194	logEvent("reviewer_removed", caller, communityID, reviewer.String())
195}
196
197func CreateTask(cur realm, communityID int, title, description, requirements string) int {
198	caller := unsafe.PreviousRealm().Address()
199	c := getCommunity(communityID)
200	requireAdmin(c, caller)
201	checkText("title", title, 3, 100, false)
202	checkText("description", description, 0, 1000, true)
203	checkText("requirements", requirements, 0, 1000, true)
204	id := len(tasks) + 1
205	tasks = append(tasks, &Task{id: id, communityID: communityID, title: title, description: description, requirements: requirements, status: TaskOpen, createdBy: caller, createdAt: now()})
206	logEvent("task_created", caller, id, title)
207	return id
208}
209
210// Description/requirements may only change while the task is open and has no submissions,
211// so contributors are never judged against rules that changed after they submitted.
212func UpdateTask(cur realm, taskID int, description, requirements string) {
213	caller := unsafe.PreviousRealm().Address()
214	t := getTask(taskID)
215	requireAdmin(getCommunity(t.communityID), caller)
216	if t.status != TaskOpen {
217		panic("task is not open")
218	}
219	for _, s := range submissions {
220		if s.taskID == taskID {
221			panic("task already has submissions and can no longer be edited")
222		}
223	}
224	checkText("description", description, 0, 1000, true)
225	checkText("requirements", requirements, 0, 1000, true)
226	t.description = description
227	t.requirements = requirements
228	logEvent("task_updated", caller, taskID, "")
229}
230
231func CloseTask(cur realm, taskID int) {
232	caller := unsafe.PreviousRealm().Address()
233	t := getTask(taskID)
234	requireAdmin(getCommunity(t.communityID), caller)
235	if t.status != TaskOpen {
236		panic("task is already closed")
237	}
238	t.status = TaskClosed
239	logEvent("task_closed", caller, taskID, "")
240}
241
242func SubmitContribution(cur realm, taskID int, evidenceURL, evidenceHash, notes string) int {
243	caller := unsafe.PreviousRealm().Address()
244	t := getTask(taskID)
245	if t.status != TaskOpen {
246		panic("task is closed")
247	}
248	checkURL(evidenceURL)
249	checkHash(evidenceHash)
250	checkText("notes", notes, 0, 500, true)
251	for _, s := range submissions {
252		if s.taskID != taskID {
253			continue
254		}
255		if s.contributor == caller && s.status != StatusRejected {
256			panic("you already have an active or accepted submission for this task")
257		}
258		if s.evidenceHash == evidenceHash && s.status != StatusRejected {
259			panic("this evidence was already submitted for this task")
260		}
261	}
262	id := len(submissions) + 1
263	submissions = append(submissions, &Submission{id: id, taskID: taskID, communityID: t.communityID, contributor: caller, evidenceURL: evidenceURL, evidenceHash: evidenceHash, notes: notes, status: StatusPending, submittedAt: now()})
264	logEvent("submitted", caller, id, evidenceHash)
265	return id
266}
267
268func review(caller address, id int, to string, reason string) {
269	s := getSubmission(id)
270	c := getCommunity(s.communityID)
271	if !c.isReviewer(caller) {
272		panic("not an authorized reviewer for this community")
273	}
274	if s.contributor == caller {
275		panic("reviewers cannot review their own submission")
276	}
277	if s.status != StatusPending {
278		panic("submission is already " + s.status)
279	}
280	s.status = to
281	s.reviewer = caller
282	s.reviewReason = reason
283	s.reviewedAt = now()
284	logEvent("review_"+to, caller, id, reason)
285}
286
287func AcceptSubmission(cur realm, submissionID int, reason string) {
288	checkText("reason", reason, 0, 500, true)
289	review(unsafe.PreviousRealm().Address(), submissionID, StatusAccepted, reason)
290}
291
292func RejectSubmission(cur realm, submissionID int, reason string) {
293	checkText("reason", reason, 3, 500, true)
294	review(unsafe.PreviousRealm().Address(), submissionID, StatusRejected, reason)
295}
296
297// ---------- JSON helpers (read-only) ----------
298
299func js(s string) string {
300	r := strings.NewReplacer("\\", "\\\\", "\"", "\\\"", "\n", "\\n", "\t", "\\t")
301	return "\"" + r.Replace(s) + "\""
302}
303
304func i64(n int64) string { return strconv.FormatInt(n, 10) }
305func in(n int) string    { return strconv.Itoa(n) }
306
307func (c *Community) json() string {
308	rs := []string{}
309	for _, r := range c.reviewers {
310		rs = append(rs, js(r.String()))
311	}
312	return "{\"id\":" + in(c.id) + ",\"name\":" + js(c.name) + ",\"description\":" + js(c.description) + ",\"admin\":" + js(c.admin.String()) + ",\"reviewers\":[" + strings.Join(rs, ",") + "],\"createdAt\":" + i64(c.createdAt) + "}"
313}
314
315func (t *Task) json() string {
316	return "{\"id\":" + in(t.id) + ",\"communityId\":" + in(t.communityID) + ",\"title\":" + js(t.title) + ",\"description\":" + js(t.description) + ",\"requirements\":" + js(t.requirements) + ",\"status\":" + js(t.status) + ",\"createdBy\":" + js(t.createdBy.String()) + ",\"createdAt\":" + i64(t.createdAt) + "}"
317}
318
319func (s *Submission) json() string {
320	return "{\"id\":" + in(s.id) + ",\"taskId\":" + in(s.taskID) + ",\"communityId\":" + in(s.communityID) + ",\"contributor\":" + js(s.contributor.String()) + ",\"evidenceUrl\":" + js(s.evidenceURL) + ",\"evidenceHash\":" + js(s.evidenceHash) + ",\"notes\":" + js(s.notes) + ",\"status\":" + js(s.status) + ",\"reviewer\":" + js(s.reviewer.String()) + ",\"reviewReason\":" + js(s.reviewReason) + ",\"submittedAt\":" + i64(s.submittedAt) + ",\"reviewedAt\":" + i64(s.reviewedAt) + "}"
321}
322
323func (e *Event) json() string {
324	return "{\"seq\":" + in(e.seq) + ",\"kind\":" + js(e.kind) + ",\"actor\":" + js(e.actor.String()) + ",\"subject\":" + in(e.subject) + ",\"detail\":" + js(e.detail) + ",\"at\":" + i64(e.at) + "}"
325}
326
327func arr(items []string) string { return "[" + strings.Join(items, ",") + "]" }
328
329// ---------- Render: markdown for gnoweb, "api/..." paths return JSON for the web app ----------
330
331func mdEscape(s string) string {
332	r := strings.NewReplacer("<", "\\<", ">", "\\>", "[", "\\[", "]", "\\]", "(", "\\(", ")", "\\)", "*", "\\*", "_", "\\_", "`", "\\`")
333	return r.Replace(s)
334}
335
336func Render(path string) string {
337	if strings.HasPrefix(path, "api/") {
338		return renderAPI(strings.TrimPrefix(path, "api/"))
339	}
340	out := "# ProofTrail\n\nVerifiable Contributions. Transparent History.\n\n"
341	out += "Communities: " + in(len(communities)) + " | Tasks: " + in(len(tasks)) + " | Submissions: " + in(len(submissions)) + "\n\n"
342	for _, s := range submissions {
343		if s.status == StatusAccepted {
344			out += "- Accepted #" + in(s.id) + " on task " + in(s.taskID) + " by " + s.contributor.String() + " (hash " + s.evidenceHash + ")\n"
345		}
346	}
347	return out
348}
349
350func renderAPI(p string) string {
351	parts := strings.Split(p, "/")
352	switch parts[0] {
353	case "stats":
354		return "{\"communities\":" + in(len(communities)) + ",\"tasks\":" + in(len(tasks)) + ",\"submissions\":" + in(len(submissions)) + ",\"events\":" + in(len(audit)) + "}"
355	case "communities":
356		out := []string{}
357		for _, c := range communities {
358			out = append(out, c.json())
359		}
360		return arr(out)
361	case "tasks": // api/tasks or api/tasks/<communityId>
362		out := []string{}
363		for _, t := range tasks {
364			if len(parts) > 1 && in(t.communityID) != parts[1] {
365				continue
366			}
367			out = append(out, t.json())
368		}
369		return arr(out)
370	case "submissions": // api/submissions/task/<id> | contributor/<addr> | community/<id> | accepted
371		out := []string{}
372		for _, s := range submissions {
373			ok := len(parts) == 1
374			if len(parts) == 2 && parts[1] == "accepted" {
375				ok = s.status == StatusAccepted
376			}
377			if len(parts) == 3 {
378				switch parts[1] {
379				case "task":
380					ok = in(s.taskID) == parts[2]
381				case "contributor":
382					ok = s.contributor.String() == parts[2]
383				case "community":
384					ok = in(s.communityID) == parts[2]
385				}
386			}
387			if ok {
388				out = append(out, s.json())
389			}
390		}
391		return arr(out)
392	case "audit":
393		out := []string{}
394		for _, e := range audit {
395			out = append(out, e.json())
396		}
397		return arr(out)
398	}
399	return "{\"error\":\"unknown path\"}"
400}