forked from kaspanet/kaspad
-
Notifications
You must be signed in to change notification settings - Fork 1
/
block_staging_shard.go
69 lines (60 loc) · 1.64 KB
/
block_staging_shard.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
package blockstore
import (
"github.com/catspa3/catspad/domain/consensus/model"
"github.com/catspa3/catspad/domain/consensus/model/externalapi"
)
type blockStagingShard struct {
store *blockStore
toAdd map[externalapi.DomainHash]*externalapi.DomainBlock
toDelete map[externalapi.DomainHash]struct{}
}
func (bs *blockStore) stagingShard(stagingArea *model.StagingArea) *blockStagingShard {
return stagingArea.GetOrCreateShard(bs.shardID, func() model.StagingShard {
return &blockStagingShard{
store: bs,
toAdd: make(map[externalapi.DomainHash]*externalapi.DomainBlock),
toDelete: make(map[externalapi.DomainHash]struct{}),
}
}).(*blockStagingShard)
}
func (bss *blockStagingShard) Commit(dbTx model.DBTransaction) error {
for hash, block := range bss.toAdd {
blockBytes, err := bss.store.serializeBlock(block)
if err != nil {
return err
}
err = dbTx.Put(bss.store.hashAsKey(&hash), blockBytes)
if err != nil {
return err
}
bss.store.cache.Add(&hash, block)
}
for hash := range bss.toDelete {
err := dbTx.Delete(bss.store.hashAsKey(&hash))
if err != nil {
return err
}
bss.store.cache.Remove(&hash)
}
err := bss.commitCount(dbTx)
if err != nil {
return err
}
return nil
}
func (bss *blockStagingShard) commitCount(dbTx model.DBTransaction) error {
count := bss.store.count(bss)
countBytes, err := bss.store.serializeBlockCount(count)
if err != nil {
return err
}
err = dbTx.Put(bss.store.countKey, countBytes)
if err != nil {
return err
}
bss.store.countCached = count
return nil
}
func (bss *blockStagingShard) isStaged() bool {
return len(bss.toAdd) != 0 || len(bss.toDelete) != 0
}