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
323
|
package ingest
import (
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/json"
"github.com/Fuwn/plutia/internal/config"
"github.com/Fuwn/plutia/internal/storage"
"github.com/Fuwn/plutia/internal/types"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
func TestThinResolveStateCacheTTL(t *testing.T) {
did := "did:plc:thin-a"
logRecords := signedDIDLog(t, did, 2)
upstream := newThinUpstream(t, map[string][]types.ExportRecord{did: logRecords})
defer upstream.close()
store, svc, cleanup := newThinService(t, upstream.url, time.Hour, 10)
defer cleanup()
if _, err := svc.ResolveState(context.Background(), did); err != nil {
t.Fatalf("first resolve: %v", err)
}
stats := svc.Stats()
if stats.ThinCacheMisses != 1 || stats.ThinCacheHits != 0 {
t.Fatalf("unexpected stats after first resolve: %+v", stats)
}
if _, err := svc.ResolveState(context.Background(), did); err != nil {
t.Fatalf("second resolve: %v", err)
}
stats = svc.Stats()
if stats.ThinCacheMisses != 1 || stats.ThinCacheHits != 1 {
t.Fatalf("unexpected stats after second resolve: %+v", stats)
}
if got := upstream.hitCount(did); got != 1 {
t.Fatalf("upstream calls mismatch after cache hit: got %d want 1", got)
}
meta, ok, err := store.GetThinCacheMeta(did)
if err != nil || !ok {
t.Fatalf("load thin meta: ok=%v err=%v", ok, err)
}
meta.LastVerified = time.Now().UTC().Add(-2 * time.Hour)
if err := store.PutThinCacheMeta(meta); err != nil {
t.Fatalf("expire meta: %v", err)
}
if _, err := svc.ResolveState(context.Background(), did); err != nil {
t.Fatalf("third resolve: %v", err)
}
stats = svc.Stats()
if stats.ThinCacheMisses != 2 || stats.ThinCacheHits != 1 {
t.Fatalf("unexpected stats after ttl refresh: %+v", stats)
}
if got := upstream.hitCount(did); got != 2 {
t.Fatalf("upstream calls mismatch after ttl refresh: got %d want 2", got)
}
}
func TestThinResolveStateEvictsLRU(t *testing.T) {
didA := "did:plc:thin-1"
didB := "did:plc:thin-2"
didC := "did:plc:thin-3"
upstream := newThinUpstream(t, map[string][]types.ExportRecord{
didA: signedDIDLog(t, didA, 1),
didB: signedDIDLog(t, didB, 1),
didC: signedDIDLog(t, didC, 1),
})
defer upstream.close()
store, svc, cleanup := newThinService(t, upstream.url, 24*time.Hour, 2)
defer cleanup()
for _, did := range []string{didA, didB} {
if _, err := svc.ResolveState(context.Background(), did); err != nil {
t.Fatalf("resolve %s: %v", did, err)
}
}
if _, err := svc.ResolveState(context.Background(), didA); err != nil {
t.Fatalf("refresh didA access: %v", err)
}
if _, err := svc.ResolveState(context.Background(), didC); err != nil {
t.Fatalf("resolve didC: %v", err)
}
if _, ok, err := store.GetState(didB); err != nil || ok {
t.Fatalf("didB expected eviction: ok=%v err=%v", ok, err)
}
for _, did := range []string{didA, didC} {
if _, ok, err := store.GetState(did); err != nil || !ok {
t.Fatalf("did %s expected cached: ok=%v err=%v", did, ok, err)
}
}
stats := svc.Stats()
if stats.ThinEvictions != 1 {
t.Fatalf("evictions mismatch: got %d want 1", stats.ThinEvictions)
}
if stats.ThinCacheCount != 2 || stats.DIDCount != 2 {
t.Fatalf("cache count mismatch: %+v", stats)
}
}
func TestThinResolveStateRejectsInvalidChain(t *testing.T) {
did := "did:plc:thin-invalid"
ops := signedDIDLog(t, did, 2)
var second map[string]any
if err := json.Unmarshal(ops[1].Operation, &second); err != nil {
t.Fatalf("decode op: %v", err)
}
second["prev"] = "sha256:invalid"
rawSecond, _ := json.Marshal(second)
ops[1].Operation = rawSecond
ops[1].CID = ""
upstream := newThinUpstream(t, map[string][]types.ExportRecord{did: ops})
defer upstream.close()
store, svc, cleanup := newThinService(t, upstream.url, time.Hour, 10)
defer cleanup()
if _, err := svc.ResolveState(context.Background(), did); err == nil {
t.Fatalf("expected invalid chain error")
}
if _, ok, err := store.GetState(did); err != nil || ok {
t.Fatalf("invalid chain should not be cached: ok=%v err=%v", ok, err)
}
}
func newThinService(t *testing.T, source string, ttl time.Duration, maxEntries int) (*storage.PebbleStore, *Service, func()) {
t.Helper()
tmp := t.TempDir()
dataDir := filepath.Join(tmp, "data")
if err := os.MkdirAll(dataDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
store, err := storage.OpenPebble(dataDir)
if err != nil {
t.Fatalf("open pebble: %v", err)
}
if err := store.SetMode(config.ModeThin); err != nil {
t.Fatalf("set mode: %v", err)
}
cfg := config.Default()
cfg.Mode = config.ModeThin
cfg.DataDir = dataDir
cfg.PLCSource = source
cfg.ThinCacheTTL = ttl
cfg.ThinCacheMaxEntries = maxEntries
cfg.VerifyPolicy = config.VerifyFull
svc := NewService(cfg, store, NewClient(source), nil, nil)
cleanup := func() {
svc.Close()
_ = store.Close()
}
return store, svc, cleanup
}
type thinUpstream struct {
t *testing.T
url string
srv *httptest.Server
mu sync.Mutex
logs map[string][]types.ExportRecord
hits map[string]int
}
func newThinUpstream(t *testing.T, logs map[string][]types.ExportRecord) *thinUpstream {
t.Helper()
u := &thinUpstream{
t: t,
logs: logs,
hits: map[string]int{},
}
u.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
path := strings.TrimPrefix(r.URL.Path, "/")
if !strings.HasSuffix(path, "/log") {
w.WriteHeader(http.StatusNotFound)
return
}
did := strings.TrimSuffix(path, "/log")
did = strings.TrimSpace(did)
if did == "" {
w.WriteHeader(http.StatusNotFound)
return
}
u.mu.Lock()
u.hits[did]++
records, ok := u.logs[did]
u.mu.Unlock()
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
type entry struct {
Operation json.RawMessage `json:"operation"`
CID string `json:"cid"`
CreatedAt string `json:"createdAt"`
Nullified bool `json:"nullified"`
}
out := make([]entry, 0, len(records))
for _, rec := range records {
out = append(out, entry{
Operation: rec.Operation,
CID: rec.CID,
CreatedAt: rec.CreatedAt,
Nullified: rec.Nullified,
})
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(out)
}))
u.url = u.srv.URL
return u
}
func (u *thinUpstream) hitCount(did string) int {
u.mu.Lock()
defer u.mu.Unlock()
return u.hits[did]
}
func (u *thinUpstream) close() {
u.srv.Close()
}
func signedDIDLog(t *testing.T, did string, length int) []types.ExportRecord {
t.Helper()
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("generate key: %v", err)
}
records := make([]types.ExportRecord, 0, length)
prev := ""
for i := 0; i < length; i++ {
unsigned := map[string]any{
"did": did,
"didDoc": map[string]any{"id": did, "seq": i + 1},
"publicKey": base64.RawURLEncoding.EncodeToString(pub),
}
if prev != "" {
unsigned["prev"] = prev
}
payload, _ := json.Marshal(unsigned)
canon, _ := types.CanonicalizeJSON(payload)
sig := ed25519.Sign(priv, canon)
op := map[string]any{}
for k, v := range unsigned {
op[k] = v
}
op["sigPayload"] = base64.RawURLEncoding.EncodeToString(canon)
op["sig"] = base64.RawURLEncoding.EncodeToString(sig)
raw, _ := json.Marshal(op)
parsed, err := types.ParseOperation(types.ExportRecord{
Seq: uint64(i + 1),
DID: did,
Operation: raw,
})
if err != nil {
t.Fatalf("parse operation: %v", err)
}
prev = parsed.CID
records = append(records, types.ExportRecord{
Seq: uint64(i + 1),
DID: did,
CID: parsed.CID,
CreatedAt: time.Now().UTC().Add(time.Duration(i) * time.Second).Format(time.RFC3339),
Operation: raw,
})
}
return records
}
|