OSDN Git Service

re design reorganizeChain (#495)
[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/bytom/vapor/database/leveldb"
13         "github.com/bytom/vapor/database/storage"
14         "github.com/bytom/vapor/errors"
15         "github.com/bytom/vapor/protocol"
16         "github.com/bytom/vapor/protocol/bc"
17         "github.com/bytom/vapor/protocol/bc/types"
18         "github.com/bytom/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 // DeleteBlock delete a new block in the protocol.
160 func (s *Store) DeleteBlock(block *types.Block) error {
161         blockHash := block.Hash()
162         blockHashes, err := s.GetBlockHashesByHeight(block.Height)
163         if err != nil {
164                 return err
165         }
166
167         for i := 0; i < len(blockHashes); i++ {
168                 if blockHashes[i].String() == blockHash.String() {
169                         blockHashes = append(blockHashes[0:i], blockHashes[i+1:len(blockHashes)]...)
170                         break
171                 }
172         }
173
174         batch := s.db.NewBatch()
175         if len(blockHashes) == 0 {
176                 batch.Delete(calcBlockHashesPrefix(block.Height))
177         } else {
178                 binaryBlockHashes, err := json.Marshal(blockHashes)
179                 if err != nil {
180                         return errors.Wrap(err, "Marshal block hashes")
181                 }
182
183                 batch.Set(calcBlockHashesPrefix(block.Height), binaryBlockHashes)
184         }
185
186         batch.Delete(calcBlockHeaderKey(&blockHash))
187         batch.Delete(calcBlockTransactionsKey(&blockHash))
188         batch.Delete(calcTxStatusKey(&blockHash))
189         batch.Write()
190
191         s.cache.removeBlockHashes(block.Height)
192         s.cache.removeBlockHeader(&block.BlockHeader)
193
194         return nil
195 }
196
197 // NewStore creates and returns a new Store object.
198 func NewStore(db dbm.DB) *Store {
199         fillBlockHeaderFn := func(hash *bc.Hash) (*types.BlockHeader, error) {
200                 return GetBlockHeader(db, hash)
201         }
202         fillBlockTxsFn := func(hash *bc.Hash) ([]*types.Tx, error) {
203                 return GetBlockTransactions(db, hash)
204         }
205
206         fillBlockHashesFn := func(height uint64) ([]*bc.Hash, error) {
207                 return GetBlockHashesByHeight(db, height)
208         }
209
210         fillMainChainHashFn := func(height uint64) (*bc.Hash, error) {
211                 return GetMainChainHash(db, height)
212         }
213
214         fillConsensusResultFn := func(seq uint64) (*state.ConsensusResult, error) {
215                 return GetConsensusResult(db, seq)
216         }
217
218         cache := newCache(fillBlockHeaderFn, fillBlockTxsFn, fillBlockHashesFn, fillMainChainHashFn, fillConsensusResultFn)
219         return &Store{
220                 db:    db,
221                 cache: cache,
222         }
223 }
224
225 // BlockExist check if the block is stored in disk
226 func (s *Store) BlockExist(hash *bc.Hash) bool {
227         _, err := s.cache.lookupBlockHeader(hash)
228         return err == nil
229 }
230
231 // GetBlock return the block by given hash
232 func (s *Store) GetBlock(hash *bc.Hash) (*types.Block, error) {
233         blockHeader, err := s.GetBlockHeader(hash)
234         if err != nil {
235                 return nil, err
236         }
237
238         txs, err := s.GetBlockTransactions(hash)
239         if err != nil {
240                 return nil, err
241         }
242
243         return &types.Block{
244                 BlockHeader:  *blockHeader,
245                 Transactions: txs,
246         }, nil
247 }
248
249 // GetBlockHeader return the BlockHeader by given hash
250 func (s *Store) GetBlockHeader(hash *bc.Hash) (*types.BlockHeader, error) {
251         return s.cache.lookupBlockHeader(hash)
252 }
253
254 // GetBlockTransactions return the Block transactions by given hash
255 func (s *Store) GetBlockTransactions(hash *bc.Hash) ([]*types.Tx, error) {
256         return s.cache.lookupBlockTxs(hash)
257 }
258
259 // GetBlockHashesByHeight return the block hash by the specified height
260 func (s *Store) GetBlockHashesByHeight(height uint64) ([]*bc.Hash, error) {
261         return s.cache.lookupBlockHashesByHeight(height)
262 }
263
264 // GetMainChainHash return the block hash by the specified height
265 func (s *Store) GetMainChainHash(height uint64) (*bc.Hash, error) {
266         return s.cache.lookupMainChainHash(height)
267 }
268
269 // GetStoreStatus return the BlockStoreStateJSON
270 func (s *Store) GetStoreStatus() *protocol.BlockStoreState {
271         return loadBlockStoreStateJSON(s.db)
272 }
273
274 // GetTransactionsUtxo will return all the utxo that related to the input txs
275 func (s *Store) GetTransactionsUtxo(view *state.UtxoViewpoint, txs []*bc.Tx) error {
276         return getTransactionsUtxo(s.db, view, txs)
277 }
278
279 // GetTransactionStatus will return the utxo that related to the block hash
280 func (s *Store) GetTransactionStatus(hash *bc.Hash) (*bc.TransactionStatus, error) {
281         data := s.db.Get(calcTxStatusKey(hash))
282         if data == nil {
283                 return nil, errors.New("can't find the transaction status by given hash")
284         }
285
286         ts := &bc.TransactionStatus{}
287         if err := proto.Unmarshal(data, ts); err != nil {
288                 return nil, errors.Wrap(err, "unmarshaling transaction status")
289         }
290         return ts, nil
291 }
292
293 // GetUtxo will search the utxo in db
294 func (s *Store) GetUtxo(hash *bc.Hash) (*storage.UtxoEntry, error) {
295         return getUtxo(s.db, hash)
296 }
297
298 // GetConsensusResult retrive the voting result in specified vote sequence
299 func (s *Store) GetConsensusResult(seq uint64) (*state.ConsensusResult, error) {
300         return s.cache.lookupConsensusResult(seq)
301 }
302
303 // SaveBlock persists a new block in the protocol.
304 func (s *Store) SaveBlock(block *types.Block, ts *bc.TransactionStatus) error {
305         startTime := time.Now()
306         binaryBlockHeader, err := block.MarshalTextForBlockHeader()
307         if err != nil {
308                 return errors.Wrap(err, "Marshal block header")
309         }
310
311         binaryBlockTxs, err := block.MarshalTextForTransactions()
312         if err != nil {
313                 return errors.Wrap(err, "Marshal block transactions")
314         }
315
316         binaryTxStatus, err := proto.Marshal(ts)
317         if err != nil {
318                 return errors.Wrap(err, "Marshal block transaction status")
319         }
320
321         blockHashes := []*bc.Hash{}
322         hashes, err := s.GetBlockHashesByHeight(block.Height)
323         if err != nil {
324                 return err
325         }
326         blockHashes = append(blockHashes, hashes...)
327         blockHash := block.Hash()
328         blockHashes = append(blockHashes, &blockHash)
329         binaryBlockHashes, err := json.Marshal(blockHashes)
330         if err != nil {
331                 return errors.Wrap(err, "Marshal block hashes")
332         }
333
334         batch := s.db.NewBatch()
335         batch.Set(calcBlockHashesPrefix(block.Height), binaryBlockHashes)
336         batch.Set(calcBlockHeaderKey(&blockHash), binaryBlockHeader)
337         batch.Set(calcBlockTransactionsKey(&blockHash), binaryBlockTxs)
338         batch.Set(calcTxStatusKey(&blockHash), binaryTxStatus)
339         batch.Write()
340
341         s.cache.removeBlockHashes(block.Height)
342         log.WithFields(log.Fields{
343                 "module":   logModule,
344                 "height":   block.Height,
345                 "hash":     blockHash.String(),
346                 "duration": time.Since(startTime),
347         }).Info("block saved on disk")
348         return nil
349 }
350
351 // SaveBlockHeader persists a new block header in the protocol.
352 func (s *Store) SaveBlockHeader(blockHeader *types.BlockHeader) error {
353         binaryBlockHeader, err := blockHeader.MarshalText()
354         if err != nil {
355                 return errors.Wrap(err, "Marshal block header")
356         }
357
358         blockHash := blockHeader.Hash()
359         s.db.Set(calcBlockHeaderKey(&blockHash), binaryBlockHeader)
360         s.cache.removeBlockHeader(blockHeader)
361         return nil
362 }
363
364 // SaveChainStatus save the core's newest status && delete old status
365 func (s *Store) SaveChainStatus(blockHeader, irrBlockHeader *types.BlockHeader, mainBlockHeaders []*types.BlockHeader, view *state.UtxoViewpoint, consensusResults []*state.ConsensusResult) error {
366         currentStatus := loadBlockStoreStateJSON(s.db)
367         batch := s.db.NewBatch()
368         if err := saveUtxoView(batch, view); err != nil {
369                 return err
370         }
371
372         var clearCacheFuncs []func()
373         for _, consensusResult := range consensusResults {
374                 result := consensusResult
375                 bytes, err := json.Marshal(result)
376                 if err != nil {
377                         return err
378                 }
379
380                 batch.Set(calcConsensusResultKey(result.Seq), bytes)
381                 clearCacheFuncs = append(clearCacheFuncs, func() {
382                         s.cache.removeConsensusResult(result)
383                 })
384         }
385
386         blockHash := blockHeader.Hash()
387         irrBlockHash := irrBlockHeader.Hash()
388         bytes, err := json.Marshal(protocol.BlockStoreState{
389                 Height:             blockHeader.Height,
390                 Hash:               &blockHash,
391                 IrreversibleHeight: irrBlockHeader.Height,
392                 IrreversibleHash:   &irrBlockHash,
393         })
394         if err != nil {
395                 return err
396         }
397         batch.Set([]byte{blockStore}, bytes)
398
399         // save main chain blockHeaders
400         for _, blockHeader := range mainBlockHeaders {
401                 bh := blockHeader
402                 blockHash := bh.Hash()
403                 binaryBlockHash, err := blockHash.MarshalText()
404                 if err != nil {
405                         return errors.Wrap(err, "Marshal block hash")
406                 }
407
408                 batch.Set(calcMainChainIndexPrefix(bh.Height), binaryBlockHash)
409                 clearCacheFuncs = append(clearCacheFuncs, func() {
410                         s.cache.removeMainChainHash(bh.Height)
411                 })
412         }
413
414         if currentStatus != nil {
415                 for i := blockHeader.Height + 1; i <= currentStatus.Height; i++ {
416                         index := i
417                         batch.Delete(calcMainChainIndexPrefix(index))
418                         clearCacheFuncs = append(clearCacheFuncs, func() {
419                                 s.cache.removeMainChainHash(index)
420                         })
421                 }
422         }
423         batch.Write()
424
425         for _, clearCacheFunc := range clearCacheFuncs {
426                 clearCacheFunc()
427         }
428         return nil
429 }