// Package budget provides accounting, spending limits, and presentation for a shared pool. package budget import ( "crypto/bech32" "crypto/sha256" "encoding/hex" "strconv" "strings" "unicode" "unicode/utf8" ) const ( Denom = "ugnot" GRC20Prefix = "grc20:" RefundLane = "refund" maxInt64 = 1<<63 - 1 ) type Ledger struct { Funded int64 Available int64 Reserved int64 Claimable int64 Paid int64 } // AssertConserved checks that all balances are non-negative and account for all funding. func (l Ledger) AssertConserved() { total := Add(Add(l.Available, l.Reserved), Add(l.Claimable, l.Paid)) if l.Funded != total { panic("ledger does not conserve funds") } } type SpendCheck struct { Allowed bool Amount int64 Available int64 MaxAllowed int64 Shortfall int64 BindingConstraint string ItemRoom int64 PeriodRoom int64 PoolRoom int64 } // EvaluateSpend reports the raw available balance and the room under each // limit. Ties favor the item cap, then the period cap, then the pool. func EvaluateSpend(available, reserveFloor int64, canBreachFloor bool, itemCap, periodCap, periodUsed, amount int64) SpendCheck { RequirePositive(amount) if available < 0 || reserveFloor < 0 || itemCap < 0 || periodCap < 0 || periodUsed < 0 { panic("spending limits and balances must be non-negative") } check := SpendCheck{ Amount: amount, Available: available, ItemRoom: itemCap, PeriodRoom: nonnegative(periodCap - periodUsed), PoolRoom: available, } if !canBreachFloor { check.PoolRoom = nonnegative(available - reserveFloor) } check.MaxAllowed = min64(min64(check.ItemRoom, check.PeriodRoom), check.PoolRoom) check.Allowed = amount <= check.MaxAllowed if check.Allowed { return check } check.Shortfall = amount - check.MaxAllowed switch { case check.MaxAllowed == check.ItemRoom: check.BindingConstraint = "item_cap" case check.MaxAllowed == check.PeriodRoom: check.BindingConstraint = "period_cap" case amount > available: check.BindingConstraint = "shared_balance" default: check.BindingConstraint = "reserve_floor" } return check } func min64(a, b int64) int64 { if a < b { return a } return b } func nonnegative(n int64) int64 { if n < 0 { return 0 } return n } func Add(a, b int64) int64 { if a < 0 || b < 0 || a > maxInt64-b { panic("amount or height overflow") } return a + b } func Subtract(a, b int64) int64 { if b < 0 || a < b { panic("amount underflow") } return a - b } func RequirePositive(amount int64) { if amount <= 0 { panic("amount must be positive") } } func (l Ledger) Fund(amount int64) Ledger { RequirePositive(amount) l.Funded = Add(l.Funded, amount) l.Available = Add(l.Available, amount) return l } func (l Ledger) Reserve(amount int64) Ledger { RequirePositive(amount) l.Available = Subtract(l.Available, amount) l.Reserved = Add(l.Reserved, amount) return l } func (l Ledger) Approve(amount int64) Ledger { RequirePositive(amount) l.Reserved = Subtract(l.Reserved, amount) l.Claimable = Add(l.Claimable, amount) return l } func (l Ledger) Release(amount int64) Ledger { RequirePositive(amount) l.Reserved = Subtract(l.Reserved, amount) l.Available = Add(l.Available, amount) return l } func (l Ledger) RefundAvailable() Ledger { l.Claimable = Add(l.Claimable, l.Available) l.Available = 0 return l } func (l Ledger) Pay(amount int64) Ledger { RequirePositive(amount) l.Claimable = Subtract(l.Claimable, amount) l.Paid = Add(l.Paid, amount) return l } func PeriodAt(height, start, periodBlocks int64) int64 { if start < 0 || height < start || periodBlocks <= 0 { panic("invalid period") } return (height - start) / periodBlocks } func CheckDeadline(height, deadline, maxHold int64) { if height < 0 || deadline <= height || deadline-height > maxHold { panic("deadline outside reservation window") } } func RequireAddress(addr address) { s := string(addr) if len(s) != 40 || !strings.HasPrefix(s, "g1") { panic("invalid Gno address") } hrp, data, version, err := bech32.DecodeGeneric(s) if err != nil || hrp != "g" || len(data) != 32 || version != bech32.Version0 { panic("invalid Gno address") } } func RequireDigest(digest string) { if len(digest) != 64 || strings.ToLower(digest) != digest { panic("evidence must be a lowercase SHA-256 digest") } if _, err := hex.DecodeString(digest); err != nil { panic("evidence must be a lowercase SHA-256 digest") } } func RequireLaneName(lane string) { if lane == RefundLane || lane == "period" || lane == "check" { panic("reserved policy lane name") } if !validKey(lane) { panic("invalid policy lane name") } } // RequireAsset accepts a bank denomination or a GRC20 registry key. func RequireAsset(asset string) { if key, ok := strings.CutPrefix(asset, GRC20Prefix); ok { if !validKey(key) { panic("invalid GRC20 token key") } return } // Match the Gno bank grammar and the 256-byte realm path plus base denom limit. if len(asset) < 3 || len(asset) > 274 || ((asset[0] < 'a' || asset[0] > 'z') && asset[0] != '/') { panic("invalid native denomination") } for i := 1; i < len(asset); i++ { c := asset[i] if (c < 'a' || c > 'z') && (c < '0' || c > '9') && !strings.ContainsRune("_.:/-", rune(c)) { panic("invalid native denomination") } } } func validKey(key string) bool { if len(key) == 0 || len(key) > 32 || key[0] < 'a' || key[0] > 'z' { return false } for i := 1; i < len(key); i++ { c := key[i] if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' && c != '-' { return false } } return true } // RequireMemo accepts a single line of up to 80 printable UTF-8 bytes. func RequireMemo(memo string) { if len(memo) > 80 || !utf8.ValidString(memo) { panic("memo must be valid UTF-8 and at most 80 bytes") } for _, r := range memo { if !unicode.IsPrint(r) || strings.ContainsRune("|[]<>", r) { panic("memo contains a control or unsupported Markdown character") } } } // EvidenceCommitment binds a salted proof digest to its program and item. func EvidenceCommitment(programID int64, lane string, itemID int64, proofDigest string) string { RequireDigest(proofDigest) payload := "shared-budget/v1\n" + strconv.FormatInt(programID, 10) + "\n" + lane + "\n" + strconv.FormatInt(itemID, 10) + "\n" + proofDigest + "\n" hash := sha256.Sum256([]byte(payload)) return hex.EncodeToString(hash[:]) } // ParsePolicyViewPath reads programID or programID/itemID for policy renders. func ParsePolicyViewPath(path string) (int64, int64) { parts := strings.SplitN(strings.TrimPrefix(path, ":"), "/", 3) programID, err := strconv.ParseInt(parts[0], 10, 64) if err != nil || programID <= 0 { return 0, 0 } if len(parts) == 1 { return programID, 0 } itemID, err := strconv.ParseInt(parts[1], 10, 64) if len(parts) != 2 || err != nil || itemID <= 0 { return 0, 0 } return programID, itemID } // ParsePolicyLanePath accepts programID, programID/lane, and // programID/lane/itemID. The legacy programID/itemID route leaves lane empty. func ParsePolicyLanePath(path string) (int64, string, int64) { parts := strings.SplitN(strings.TrimPrefix(path, ":"), "/", 4) if len(parts) > 3 { return 0, "", 0 } if len(parts) == 1 || (len(parts) == 2 && !validKey(parts[1])) { programID, itemID := ParsePolicyViewPath(path) return programID, "", itemID } programID, err := strconv.ParseInt(parts[0], 10, 64) lane := parts[1] if err != nil || programID <= 0 || !validKey(lane) { return 0, "", 0 } if len(parts) == 2 { return programID, lane, 0 } itemID, err := strconv.ParseInt(parts[2], 10, 64) if err != nil || itemID <= 0 { return 0, "", 0 } return programID, lane, itemID } // PolicyLaneKey identifies a lane in a policy realm's configuration tree. func PolicyLaneKey(programID int64, lane string) string { return strconv.FormatInt(programID, 10) + "/" + lane }