-
Notifications
You must be signed in to change notification settings - Fork 212
/
store.go
396 lines (343 loc) · 10.4 KB
/
store.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package datastore
import (
"errors"
"fmt"
"sync"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/spacemeshos/go-spacemesh/codec"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/sql"
"github.com/spacemeshos/go-spacemesh/sql/activesets"
"github.com/spacemeshos/go-spacemesh/sql/atxs"
"github.com/spacemeshos/go-spacemesh/sql/ballots"
"github.com/spacemeshos/go-spacemesh/sql/blocks"
"github.com/spacemeshos/go-spacemesh/sql/identities"
"github.com/spacemeshos/go-spacemesh/sql/poets"
"github.com/spacemeshos/go-spacemesh/sql/proposals"
"github.com/spacemeshos/go-spacemesh/sql/transactions"
)
type VrfNonceKey struct {
ID types.NodeID
Epoch types.EpochID
}
// CachedDB is simply a database injected with cache.
type CachedDB struct {
*sql.Database
logger log.Log
atxHdrCache *lru.Cache[types.ATXID, *types.ActivationTxHeader]
vrfNonceCache *lru.Cache[VrfNonceKey, *types.VRFPostIndex]
// used to coordinate db update and cache
mu sync.Mutex
malfeasanceCache *lru.Cache[types.NodeID, *types.MalfeasanceProof]
}
type Config struct {
ATXSize int `mapstructure:"atx-size"`
MalfeasenceSize int `mapstructure:"malfeasence-size"`
}
func DefaultConfig() Config {
return Config{
ATXSize: 50_000,
MalfeasenceSize: 1_000,
}
}
type cacheOpts struct {
cfg Config
}
type Opt func(*cacheOpts)
func WithConfig(cfg Config) Opt {
return func(o *cacheOpts) {
o.cfg = cfg
}
}
// NewCachedDB create an instance of a CachedDB.
func NewCachedDB(db *sql.Database, lg log.Log, opts ...Opt) *CachedDB {
o := cacheOpts{cfg: DefaultConfig()}
for _, opt := range opts {
opt(&o)
}
lg.With().Info("initialized datastore", log.Any("config", o.cfg))
atxHdrCache, err := lru.New[types.ATXID, *types.ActivationTxHeader](o.cfg.ATXSize)
if err != nil {
lg.Fatal("failed to create atx cache", err)
}
malfeasanceCache, err := lru.New[types.NodeID, *types.MalfeasanceProof](o.cfg.MalfeasenceSize)
if err != nil {
lg.Fatal("failed to create malfeasance cache", err)
}
vrfNonceCache, err := lru.New[VrfNonceKey, *types.VRFPostIndex](o.cfg.ATXSize)
if err != nil {
lg.Fatal("failed to create vrf nonce cache", err)
}
return &CachedDB{
Database: db,
logger: lg,
atxHdrCache: atxHdrCache,
malfeasanceCache: malfeasanceCache,
vrfNonceCache: vrfNonceCache,
}
}
func (db *CachedDB) MalfeasanceCacheSize() int {
return db.malfeasanceCache.Len()
}
// IsMalicious returns true if the NodeID is malicious.
func (db *CachedDB) IsMalicious(id types.NodeID) (bool, error) {
if id == types.EmptyNodeID {
db.logger.Fatal("invalid argument to IsMalicious")
}
db.mu.Lock()
defer db.mu.Unlock()
if proof, ok := db.malfeasanceCache.Get(id); ok {
if proof == nil {
return false, nil
} else {
return true, nil
}
}
bad, err := identities.IsMalicious(db, id)
if err != nil {
return false, err
}
if !bad {
db.malfeasanceCache.Add(id, nil)
}
return bad, nil
}
// GetMalfeasanceProof gets the malfeasance proof associated with the NodeID.
func (db *CachedDB) GetMalfeasanceProof(id types.NodeID) (*types.MalfeasanceProof, error) {
if id == types.EmptyNodeID {
db.logger.Fatal("invalid argument to GetMalfeasanceProof")
}
db.mu.Lock()
defer db.mu.Unlock()
if proof, ok := db.malfeasanceCache.Get(id); ok {
if proof == nil {
return nil, sql.ErrNotFound
}
return proof, nil
}
proof, err := identities.GetMalfeasanceProof(db.Database, id)
if err != nil && err != sql.ErrNotFound {
return nil, err
}
db.malfeasanceCache.Add(id, proof)
return proof, err
}
func (db *CachedDB) CacheMalfeasanceProof(id types.NodeID, proof *types.MalfeasanceProof) {
if id == types.EmptyNodeID {
db.logger.Fatal("invalid argument to CacheMalfeasanceProof")
}
db.mu.Lock()
defer db.mu.Unlock()
db.malfeasanceCache.Add(id, proof)
}
// VRFNonce returns the VRF nonce of for the given node in the given epoch. This function is thread safe and will return an error if the
// nonce is not found in the ATX DB.
func (db *CachedDB) VRFNonce(id types.NodeID, epoch types.EpochID) (types.VRFPostIndex, error) {
key := VrfNonceKey{id, epoch}
if nonce, ok := db.vrfNonceCache.Get(key); ok {
return *nonce, nil
}
nonce, err := atxs.VRFNonce(db, id, epoch)
if err != nil {
return types.VRFPostIndex(0), err
}
db.vrfNonceCache.Add(key, &nonce)
return nonce, nil
}
// GetAtxHeader returns the ATX header by the given ID. This function is thread safe and will return an error if the ID
// is not found in the ATX DB.
func (db *CachedDB) GetAtxHeader(id types.ATXID) (*types.ActivationTxHeader, error) {
if id == types.EmptyATXID {
return nil, errors.New("trying to fetch empty atx id")
}
if atxHeader, gotIt := db.atxHdrCache.Get(id); gotIt {
return atxHeader, nil
}
return db.getAndCacheHeader(id)
}
// GetFullAtx returns the full atx struct of the given atxId id, it returns an error if the full atx cannot be found
// in all databases.
func (db *CachedDB) GetFullAtx(id types.ATXID) (*types.VerifiedActivationTx, error) {
if id == types.EmptyATXID {
return nil, errors.New("trying to fetch empty atx id")
}
atx, err := atxs.Get(db, id)
if err != nil {
return nil, fmt.Errorf("get ATXs from DB: %w", err)
}
db.atxHdrCache.Add(id, getHeader(atx))
return atx, nil
}
// getAndCacheHeader fetches the full atx struct from the database, caches it and returns the cached header.
func (db *CachedDB) getAndCacheHeader(id types.ATXID) (*types.ActivationTxHeader, error) {
_, err := db.GetFullAtx(id)
if err != nil {
return nil, err
}
atxHeader, gotIt := db.atxHdrCache.Get(id)
if !gotIt {
return nil, fmt.Errorf("inconsistent state: failed to get atx header: %w", err)
}
return atxHeader, nil
}
// GetEpochWeight returns the total weight of ATXs targeting the given epochID.
func (db *CachedDB) GetEpochWeight(epoch types.EpochID) (uint64, []types.ATXID, error) {
var (
weight uint64
ids []types.ATXID
)
if err := db.IterateEpochATXHeaders(epoch, func(header *types.ActivationTxHeader) error {
weight += header.GetWeight()
ids = append(ids, header.ID)
return nil
}); err != nil {
return 0, nil, err
}
return weight, ids, nil
}
// IterateEpochATXHeaders iterates over ActivationTxs that target an epoch.
func (db *CachedDB) IterateEpochATXHeaders(epoch types.EpochID, iter func(*types.ActivationTxHeader) error) error {
ids, err := atxs.GetIDsByEpoch(db, epoch-1)
if err != nil {
return err
}
for _, id := range ids {
header, err := db.GetAtxHeader(id)
if err != nil {
return err
}
if err := iter(header); err != nil {
return err
}
}
return nil
}
func (db *CachedDB) IterateMalfeasanceProofs(iter func(types.NodeID, *types.MalfeasanceProof) error) error {
ids, err := identities.GetMalicious(db)
if err != nil {
return err
}
for _, id := range ids {
proof, err := db.GetMalfeasanceProof(id)
if err != nil {
return err
}
if err := iter(id, proof); err != nil {
return err
}
}
return nil
}
// GetLastAtx gets the last atx header of specified node ID.
func (db *CachedDB) GetLastAtx(nodeID types.NodeID) (*types.ActivationTxHeader, error) {
if atxid, err := atxs.GetLastIDByNodeID(db, nodeID); err != nil {
return nil, fmt.Errorf("no prev atx found: %w", err)
} else if atx, err := db.GetAtxHeader(atxid); err != nil {
return nil, fmt.Errorf("inconsistent state: failed to get atx header: %v", err)
} else {
return atx, nil
}
}
// GetEpochAtx gets the atx header of specified node ID published in the specified epoch.
func (db *CachedDB) GetEpochAtx(epoch types.EpochID, nodeID types.NodeID) (*types.ActivationTxHeader, error) {
vatx, err := atxs.GetByEpochAndNodeID(db, epoch, nodeID)
if err != nil {
return nil, fmt.Errorf("no epoch atx found: %w", err)
}
hdr := getHeader(vatx)
db.atxHdrCache.Add(vatx.ID(), hdr)
return hdr, nil
}
// IdentityExists returns true if this NodeID has published any ATX.
func (db *CachedDB) IdentityExists(nodeID types.NodeID) (bool, error) {
_, err := atxs.GetLastIDByNodeID(db, nodeID)
if err != nil {
if errors.Is(err, sql.ErrNotFound) {
return false, nil
}
return false, err
}
return true, nil
}
func (db *CachedDB) MaxHeightAtx() (types.ATXID, error) {
return atxs.GetIDWithMaxHeight(db, types.EmptyNodeID)
}
// Hint marks which DB should be queried for a certain provided hash.
type Hint string
// DB hints per DB.
const (
BallotDB Hint = "ballotDB"
BlockDB Hint = "blocksDB"
ProposalDB Hint = "proposalDB"
ATXDB Hint = "ATXDB"
TXDB Hint = "TXDB"
POETDB Hint = "POETDB"
Malfeasance Hint = "malfeasance"
ActiveSet Hint = "activeset"
)
// NewBlobStore returns a BlobStore.
func NewBlobStore(db *sql.Database) *BlobStore {
return &BlobStore{DB: db}
}
// BlobStore gets data as a blob to serve direct fetch requests.
type BlobStore struct {
DB *sql.Database
}
// Get gets an ATX as bytes by an ATX ID as bytes.
func (bs *BlobStore) Get(hint Hint, key []byte) ([]byte, error) {
switch hint {
case ATXDB:
return atxs.GetBlob(bs.DB, key)
case ProposalDB:
return proposals.GetBlob(bs.DB, key)
case BallotDB:
id := types.BallotID(types.BytesToHash(key).ToHash20())
blt, err := ballots.Get(bs.DB, id)
if err != nil {
return nil, fmt.Errorf("get ballot blob: %w", err)
}
data, err := codec.Encode(blt)
if err != nil {
return data, fmt.Errorf("serialize: %w", err)
}
return data, nil
case BlockDB:
id := types.BlockID(types.BytesToHash(key).ToHash20())
blk, err := blocks.Get(bs.DB, id)
if err != nil {
return nil, fmt.Errorf("get block: %w", err)
}
data, err := codec.Encode(blk)
if err != nil {
return data, fmt.Errorf("serialize: %w", err)
}
return data, nil
case TXDB:
return transactions.GetBlob(bs.DB, key)
case POETDB:
var ref types.PoetProofRef
copy(ref[:], key)
return poets.Get(bs.DB, ref)
case Malfeasance:
return identities.GetMalfeasanceBlob(bs.DB, key)
case ActiveSet:
return activesets.GetBlob(bs.DB, key)
}
return nil, fmt.Errorf("blob store not found %s", hint)
}
func getHeader(vatx *types.VerifiedActivationTx) *types.ActivationTxHeader {
return &types.ActivationTxHeader{
NIPostChallenge: vatx.NIPostChallenge,
Coinbase: vatx.Coinbase,
NumUnits: vatx.NumUnits,
EffectiveNumUnits: vatx.EffectiveNumUnits(),
VRFNonce: vatx.VRFNonce,
Received: vatx.Received(),
ID: vatx.ID(),
NodeID: vatx.SmesherID,
BaseTickHeight: vatx.BaseTickHeight(),
TickCount: vatx.TickCount(),
Golden: vatx.Golden(),
}
}