1 // MemStore is a Store implementation that
2 // keeps all blockchain state in memory.
4 // It is used in tests to avoid needing a database.
12 "github.com/bytom/protocol/bc/legacy"
13 "github.com/bytom/protocol/state"
16 // MemStore satisfies the Store interface.
17 type MemStore struct {
19 Blocks map[uint64]*legacy.Block
24 // New returns a new MemStore
25 func New() *MemStore {
26 return &MemStore{Blocks: make(map[uint64]*legacy.Block)}
29 func (m *MemStore) Height() uint64 {
33 return uint64(len(m.Blocks))
37 func (m *MemStore) SaveBlock(b *legacy.Block) error {
41 existing, ok := m.Blocks[b.Height]
42 if ok && existing.Hash() != b.Hash() {
43 return fmt.Errorf("already have a block at height %d", b.Height)
45 m.Blocks[b.Height] = b
49 func (m *MemStore) SaveSnapshot(ctx context.Context, height uint64, snapshot *state.Snapshot) error {
53 m.State = state.Copy(snapshot)
54 m.StateHeight = height
58 func (m *MemStore) GetBlock(height uint64) (*legacy.Block, error) {
61 b, ok := m.Blocks[height]
63 return nil, fmt.Errorf("memstore: no block at height %d", height)
68 func (m *MemStore) LatestSnapshot(context.Context) (*state.Snapshot, uint64, error) {
73 m.State = state.Empty()
75 return state.Copy(m.State), m.StateHeight, nil
78 func (m *MemStore) FinalizeBlock(context.Context, uint64) error { return nil }