-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcaching_rev_status_resolver.go
322 lines (271 loc) · 8.45 KB
/
caching_rev_status_resolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package c_polygonid
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"slices"
"sync"
"time"
"github.com/dgraph-io/badger/v4"
"github.com/iden3/go-iden3-core/v2/w3c"
"github.com/iden3/go-merkletree-sql/v2"
"github.com/iden3/go-schema-processor/v2/verifiable"
"github.com/iden3/iden3comm/v2/resolvers"
)
type CredentialStatusOwner uint8
const (
CredentialStatusOwnerUnset CredentialStatusOwner = iota
CredentialStatusOwnerIssuer CredentialStatusOwner = iota
CredentialStatusOwnerUser CredentialStatusOwner = iota
)
var revStatusCacheMutex sync.RWMutex
const issuerStateTTL = 5 * time.Minute
func toHash(in *string) (merkletree.Hash, error) {
if in == nil || *in == "" {
return merkletree.HashZero, nil
}
h, err := merkletree.NewHashFromHex(*in)
if err != nil {
return merkletree.Hash{}, err
}
return *h, nil
}
func cacheKeyIssuerState(issuerDID *w3c.DID) string {
return fmt.Sprintf("issuer-state-%v", issuerDID.String())
}
func cacheKeyRevStatus(revTreeRoot merkletree.Hash,
credStatus verifiable.CredentialStatus) string {
return fmt.Sprintf("rev-status-%s-%s-%s-%d", hex.EncodeToString(revTreeRoot[:]),
credStatus.ID, credStatus.Type, credStatus.RevocationNonce)
}
func cacheKeyRevTreeEntries(revTreeRoot merkletree.Hash) string {
return fmt.Sprintf("rev-tree-entries-%s",
hex.EncodeToString(revTreeRoot[:]))
}
type treeStateEntry struct {
TreeState verifiable.TreeState `json:"treeState"`
CreatedAt time.Time `json:"createdAt"`
}
func putIssuerStateToCache(db *badger.DB, issuerDID *w3c.DID,
issuerState verifiable.TreeState) error {
key := []byte(cacheKeyIssuerState(issuerDID))
value, err := json.Marshal(treeStateEntry{
TreeState: issuerState,
CreatedAt: time.Now().UTC(),
})
if err != nil {
return err
}
return db.Update(func(txn *badger.Txn) error {
return txn.Set(key, value)
})
}
// may return badger.ErrKeyNotFound if state is not found in cache
func getIssuerStateFromCache(db *badger.DB,
issuerDID *w3c.DID) (verifiable.TreeState, time.Time, error) {
var stateEntry treeStateEntry
err := db.View(func(txn *badger.Txn) error {
itm, err2 := txn.Get([]byte(cacheKeyIssuerState(issuerDID)))
if err2 != nil {
return err2
}
return itm.Value(func(val []byte) error {
return json.Unmarshal(val, &stateEntry)
})
})
if err != nil {
return verifiable.TreeState{}, time.Time{}, err
}
return stateEntry.TreeState, stateEntry.CreatedAt, nil
}
type registryBuilder func(ctx context.Context, cfg PerChainConfig) (
*verifiable.CredentialStatusResolverRegistry, func(), error)
func resolveRevStatus(ctx context.Context, chainCfg PerChainConfig,
issuerDID, userDID *w3c.DID, credStatus verifiable.CredentialStatus,
regBuilder registryBuilder) (verifiable.RevocationStatus, error) {
if regBuilder == nil {
return verifiable.RevocationStatus{},
errors.New("[assertion] registry builder is null")
}
if userDID == nil {
return verifiable.RevocationStatus{}, errors.New("user DID is null")
}
resolversRegistry, registryCleanupFn, err := regBuilder(ctx, chainCfg)
if err != nil {
return verifiable.RevocationStatus{}, err
}
defer registryCleanupFn()
resolver, err := resolversRegistry.Get(credStatus.Type)
if err != nil {
return verifiable.RevocationStatus{}, err
}
ctx = verifiable.WithIssuerDID(ctx, issuerDID)
ctx = resolvers.WithSenderDID(ctx, userDID)
return resolver.Resolve(ctx, credStatus)
}
func resolveRevStatusAndCache(ctx context.Context, db *badger.DB,
chainCfg PerChainConfig, issuerDID, userDID *w3c.DID,
credStatus verifiable.CredentialStatus,
regBuilder registryBuilder) (verifiable.RevocationStatus, error) {
revStatus, err := resolveRevStatus(ctx, chainCfg, issuerDID, userDID,
credStatus, regBuilder)
if err != nil {
return verifiable.RevocationStatus{}, err
}
revStatusCacheMutex.Lock()
defer revStatusCacheMutex.Unlock()
var oldState verifiable.TreeState
var hasOldState bool
var oldRevTreeRoot merkletree.Hash
oldState, _, err = getIssuerStateFromCache(db, issuerDID)
if errors.Is(err, badger.ErrKeyNotFound) {
hasOldState = false
} else if err != nil {
return verifiable.RevocationStatus{}, err
} else {
hasOldState = true
oldRevTreeRoot, err = toHash(oldState.RevocationTreeRoot)
if err != nil {
return verifiable.RevocationStatus{}, err
}
}
var newRevTreeRoot merkletree.Hash
newRevTreeRoot, err = toHash(revStatus.Issuer.RevocationTreeRoot)
if err != nil {
return verifiable.RevocationStatus{}, err
}
if hasOldState && newRevTreeRoot != oldRevTreeRoot {
err = removeExpiredRevStatusFromCache(db, oldRevTreeRoot)
if err != nil {
return verifiable.RevocationStatus{}, err
}
}
err = putIssuerStateToCache(db, issuerDID, revStatus.Issuer)
if err != nil {
return verifiable.RevocationStatus{}, err
}
err = putRevProofToCache(db, newRevTreeRoot, credStatus, revStatus.MTP)
if err != nil {
return verifiable.RevocationStatus{}, err
}
return revStatus, nil
}
func removeExpiredRevStatusFromCache(db *badger.DB,
revTreeRoot merkletree.Hash) error {
treeEntriesKey := cacheKeyRevTreeEntries(revTreeRoot)
return db.Update(func(txn *badger.Txn) error {
ent, err := txn.Get([]byte(treeEntriesKey))
if errors.Is(err, badger.ErrKeyNotFound) {
return nil
} else if err != nil {
return err
}
var treeProofs []string
err = ent.Value(func(val []byte) error {
return json.Unmarshal(val, &treeProofs)
})
if err != nil {
return err
}
for _, k := range treeProofs {
err = txn.Delete([]byte(k))
if err != nil {
return err
}
}
return txn.Delete([]byte(treeEntriesKey))
})
}
func putRevProofToCache(db *badger.DB, revTreeRoot merkletree.Hash,
credStatus verifiable.CredentialStatus, revProof merkletree.Proof) error {
treeEntriesKey := cacheKeyRevTreeEntries(revTreeRoot)
revStatusKey := cacheKeyRevStatus(revTreeRoot, credStatus)
return db.Update(func(txn *badger.Txn) error {
var treeProofs []string
ent, err := txn.Get([]byte(treeEntriesKey))
if errors.Is(err, badger.ErrKeyNotFound) {
} else if err != nil {
return err
} else {
err = ent.Value(func(val []byte) error {
return json.Unmarshal(val, &treeProofs)
})
if err != nil {
return err
}
}
var val []byte
if !slices.Contains(treeProofs, revStatusKey) {
treeProofs = append(treeProofs, revStatusKey)
val, err = json.Marshal(treeProofs)
if err != nil {
return err
}
err = txn.Set([]byte(treeEntriesKey), val)
if err != nil {
return err
}
}
val, err = json.Marshal(revProof)
if err != nil {
return err
}
return txn.Set([]byte(revStatusKey), val)
})
}
func getRevProofFromCache(db *badger.DB, revTreeRoot merkletree.Hash,
credStatus verifiable.CredentialStatus) (merkletree.Proof, error) {
var revProof merkletree.Proof
err := db.View(func(txn *badger.Txn) error {
itm, err2 := txn.Get([]byte(cacheKeyRevStatus(revTreeRoot, credStatus)))
if err2 != nil {
return err2
}
return itm.Value(func(val []byte) error {
return json.Unmarshal(val, &revProof)
})
})
if err != nil {
return merkletree.Proof{}, err
}
return revProof, nil
}
func cachedResolve(ctx context.Context, cfg EnvConfig,
issuerDID, userDID *w3c.DID, credStatus verifiable.CredentialStatus,
regBuilder registryBuilder) (verifiable.RevocationStatus, error) {
cache, cacheCleanup, err := getCacheDB(cfg.CacheDir)
if err != nil {
// Cache engine is not available, so resolve without cache
return resolveRevStatus(ctx, cfg.ChainConfigs, issuerDID, userDID,
credStatus, regBuilder)
}
defer cacheCleanup()
if issuerDID == nil {
return verifiable.RevocationStatus{}, errors.New("issuer DID is null")
}
var revStatus verifiable.RevocationStatus
var createdAt time.Time
revStatus.Issuer, createdAt, err = getIssuerStateFromCache(cache, issuerDID)
if errors.Is(err, badger.ErrKeyNotFound) ||
(err == nil && createdAt.Before(time.Now().Add(-issuerStateTTL))) {
return resolveRevStatusAndCache(ctx, cache, cfg.ChainConfigs, issuerDID,
userDID, credStatus, regBuilder)
} else if err != nil {
return verifiable.RevocationStatus{}, err
}
var revTreeRoot merkletree.Hash
revTreeRoot, err = toHash(revStatus.Issuer.RevocationTreeRoot)
if err != nil {
return verifiable.RevocationStatus{}, err
}
revStatus.MTP, err = getRevProofFromCache(cache, revTreeRoot, credStatus)
if errors.Is(err, badger.ErrKeyNotFound) {
return resolveRevStatusAndCache(ctx, cache, cfg.ChainConfigs, issuerDID,
userDID, credStatus, regBuilder)
} else if err != nil {
return verifiable.RevocationStatus{}, err
}
return revStatus, nil
}