budget.gno
7.79 Kb · 303 lines
1// Package budget provides accounting, spending limits, and presentation for a shared pool.
2package budget
3
4import (
5 "crypto/bech32"
6 "crypto/sha256"
7 "encoding/hex"
8 "strconv"
9 "strings"
10 "unicode"
11 "unicode/utf8"
12)
13
14const (
15 Denom = "ugnot"
16 GRC20Prefix = "grc20:"
17 RefundLane = "refund"
18 maxInt64 = 1<<63 - 1
19)
20
21type Ledger struct {
22 Funded int64
23 Available int64
24 Reserved int64
25 Claimable int64
26 Paid int64
27}
28
29// AssertConserved checks that all balances are non-negative and account for all funding.
30func (l Ledger) AssertConserved() {
31 total := Add(Add(l.Available, l.Reserved), Add(l.Claimable, l.Paid))
32 if l.Funded != total {
33 panic("ledger does not conserve funds")
34 }
35}
36
37type SpendCheck struct {
38 Allowed bool
39 Amount int64
40 Available int64
41 MaxAllowed int64
42 Shortfall int64
43 BindingConstraint string
44 ItemRoom int64
45 PeriodRoom int64
46 PoolRoom int64
47}
48
49// EvaluateSpend reports the raw available balance and the room under each
50// limit. Ties favor the item cap, then the period cap, then the pool.
51func EvaluateSpend(available, reserveFloor int64, canBreachFloor bool, itemCap, periodCap, periodUsed, amount int64) SpendCheck {
52 RequirePositive(amount)
53 if available < 0 || reserveFloor < 0 || itemCap < 0 || periodCap < 0 || periodUsed < 0 {
54 panic("spending limits and balances must be non-negative")
55 }
56 check := SpendCheck{
57 Amount: amount,
58 Available: available,
59 ItemRoom: itemCap,
60 PeriodRoom: nonnegative(periodCap - periodUsed),
61 PoolRoom: available,
62 }
63 if !canBreachFloor {
64 check.PoolRoom = nonnegative(available - reserveFloor)
65 }
66 check.MaxAllowed = min64(min64(check.ItemRoom, check.PeriodRoom), check.PoolRoom)
67 check.Allowed = amount <= check.MaxAllowed
68 if check.Allowed {
69 return check
70 }
71 check.Shortfall = amount - check.MaxAllowed
72 switch {
73 case check.MaxAllowed == check.ItemRoom:
74 check.BindingConstraint = "item_cap"
75 case check.MaxAllowed == check.PeriodRoom:
76 check.BindingConstraint = "period_cap"
77 case amount > available:
78 check.BindingConstraint = "shared_balance"
79 default:
80 check.BindingConstraint = "reserve_floor"
81 }
82 return check
83}
84
85func min64(a, b int64) int64 {
86 if a < b {
87 return a
88 }
89 return b
90}
91
92func nonnegative(n int64) int64 {
93 if n < 0 {
94 return 0
95 }
96 return n
97}
98
99func Add(a, b int64) int64 {
100 if a < 0 || b < 0 || a > maxInt64-b {
101 panic("amount or height overflow")
102 }
103 return a + b
104}
105
106func Subtract(a, b int64) int64 {
107 if b < 0 || a < b {
108 panic("amount underflow")
109 }
110 return a - b
111}
112
113func RequirePositive(amount int64) {
114 if amount <= 0 {
115 panic("amount must be positive")
116 }
117}
118
119func (l Ledger) Fund(amount int64) Ledger {
120 RequirePositive(amount)
121 l.Funded = Add(l.Funded, amount)
122 l.Available = Add(l.Available, amount)
123 return l
124}
125
126func (l Ledger) Reserve(amount int64) Ledger {
127 RequirePositive(amount)
128 l.Available = Subtract(l.Available, amount)
129 l.Reserved = Add(l.Reserved, amount)
130 return l
131}
132
133func (l Ledger) Approve(amount int64) Ledger {
134 RequirePositive(amount)
135 l.Reserved = Subtract(l.Reserved, amount)
136 l.Claimable = Add(l.Claimable, amount)
137 return l
138}
139
140func (l Ledger) Release(amount int64) Ledger {
141 RequirePositive(amount)
142 l.Reserved = Subtract(l.Reserved, amount)
143 l.Available = Add(l.Available, amount)
144 return l
145}
146
147func (l Ledger) RefundAvailable() Ledger {
148 l.Claimable = Add(l.Claimable, l.Available)
149 l.Available = 0
150 return l
151}
152
153func (l Ledger) Pay(amount int64) Ledger {
154 RequirePositive(amount)
155 l.Claimable = Subtract(l.Claimable, amount)
156 l.Paid = Add(l.Paid, amount)
157 return l
158}
159
160func PeriodAt(height, start, periodBlocks int64) int64 {
161 if start < 0 || height < start || periodBlocks <= 0 {
162 panic("invalid period")
163 }
164 return (height - start) / periodBlocks
165}
166
167func CheckDeadline(height, deadline, maxHold int64) {
168 if height < 0 || deadline <= height || deadline-height > maxHold {
169 panic("deadline outside reservation window")
170 }
171}
172
173func RequireAddress(addr address) {
174 s := string(addr)
175 if len(s) != 40 || !strings.HasPrefix(s, "g1") {
176 panic("invalid Gno address")
177 }
178 hrp, data, version, err := bech32.DecodeGeneric(s)
179 if err != nil || hrp != "g" || len(data) != 32 || version != bech32.Version0 {
180 panic("invalid Gno address")
181 }
182}
183
184func RequireDigest(digest string) {
185 if len(digest) != 64 || strings.ToLower(digest) != digest {
186 panic("evidence must be a lowercase SHA-256 digest")
187 }
188 if _, err := hex.DecodeString(digest); err != nil {
189 panic("evidence must be a lowercase SHA-256 digest")
190 }
191}
192
193func RequireLaneName(lane string) {
194 if lane == RefundLane || lane == "period" || lane == "check" {
195 panic("reserved policy lane name")
196 }
197 if !validKey(lane) {
198 panic("invalid policy lane name")
199 }
200}
201
202// RequireAsset accepts a bank denomination or a GRC20 registry key.
203func RequireAsset(asset string) {
204 if key, ok := strings.CutPrefix(asset, GRC20Prefix); ok {
205 if !validKey(key) {
206 panic("invalid GRC20 token key")
207 }
208 return
209 }
210 // Match the Gno bank grammar and the 256-byte realm path plus base denom limit.
211 if len(asset) < 3 || len(asset) > 274 ||
212 ((asset[0] < 'a' || asset[0] > 'z') && asset[0] != '/') {
213 panic("invalid native denomination")
214 }
215 for i := 1; i < len(asset); i++ {
216 c := asset[i]
217 if (c < 'a' || c > 'z') && (c < '0' || c > '9') && !strings.ContainsRune("_.:/-", rune(c)) {
218 panic("invalid native denomination")
219 }
220 }
221}
222
223func validKey(key string) bool {
224 if len(key) == 0 || len(key) > 32 || key[0] < 'a' || key[0] > 'z' {
225 return false
226 }
227 for i := 1; i < len(key); i++ {
228 c := key[i]
229 if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' && c != '-' {
230 return false
231 }
232 }
233 return true
234}
235
236// RequireMemo accepts a single line of up to 80 printable UTF-8 bytes.
237func RequireMemo(memo string) {
238 if len(memo) > 80 || !utf8.ValidString(memo) {
239 panic("memo must be valid UTF-8 and at most 80 bytes")
240 }
241 for _, r := range memo {
242 if !unicode.IsPrint(r) || strings.ContainsRune("|[]<>", r) {
243 panic("memo contains a control or unsupported Markdown character")
244 }
245 }
246}
247
248// EvidenceCommitment binds a salted proof digest to its program and item.
249func EvidenceCommitment(programID int64, lane string, itemID int64, proofDigest string) string {
250 RequireDigest(proofDigest)
251 payload := "shared-budget/v1\n" + strconv.FormatInt(programID, 10) + "\n" +
252 lane + "\n" + strconv.FormatInt(itemID, 10) + "\n" + proofDigest + "\n"
253 hash := sha256.Sum256([]byte(payload))
254 return hex.EncodeToString(hash[:])
255}
256
257// ParsePolicyViewPath reads programID or programID/itemID for policy renders.
258func ParsePolicyViewPath(path string) (int64, int64) {
259 parts := strings.SplitN(strings.TrimPrefix(path, ":"), "/", 3)
260 programID, err := strconv.ParseInt(parts[0], 10, 64)
261 if err != nil || programID <= 0 {
262 return 0, 0
263 }
264 if len(parts) == 1 {
265 return programID, 0
266 }
267 itemID, err := strconv.ParseInt(parts[1], 10, 64)
268 if len(parts) != 2 || err != nil || itemID <= 0 {
269 return 0, 0
270 }
271 return programID, itemID
272}
273
274// ParsePolicyLanePath accepts programID, programID/lane, and
275// programID/lane/itemID. The legacy programID/itemID route leaves lane empty.
276func ParsePolicyLanePath(path string) (int64, string, int64) {
277 parts := strings.SplitN(strings.TrimPrefix(path, ":"), "/", 4)
278 if len(parts) > 3 {
279 return 0, "", 0
280 }
281 if len(parts) == 1 || (len(parts) == 2 && !validKey(parts[1])) {
282 programID, itemID := ParsePolicyViewPath(path)
283 return programID, "", itemID
284 }
285 programID, err := strconv.ParseInt(parts[0], 10, 64)
286 lane := parts[1]
287 if err != nil || programID <= 0 || !validKey(lane) {
288 return 0, "", 0
289 }
290 if len(parts) == 2 {
291 return programID, lane, 0
292 }
293 itemID, err := strconv.ParseInt(parts[2], 10, 64)
294 if err != nil || itemID <= 0 {
295 return 0, "", 0
296 }
297 return programID, lane, itemID
298}
299
300// PolicyLaneKey identifies a lane in a policy realm's configuration tree.
301func PolicyLaneKey(programID int64, lane string) string {
302 return strconv.FormatInt(programID, 10) + "/" + lane
303}