budget.gno
6.06 Kb · 241 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 RefundLane = "refund"
17 maxInt64 = 1<<63 - 1
18)
19
20type Ledger struct {
21 Funded int64
22 Available int64
23 Reserved int64
24 Claimable int64
25 Paid int64
26}
27
28// AssertConserved checks that all balances are non-negative and account for all funding.
29func (l Ledger) AssertConserved() {
30 total := Add(Add(l.Available, l.Reserved), Add(l.Claimable, l.Paid))
31 if l.Funded != total {
32 panic("ledger does not conserve funds")
33 }
34}
35
36type SpendCheck struct {
37 Allowed bool
38 Amount int64
39 MaxAllowed int64
40 Shortfall int64
41 BindingConstraint string
42 ItemRoom int64
43 PeriodRoom int64
44 PoolRoom int64
45}
46
47// EvaluateSpend reports the tightest room, breaking ties in item, period, pool
48// order. A pool failure identifies a shortfall of cash before floor protection.
49func EvaluateSpend(available, reserveFloor int64, canBreachFloor bool, itemCap, periodCap, periodUsed, amount int64) SpendCheck {
50 RequirePositive(amount)
51 if available < 0 || reserveFloor < 0 || itemCap < 0 || periodCap < 0 || periodUsed < 0 {
52 panic("spending limits and balances must be non-negative")
53 }
54 check := SpendCheck{
55 Amount: amount,
56 ItemRoom: itemCap,
57 PeriodRoom: nonnegative(periodCap - periodUsed),
58 PoolRoom: available,
59 }
60 if !canBreachFloor {
61 check.PoolRoom = nonnegative(available - reserveFloor)
62 }
63 check.MaxAllowed = min64(min64(check.ItemRoom, check.PeriodRoom), check.PoolRoom)
64 check.Allowed = amount <= check.MaxAllowed
65 if check.Allowed {
66 return check
67 }
68 check.Shortfall = amount - check.MaxAllowed
69 switch {
70 case check.MaxAllowed == check.ItemRoom:
71 check.BindingConstraint = "item_cap"
72 case check.MaxAllowed == check.PeriodRoom:
73 check.BindingConstraint = "period_cap"
74 case amount > available:
75 check.BindingConstraint = "shared_balance"
76 default:
77 check.BindingConstraint = "reserve_floor"
78 }
79 return check
80}
81
82func min64(a, b int64) int64 {
83 if a < b {
84 return a
85 }
86 return b
87}
88
89func nonnegative(n int64) int64 {
90 if n < 0 {
91 return 0
92 }
93 return n
94}
95
96func Add(a, b int64) int64 {
97 if a < 0 || b < 0 || a > maxInt64-b {
98 panic("amount or height overflow")
99 }
100 return a + b
101}
102
103func Subtract(a, b int64) int64 {
104 if b < 0 || a < b {
105 panic("amount underflow")
106 }
107 return a - b
108}
109
110func RequirePositive(amount int64) {
111 if amount <= 0 {
112 panic("amount must be positive")
113 }
114}
115
116func (l Ledger) Fund(amount int64) Ledger {
117 RequirePositive(amount)
118 l.Funded = Add(l.Funded, amount)
119 l.Available = Add(l.Available, amount)
120 return l
121}
122
123func (l Ledger) Reserve(amount int64) Ledger {
124 RequirePositive(amount)
125 l.Available = Subtract(l.Available, amount)
126 l.Reserved = Add(l.Reserved, amount)
127 return l
128}
129
130func (l Ledger) Approve(amount int64) Ledger {
131 RequirePositive(amount)
132 l.Reserved = Subtract(l.Reserved, amount)
133 l.Claimable = Add(l.Claimable, amount)
134 return l
135}
136
137func (l Ledger) Release(amount int64) Ledger {
138 RequirePositive(amount)
139 l.Reserved = Subtract(l.Reserved, amount)
140 l.Available = Add(l.Available, amount)
141 return l
142}
143
144func (l Ledger) RefundAvailable() Ledger {
145 l.Claimable = Add(l.Claimable, l.Available)
146 l.Available = 0
147 return l
148}
149
150func (l Ledger) Pay(amount int64) Ledger {
151 RequirePositive(amount)
152 l.Claimable = Subtract(l.Claimable, amount)
153 l.Paid = Add(l.Paid, amount)
154 return l
155}
156
157func PeriodAt(height, start, periodBlocks int64) int64 {
158 if start < 0 || height < start || periodBlocks <= 0 {
159 panic("invalid period")
160 }
161 return (height - start) / periodBlocks
162}
163
164func CheckDeadline(height, deadline, maxHold int64) {
165 if height < 0 || deadline <= height || deadline-height > maxHold {
166 panic("deadline outside reservation window")
167 }
168}
169
170func RequireAddress(addr address) {
171 s := string(addr)
172 if len(s) != 40 || !strings.HasPrefix(s, "g1") {
173 panic("invalid Gno address")
174 }
175 hrp, data, version, err := bech32.DecodeGeneric(s)
176 if err != nil || hrp != "g" || len(data) != 32 || version != bech32.Version0 {
177 panic("invalid Gno address")
178 }
179}
180
181func RequireDigest(digest string) {
182 if len(digest) != 64 || strings.ToLower(digest) != digest {
183 panic("evidence must be a lowercase SHA-256 digest")
184 }
185 if _, err := hex.DecodeString(digest); err != nil {
186 panic("evidence must be a lowercase SHA-256 digest")
187 }
188}
189
190func RequireLaneName(lane string) {
191 if len(lane) == 0 || len(lane) > 32 || lane[0] < 'a' || lane[0] > 'z' {
192 panic("invalid policy lane name")
193 }
194 if lane == RefundLane || lane == "period" || lane == "check" {
195 panic("reserved policy lane name")
196 }
197 for i := 1; i < len(lane); i++ {
198 c := lane[i]
199 if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' && c != '-' {
200 panic("invalid policy lane name")
201 }
202 }
203}
204
205// RequireMemo accepts a single line of up to 80 printable UTF-8 bytes.
206func RequireMemo(memo string) {
207 if len(memo) > 80 || !utf8.ValidString(memo) {
208 panic("memo must be valid UTF-8 and at most 80 bytes")
209 }
210 for _, r := range memo {
211 if !unicode.IsPrint(r) || strings.ContainsRune("|[]<>", r) {
212 panic("memo contains a control or unsupported Markdown character")
213 }
214 }
215}
216
217// EvidenceCommitment binds a salted proof digest to its program and item.
218func EvidenceCommitment(programID int64, lane string, itemID int64, proofDigest string) string {
219 RequireDigest(proofDigest)
220 payload := "shared-budget/v1\n" + strconv.FormatInt(programID, 10) + "\n" +
221 lane + "\n" + strconv.FormatInt(itemID, 10) + "\n" + proofDigest + "\n"
222 hash := sha256.Sum256([]byte(payload))
223 return hex.EncodeToString(hash[:])
224}
225
226// ParsePolicyViewPath reads programID or programID/itemID for policy renders.
227func ParsePolicyViewPath(path string) (int64, int64) {
228 parts := strings.SplitN(strings.TrimPrefix(path, ":"), "/", 3)
229 programID, err := strconv.ParseInt(parts[0], 10, 64)
230 if err != nil || programID <= 0 {
231 return 0, 0
232 }
233 if len(parts) == 1 {
234 return programID, 0
235 }
236 itemID, err := strconv.ParseInt(parts[1], 10, 64)
237 if len(parts) != 2 || err != nil || itemID <= 0 {
238 return 0, 0
239 }
240 return programID, itemID
241}