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.

validate.gno

2.02 Kb · 81 lines
 1package idlewatt
 2
 3import "strconv"
 4
 5// Input limits.
 6const (
 7	minNameLen     = 3
 8	maxNameLen     = 48
 9	maxHardwareLen = 80
10	minRegionLen   = 2
11	maxRegionLen   = 40
12	maxWorkloadLen = 60
13	maxNoteLen     = 60
14	maxRateCents   = 100000 // $1,000/hour sanity cap
15	maxJobMinutes  = 24 * 60
16)
17
18// isSafeChar is the character whitelist for every free-text field. It keeps
19// operator-supplied strings from injecting markdown, HTML, gnoweb tags or
20// table pipes into Render output, and keeps them single-line.
21func isSafeChar(c rune) bool {
22	switch {
23	case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':
24		return true
25	}
26	switch c {
27	case ' ', '-', '.', ',', '(', ')', '\'', '/', '+', ':', '@', '#', '%', '&', '=':
28		return true
29	}
30	return false
31}
32
33// checkText validates a free-text field and panics with a readable message.
34func checkText(field, s string, minLen, maxLen int) {
35	if len(s) < minLen || len(s) > maxLen {
36		panic(field + " must be " + strconv.Itoa(minLen) + "-" + strconv.Itoa(maxLen) + " characters")
37	}
38	if s[0] == ' ' || s[len(s)-1] == ' ' {
39		panic(field + " must not start or end with a space")
40	}
41	for _, c := range s {
42		if !isSafeChar(c) {
43			panic(field + " contains an unsupported character: only letters, digits, spaces and - . , ( ) ' / + : @ # % & = are allowed")
44		}
45	}
46}
47
48func checkKind(kind string) {
49	switch kind {
50	case KindHomeGPU, KindVehicle, KindCPU:
51		return
52	}
53	panic("kind must be one of: home-gpu, vehicle, cpu")
54}
55
56func checkPower(power string) {
57	switch power {
58	case PowerGrid, PowerSolar, PowerPowershare:
59		return
60	}
61	panic("power must be one of: grid, solar, powershare-backup")
62}
63
64func checkRate(rate int64) {
65	if rate < 1 || rate > maxRateCents {
66		panic("rate must be between 1 and " + strconv.Itoa(maxRateCents) + " US cents per hour")
67	}
68}
69
70func checkMode(kind, mode string) {
71	switch mode {
72	case ModeAvailable, ModePaused:
73		return
74	case ModeDriving:
75		if kind != KindVehicle {
76			panic("only vehicle nodes can be set to driving")
77		}
78		return
79	}
80	panic("mode must be one of: available, driving, paused")
81}