OSDN Git Service

0be3df0248e9fe7979556d2674c5241542b1e997
[bytom/vapor.git] / database / store.go
1 package database
2
3 import (
4         "encoding/binary"
5         "encoding/json"
6         "fmt"
7         "time"
8
9         "github.com/golang/protobuf/proto"
10         log "github.com/sirupsen/logrus"
11
12         dbm "github.com/vapor/database/leveldb"
13         "github.com/vapor/database/storage"
14         "github.com/vapor/errors"
15         "github.com/vapor/protocol"
16         "github.com/vapor/protocol/bc"
17         "github.com/vapor/protocol/bc/types"
18         "github.com/vapor/protocol/state"
19 )
20
21 const (
22         // log module
23         logModule = "leveldb"
24         // the byte of colon(:)
25         colon = byte(0x3a)
26 )
27
28 const (
29         blockStore byte = iota
30         blockHashes
31         blockHeader
32         blockTransactons
33         mainChainIndex
34         txStatus
35         consensusResult
36 )
37
38 func loadBlockStoreStateJSON(db dbm.DB) *protocol.BlockStoreState {
39         bytes := db.Get([]byte{blockStore})
40         if bytes == nil {
41                 return nil
42         }
43
44         bsj := &protocol.BlockStoreState{}
45         if err := json.Unmarshal(bytes, bsj); err != nil {
46                 log.WithField("err", err).Panic("fail on unmarshal BlockStoreStateJSON")
47         }
48         return bsj
49 }
50
51 // A Store encapsulates storage for blockchain validation.
52 // It satisfies the interface protocol.Store, and provides additional
53 // methods for querying current data.
54 type Store struct {
55         db    dbm.DB
56         cache cache
57 }
58
59 func calcMainChainIndexPrefix(height uint64) []byte {
60         buf := [8]byte{}
61         binary.BigEndian.PutUint64(buf[:], height)
62         return append([]byte{mainChainIndex, colon}, buf[:]...)
63 }
64
65 func calcBlockHashesPrefix(height uint64) []byte {
66         buf := [8]byte{}
67         binary.BigEndian.PutUint64(buf[:], height)
68         return append([]byte{blockHashes, colon}, buf[:]...)
69 }
70
71 func calcBlockHeaderKey(hash *bc.Hash) []byte {
72         return append([]byte{blockHeader, colon}, hash.Bytes()...)
73 }
74
75 func calcBlockTransactionsKey(hash *bc.Hash) []byte {
76         return append([]byte{blockTransactons, colon}, hash.Bytes()...)
77 }
78
79 func calcTxStatusKey(hash *bc.Hash) []byte {
80         return append([]byte{txStatus, colon}, hash.Bytes()...)
81 }
82
83 func calcConsensusResultKey(seq uint64) []byte {
84         buf := [8]byte{}
85         binary.BigEndian.PutUint64(buf[:], seq)
86         return append([]byte{consensusResult, colon}, buf[:]...)
87 }
88
89 // GetBlockHeader return the block header by given hash
90 func GetBlockHeader(db dbm.DB, hash *bc.Hash) (*types.BlockHeader, error) {
91         binaryBlockHeader := db.Get(calcBlockHeaderKey(hash))
92         if binaryBlockHeader == nil {
93                 return nil, fmt.Errorf("There are no blockHeader with given hash %s", hash.String())
94         }
95
96         blockHeader := &types.BlockHeader{}
97         if err := blockHeader.UnmarshalText(binaryBlockHeader); err != nil {
98                 return nil, err
99         }
100         return blockHeader, nil
101 }
102
103 // GetBlockTransactions return the block transactions by given hash
104 func GetBlockTransactions(db dbm.DB, hash *bc.Hash) ([]*types.Tx, error) {
105         binaryBlockTxs := db.Get(calcBlockTransactionsKey(hash))
106         if binaryBlockTxs == nil {
107                 return nil, fmt.Errorf("There are no block transactions with given hash %s", hash.String())
108         }
109
110         block := &types.Block{}
111         if err := block.UnmarshalText(binaryBlockTxs); err != nil {
112                 return nil, err
113         }
114         return block.Transactions, nil
115 }
116
117 // GetBlockHashesByHeight return block hashes by given height
118 func GetBlockHashesByHeight(db dbm.DB, height uint64) ([]*bc.Hash, error) {
119         binaryHashes := db.Get(calcBlockHashesPrefix(height))
120         if binaryHashes == nil {
121                 return []*bc.Hash{}, nil
122         }
123
124         hashes := []*bc.Hash{}
125         if err := json.Unmarshal(binaryHashes, &hashes); err != nil {
126                 return nil, err
127         }
128         return hashes, nil
129 }
130
131 // GetMainChainHash return BlockHash by given height
132 func GetMainChainHash(db dbm.DB, height uint64) (*bc.Hash, error) {
133         binaryHash := db.Get(calcMainChainIndexPrefix(height))
134         if binaryHash == nil {
135                 return nil, fmt.Errorf("There are no BlockHash with given height %d", height)
136         }
137
138         hash := &bc.Hash{}
139         if err := hash.UnmarshalText(binaryHash); err != nil {
140                 return nil, err
141         }
142         return hash, nil
143 }
144
145 // GetConsensusResult return the vote result by given sequence
146 func GetConsensusResult(db dbm.DB, seq uint64) (*state.ConsensusResult, error) {
147         data := db.Get(calcConsensusResultKey(seq))
148         if data == nil {
149                 return nil, protocol.ErrNotFoundConsensusResult
150         }
151
152         consensusResult := new(state.ConsensusResult)
153         if err := json.Unmarshal(data, consensusResult); err != nil {
154                 return nil, errors.Wrap(err, "unmarshaling vote result")
155         }
156         return consensusResult, nil
157 }
158
159 // NewStore creates and returns a new Store object.
160 func NewStore(db dbm.DB) *Store {
161         fillBlockHeaderFn := func(hash *bc.Hash) (*types.BlockHeader, error) {
162                 return GetBlockHeader(db, hash)
163         }
164         fillBlockTxsFn := func(hash *bc.Hash) ([]*types.Tx, error) {
165                 return GetBlockTransactions(db, hash)
166         }
167
168         fillBlockHashesFn := func(height uint64) ([]*bc.Hash, error) {
169                 return GetBlockHashesByHeight(db, height)
170         }
171
172         fillMainChainHashFn := func(height uint64) (*bc.Hash, error) {
173                 return GetMainChainHash(db, height)
174         }
175
176         fillConsensusResultFn := func(seq uint64) (*state.ConsensusResult, error) {
177                 return GetConsensusResult(db, seq)
178         }
179
180         cache := newCache(fillBlockHeaderFn, fillBlockTxsFn, fillBlockHashesFn, fillMainChainHashFn, fillConsensusResultFn)
181         return &Store{
182                 db:    db,
183                 cache: cache,
184         }
185 }
186
187 // BlockExist check if the block is stored in disk
188 func (s *Store) BlockExist(hash *bc.Hash) bool {
189         _, err := s.cache.lookupBlockHeader(hash)
190         return err == nil
191 }
192
193 // GetBlock return the block by given hash
194 func (s *Store) GetBlock(hash *bc.Hash) (*types.Block, error) {
195         blockHeader, err := s.GetBlockHeader(hash)
196         if err != nil {
197                 return nil, err
198         }
199
200         txs, err := s.GetBlockTransactions(hash)
201         if err != nil {
202                 return nil, err
203         }
204
205         return &types.Block{
206                 BlockHeader:  *blockHeader,
207                 Transactions: txs,
208         }, nil
209 }
210
211 // GetBlockHeader return the BlockHeader by given hash
212 func (s *Store) GetBlockHeader(hash *bc.Hash) (*types.BlockHeader, error) {
213         return s.cache.lookupBlockHeader(hash)
214 }
215
216 // GetBlockTransactions return the Block transactions by given hash
217 func (s *Store) GetBlockTransactions(hash *bc.Hash) ([]*types.Tx, error) {
218         return s.cache.lookupBlockTxs(hash)
219 }
220
221 // GetBlockHashesByHeight return the block hash by the specified height
222 func (s *Store) GetBlockHashesByHeight(height uint64) ([]*bc.Hash, error) {
223         return s.cache.lookupBlockHashesByHeight(height)
224 }
225
226 // GetMainChainHash return the block hash by the specified height
227 func (s *Store) GetMainChainHash(height uint64) (*bc.Hash, error) {
228         return s.cache.lookupMainChainHash(height)
229 }
230
231 // GetStoreStatus return the BlockStoreStateJSON
232 func (s *Store) GetStoreStatus() *protocol.BlockStoreState {
233         return loadBlockStoreStateJSON(s.db)
234 }
235
236 // GetTransactionsUtxo will return all the utxo that related to the input txs
237 func (s *Store) GetTransactionsUtxo(view *state.UtxoViewpoint, txs []*bc.Tx) error {
238         return getTransactionsUtxo(s.db, view, txs)
239 }
240
241 // GetTransactionStatus will return the utxo that related to the block hash
242 func (s *Store) GetTransactionStatus(hash *bc.Hash) (*bc.TransactionStatus, error) {
243         data := s.db.Get(calcTxStatusKey(hash))
244         if data == nil {
245                 return nil, errors.New("can't find the transaction status by given hash")
246         }
247
248         ts := &bc.TransactionStatus{}
249         if err := proto.Unmarshal(data, ts); err != nil {
250                 return nil, errors.Wrap(err, "unmarshaling transaction status")
251         }
252         return ts, nil
253 }
254
255 // GetUtxo will search the utxo in db
256 func (s *Store) GetUtxo(hash *bc.Hash) (*storage.UtxoEntry, error) {
257         return getUtxo(s.db, hash)
258 }
259
260 // GetConsensusResult retrive the voting result in specified vote sequence
261 func (s *Store) GetConsensusResult(seq uint64) (*state.ConsensusResult, error) {
262         return s.cache.lookupConsensusResult(seq)
263 }
264
265 // SaveBlock persists a new block in the protocol.
266 func (s *Store) SaveBlock(block *types.Block, ts *bc.TransactionStatus) error {
267         startTime := time.Now()
268         binaryBlockHeader, err := block.MarshalTextForBlockHeader()
269         if err != nil {
270                 return errors.Wrap(err, "Marshal block header")
271         }
272
273         binaryBlockTxs, err := block.MarshalTextForTransactions()
274         if err != nil {
275                 return errors.Wrap(err, "Marshal block transactions")
276         }
277
278         binaryTxStatus, err := proto.Marshal(ts)
279         if err != nil {
280                 return errors.Wrap(err, "Marshal block transaction status")
281         }
282
283         blockHashes := []*bc.Hash{}
284         hashes, err := s.GetBlockHashesByHeight(block.Height)
285         if err != nil {
286                 return err
287         }
288         blockHashes = append(blockHashes, hashes...)
289         blockHash := block.Hash()
290         blockHashes = append(blockHashes, &blockHash)
291         binaryBlockHashes, err := json.Marshal(blockHashes)
292         if err != nil {
293                 return errors.Wrap(err, "Marshal block hashes")
294         }
295
296         batch := s.db.NewBatch()
297         batch.Set(calcBlockHashesPrefix(block.Height), binaryBlockHashes)
298         batch.Set(calcBlockHeaderKey(&blockHash), binaryBlockHeader)
299         batch.Set(calcBlockTransactionsKey(&blockHash), binaryBlockTxs)
300         batch.Set(calcTxStatusKey(&blockHash), binaryTxStatus)
301         batch.Write()
302
303         s.cache.removeBlockHashes(block.Height)
304         log.WithFields(log.Fields{
305                 "module":   logModule,
306                 "height":   block.Height,
307                 "hash":     blockHash.String(),
308                 "duration": time.Since(startTime),
309         }).Info("block saved on disk")
310         return nil
311 }
312
313 // SaveBlockHeader persists a new block header in the protocol.
314 func (s *Store) SaveBlockHeader(blockHeader *types.BlockHeader) error {
315         binaryBlockHeader, err := blockHeader.MarshalText()
316         if err != nil {
317                 return errors.Wrap(err, "Marshal block header")
318         }
319
320         blockHash := blockHeader.Hash()
321         s.db.Set(calcBlockHeaderKey(&blockHash), binaryBlockHeader)
322         s.cache.removeBlockHeader(blockHeader)
323         return nil
324 }
325
326 // SaveChainStatus save the core's newest status && delete old status
327 func (s *Store) SaveChainStatus(blockHeader, irrBlockHeader *types.BlockHeader, mainBlockHeaders []*types.BlockHeader, view *state.UtxoViewpoint, consensusResults []*state.ConsensusResult) error {
328         currentStatus := loadBlockStoreStateJSON(s.db)
329         batch := s.db.NewBatch()
330         if err := saveUtxoView(batch, view); err != nil {
331                 return err
332         }
333
334         for _, result := range consensusResults {
335                 bytes, err := json.Marshal(result)
336                 if err != nil {
337                         return err
338                 }
339
340                 batch.Set(calcConsensusResultKey(result.Seq), bytes)
341                 s.cache.removeConsensusResult(result)
342         }
343
344         blockHash := blockHeader.Hash()
345         irrBlockHash := irrBlockHeader.Hash()
346         bytes, err := json.Marshal(protocol.BlockStoreState{
347                 Height:             blockHeader.Height,
348                 Hash:               &blockHash,
349                 IrreversibleHeight: irrBlockHeader.Height,
350                 IrreversibleHash:   &irrBlockHash,
351         })
352         if err != nil {
353                 return err
354         }
355         batch.Set([]byte{blockStore}, bytes)
356
357         // save main chain blockHeaders
358         for _, bh := range mainBlockHeaders {
359                 blockHash := bh.Hash()
360                 binaryBlockHash, err := blockHash.MarshalText()
361                 if err != nil {
362                         return errors.Wrap(err, "Marshal block hash")
363                 }
364
365                 batch.Set(calcMainChainIndexPrefix(bh.Height), binaryBlockHash)
366                 s.cache.removeMainChainHash(bh.Height)
367         }
368
369         if currentStatus != nil {
370                 for i := blockHeader.Height + 1; i <= currentStatus.Height; i++ {
371                         batch.Delete(calcMainChainIndexPrefix(i))
372                         s.cache.removeMainChainHash(i)
373                 }
374         }
375         batch.Write()
376         return nil
377 }