store.gno
10.87 Kb · 377 lines
1package mandate
2
3import (
4 "chain"
5 "strconv"
6)
7
8// fanout is the number of entries per chunk, and of chunks per super-chunk.
9const fanout = 32
10
11// fixedList is an append-only list of strings of one fixed width, in two
12// levels of chunks. It holds values, never pointers to shared objects (on
13// chain, rewriting an array costs about 0.37M gas for every pointer to a
14// shared object it holds; docs/notes.md), and no array in it grows with the
15// list's length except supers, by one entry per fanout*fanout appends:
16// - tail: the newest N % fanout entries, inside the owner object;
17// - when tail is full it becomes a chunk, appended to the last
18// super-chunk (at most fanout chunks each);
19// - supers: the list of super-chunks.
20//
21// So an append rewrites the owner and its tail; every fanout appends it also
22// creates a chunk and rewrites one super-chunk (at most fanout pointers to
23// objects that only it holds); every fanout*fanout appends it rewrites
24// supers. set replaces an entry in place with one of the same width, so it
25// never changes the storage size. Appends happen only in transactions signed
26// with someone's own key (Subscribe, Offer), never under a session budget.
27type fixedList struct {
28 N int
29 tail []string // the newest N % fanout entries
30 supers []*superChunk // full chunks, fanout per super-chunk, oldest first
31}
32
33type superChunk struct {
34 chunks []*strChunk
35}
36
37type strChunk struct {
38 items []string
39}
40
41func (l *fixedList) add(s string) {
42 l.tail = append(l.tail, s)
43 l.N++
44 if len(l.tail) < fanout {
45 return
46 }
47 c := &strChunk{items: l.tail}
48 l.tail = nil
49 if n := len(l.supers); n == 0 || len(l.supers[n-1].chunks) == fanout {
50 l.supers = append(l.supers, &superChunk{chunks: []*strChunk{c}})
51 return
52 }
53 sc := l.supers[len(l.supers)-1]
54 sc.chunks = append(sc.chunks, c)
55}
56
57// at returns entry i (0 = oldest).
58func (l *fixedList) at(i int) string {
59 c := i / fanout
60 if c < l.N/fanout {
61 return l.supers[c/fanout].chunks[c%fanout].items[i%fanout]
62 }
63 return l.tail[i%fanout]
64}
65
66// set replaces entry i with s, which must have the same width.
67func (l *fixedList) set(i int, s string) {
68 c := i / fanout
69 if c < l.N/fanout {
70 l.supers[c/fanout].chunks[c%fanout].items[i%fanout] = s
71 return
72 }
73 l.tail[i%fanout] = s
74}
75
76// Supporter entries: the payer's 40-character address, the mandate id
77// padded to 10 digits, and one status character. Pull flips '0' to '1' at
78// a mandate's first payment and Cancel sets 'x', both in place.
79const (
80 statusUnpaid = '0'
81 statusPaid = '1'
82 statusCancelled = 'x'
83 entryWidth = 40 + 10 + 1
84)
85
86// entry is a decoded supporter entry.
87type entry struct {
88 Payer address
89 ID uint64 // mandate id
90 Status byte
91}
92
93func encodeEntry(payer address, id uint64, status byte) string {
94 return payer.String() + pad(id) + string(status)
95}
96
97func decodeEntry(s string) entry {
98 id, _ := strconv.ParseUint(s[40:50], 10, 64)
99 return entry{Payer: address(s[:40]), ID: id, Status: s[50]}
100}
101
102// setStatus rewrites the status character of entry i (same width).
103func (l *fixedList) setStatus(i int, status byte) {
104 s := l.at(i)
105 l.set(i, s[:50]+string(status))
106}
107
108// activeMandate returns the mandate an entry names if it is still in its
109// payer's active list (cancelled and replaced ones are not), or nil. It may
110// have expired: callers check isActive.
111func activeMandate(e entry) *Mandate {
112 if pr := payerOf(e.Payer); pr != nil {
113 for _, r := range pr.Active {
114 if r.ID == e.ID {
115 return r.M
116 }
117 }
118 }
119 return nil
120}
121
122// MaxActivePerPayer is how many active mandates one payer may hold: the
123// chain allows 16 sessions per account (tm2 std.MaxSessionsPerAccount), and
124// each active mandate needs its own session key.
125const MaxActivePerPayer = MaxSessionsPerWallet
126
127// Payer holds one payer's own lookups and nothing of anyone else's, so no
128// address can make another payer's Pull, Subscribe or Cancel read or write
129// more than the payer tree's depth.
130// - Active: the payer's current mandates, at most MaxActivePerPayer that
131// are not expired. Cancel removes an entry at once; an expired entry is
132// removed at the payer's next Subscribe. Each entry carries the session
133// address and plan id inline, so finding a mandate reads one small array
134// and loads only the mandate found.
135// - Head: the payer's newest mandate; older ones follow through
136// prevOfPayer (history, walked only by free reads).
137// - Credits: time the payer has paid for on a plan where they no longer
138// have an active mandate (cancelled by either side, or expired and
139// pruned), at most MaxCreditsPerPayer, each still in the future. A new
140// mandate for that plan starts when the credit ends, so paid time is
141// not lost or charged twice, unless 16 credits are already held (see
142// MaxCreditsPerPayer for who can then lose what).
143type Payer struct {
144 Active []activeRef
145 Head *Mandate
146 Credits []credit
147}
148
149// credit is paid time kept for a plan: the payer is covered until Until.
150type credit struct {
151 PlanID uint64
152 Until int64
153}
154
155// MaxCreditsPerPayer bounds a payer's kept credits: 16 plans left while
156// each is still paid ahead. At the bound, the payer's own Cancel or expiry
157// lets the credit ending soonest give way to a later one (that plan's time
158// is lost); a payee's Cancel never evicts: its new credit is not kept.
159const MaxCreditsPerPayer = 16
160
161type activeRef struct {
162 Session address
163 PlanID uint64
164 ID uint64 // mandate id, so a supporter entry resolves without loading mandates
165 M *Mandate
166}
167
168// payerOf returns a copy of the payer's record, or nil. Records are stored
169// by value (no heap item, about 400 bytes less per payer); after changing
170// one, write it back with save.
171func payerOf(a address) *Payer {
172 v := payers.Get(a.String())
173 if v == nil {
174 return nil
175 }
176 pr := v.(Payer)
177 return &pr
178}
179
180func (pr *Payer) save(a address) { payers.Set(a.String(), *pr) }
181
182// activeBySession returns the payer's active-list mandate for this session
183// key (it may have expired but not been pruned yet), or nil.
184func activeBySession(payer, sess address) *Mandate {
185 if pr := payerOf(payer); pr != nil {
186 for _, r := range pr.Active {
187 if r.Session == sess {
188 return r.M
189 }
190 }
191 }
192 return nil
193}
194
195// activeByPlan returns the payer's active-list mandate for the plan, or nil.
196func activeByPlan(payer address, planID uint64) *Mandate {
197 if pr := payerOf(payer); pr != nil {
198 for _, r := range pr.Active {
199 if r.PlanID == planID {
200 return r.M
201 }
202 }
203 }
204 return nil
205}
206
207// removeActive drops m's entry from the payer's active list.
208func (pr *Payer) removeActive(m *Mandate) {
209 out := make([]activeRef, 0, len(pr.Active))
210 for _, r := range pr.Active {
211 if r.M != m {
212 out = append(out, r)
213 }
214 }
215 pr.Active = out
216}
217
218// pruneExpired drops expired entries from the active list (payer is the
219// record's owner, for events). The paid time of an expired mandate for
220// planID, the plan being subscribed to, is returned directly, so nothing in
221// the same prune can evict it; every other expired mandate's paid time is
222// kept as a credit for its plan.
223func (pr *Payer) pruneExpired(payer address, planID uint64, now int64) int64 {
224 keep := 0
225 for _, r := range pr.Active {
226 if r.M.isActive(now) {
227 keep++
228 }
229 }
230 if keep == len(pr.Active) {
231 return 0
232 }
233 var own int64
234 out := make([]activeRef, 0, keep)
235 for _, r := range pr.Active {
236 if r.M.isActive(now) {
237 out = append(out, r)
238 continue
239 }
240 var kept int64
241 if r.PlanID == planID {
242 if t := r.M.paidThrough(); t > now {
243 own, kept = t, t
244 }
245 } else {
246 kept = pr.keepCredit(payer, r.PlanID, r.M.paidThrough(), now, true)
247 }
248 chain.Emit("MandatePruned",
249 "mandate", utoa(r.ID),
250 "plan", utoa(r.PlanID),
251 "payer", payer.String(),
252 "kept", itoa(kept),
253 )
254 }
255 pr.Active = out
256 return own
257}
258
259// pruneCredits drops credits that have run out.
260func (pr *Payer) pruneCredits(now int64) {
261 keep := 0
262 for _, c := range pr.Credits {
263 if c.Until > now {
264 keep++
265 }
266 }
267 if keep == len(pr.Credits) {
268 return
269 }
270 out := make([]credit, 0, keep)
271 for _, c := range pr.Credits {
272 if c.Until > now {
273 out = append(out, c)
274 }
275 }
276 pr.Credits = out
277}
278
279// keepCredit records that the payer is paid on the plan until `until`
280// (nothing if that is not in the future). One credit per plan, the later
281// time wins. At MaxCreditsPerPayer: with evict (the payer's own Cancel, or
282// the expiry prune at the payer's own Subscribe), the credit ending soonest
283// gives way if this one ends later; without evict (a payee's Cancel), this
284// one is not kept, so no third party can remove a credit the payer holds.
285//
286// It returns the time kept (0 if none) and emits CreditDropped for a credit
287// it pushes out.
288func (pr *Payer) keepCredit(payer address, planID uint64, until, now int64, evict bool) int64 {
289 if until <= now {
290 return 0
291 }
292 pr.pruneCredits(now)
293 // A plan has a credit only while the payer has no active mandate for it
294 // (Subscribe uses it up), so this is a guard, not a path taken today.
295 for i := range pr.Credits {
296 if pr.Credits[i].PlanID == planID {
297 if until > pr.Credits[i].Until {
298 pr.Credits[i] = credit{PlanID: planID, Until: until}
299 }
300 return pr.Credits[i].Until
301 }
302 }
303 if len(pr.Credits) < MaxCreditsPerPayer {
304 pr.Credits = append(pr.Credits, credit{PlanID: planID, Until: until})
305 return until
306 }
307 if !evict {
308 return 0
309 }
310 soonest := 0
311 for i := range pr.Credits {
312 if pr.Credits[i].Until < pr.Credits[soonest].Until {
313 soonest = i
314 }
315 }
316 if until <= pr.Credits[soonest].Until {
317 return 0
318 }
319 chain.Emit("CreditDropped",
320 "payer", payer.String(),
321 "plan", utoa(pr.Credits[soonest].PlanID),
322 "until", itoa(pr.Credits[soonest].Until),
323 )
324 pr.Credits[soonest] = credit{PlanID: planID, Until: until}
325 return until
326}
327
328// creditFor returns until when a kept credit covers the payer on the plan,
329// or 0. For reads; it changes nothing.
330func (pr *Payer) creditFor(planID uint64, now int64) int64 {
331 for _, c := range pr.Credits {
332 if c.PlanID == planID && c.Until > now {
333 return c.Until
334 }
335 }
336 return 0
337}
338
339// takeCredit removes the plan's credit and returns until when it covered
340// the payer, or 0 if there was none still in the future.
341func (pr *Payer) takeCredit(planID uint64, now int64) int64 {
342 pr.pruneCredits(now)
343 for i, c := range pr.Credits {
344 if c.PlanID == planID {
345 out := make([]credit, 0, len(pr.Credits)-1)
346 out = append(out, pr.Credits[:i]...)
347 pr.Credits = append(out, pr.Credits[i+1:]...)
348 return c.Until
349 }
350 }
351 return 0
352}
353
354// latestBySession returns the payer's newest mandate for this session key,
355// active or not, walking the history when it is no longer active. For free
356// reads only.
357func latestBySession(payer, sess address) *Mandate {
358 if m := activeBySession(payer, sess); m != nil {
359 return m
360 }
361 if pr := payerOf(payer); pr != nil {
362 for m := pr.Head; m != nil; m = m.prevOfPayer {
363 if m.Session == sess {
364 return m
365 }
366 }
367 }
368 return nil
369}
370
371// payerHead returns the payer's newest mandate.
372func payerHead(payer address) *Mandate {
373 if pr := payerOf(payer); pr != nil {
374 return pr.Head
375 }
376 return nil
377}