8 "github.com/golang/protobuf/proto"
9 log "github.com/sirupsen/logrus"
10 "github.com/tendermint/tmlibs/common"
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"
21 const logModule = "leveldb"
24 blockStoreKey = []byte("blockStore")
25 blockPrefix = []byte("B:")
26 blockHeaderPrefix = []byte("BH:")
27 txStatusPrefix = []byte("BTS:")
30 func loadBlockStoreStateJSON(db dbm.DB) *protocol.BlockStoreState {
31 bytes := db.Get(blockStoreKey)
35 bsj := &protocol.BlockStoreState{}
36 if err := json.Unmarshal(bytes, bsj); err != nil {
37 common.PanicCrisis(common.Fmt("Could not unmarshal bytes: %X", bytes))
42 // A Store encapsulates storage for blockchain validation.
43 // It satisfies the interface protocol.Store, and provides additional
44 // methods for querying current data.
50 func calcBlockKey(hash *bc.Hash) []byte {
51 return append(blockPrefix, hash.Bytes()...)
54 func calcBlockHeaderKey(height uint64, hash *bc.Hash) []byte {
56 binary.BigEndian.PutUint64(buf[:], height)
57 key := append(blockHeaderPrefix, buf[:]...)
58 return append(key, hash.Bytes()...)
61 func calcTxStatusKey(hash *bc.Hash) []byte {
62 return append(txStatusPrefix, hash.Bytes()...)
65 // GetBlock return the block by given hash
66 func GetBlock(db dbm.DB, hash *bc.Hash) (*types.Block, error) {
67 bytez := db.Get(calcBlockKey(hash))
72 block := &types.Block{}
73 err := block.UnmarshalText(bytez)
77 // NewStore creates and returns a new Store object.
78 func NewStore(db dbm.DB) *Store {
79 cache := newBlockCache(func(hash *bc.Hash) (*types.Block, error) {
80 return GetBlock(db, hash)
88 // GetUtxo will search the utxo in db
89 func (s *Store) GetUtxo(hash *bc.Hash) (*storage.UtxoEntry, error) {
90 return getUtxo(s.db, hash)
93 // BlockExist check if the block is stored in disk
94 func (s *Store) BlockExist(hash *bc.Hash) bool {
95 block, err := s.cache.lookup(hash)
96 return err == nil && block != nil
99 // GetBlock return the block by given hash
100 func (s *Store) GetBlock(hash *bc.Hash) (*types.Block, error) {
101 return s.cache.lookup(hash)
104 // GetTransactionsUtxo will return all the utxo that related to the input txs
105 func (s *Store) GetTransactionsUtxo(view *state.UtxoViewpoint, txs []*bc.Tx) error {
106 return getTransactionsUtxo(s.db, view, txs)
109 // GetTransactionStatus will return the utxo that related to the block hash
110 func (s *Store) GetTransactionStatus(hash *bc.Hash) (*bc.TransactionStatus, error) {
111 data := s.db.Get(calcTxStatusKey(hash))
113 return nil, errors.New("can't find the transaction status by given hash")
116 ts := &bc.TransactionStatus{}
117 if err := proto.Unmarshal(data, ts); err != nil {
118 return nil, errors.Wrap(err, "unmarshaling transaction status")
123 // GetStoreStatus return the BlockStoreStateJSON
124 func (s *Store) GetStoreStatus() *protocol.BlockStoreState {
125 return loadBlockStoreStateJSON(s.db)
128 func (s *Store) LoadBlockIndex(stateBestHeight uint64) (*state.BlockIndex, error) {
129 startTime := time.Now()
130 blockIndex := state.NewBlockIndex()
131 bhIter := s.db.IteratorPrefix(blockHeaderPrefix)
132 defer bhIter.Release()
134 var lastNode *state.BlockNode
136 bh := &types.BlockHeader{}
137 if err := bh.UnmarshalText(bhIter.Value()); err != nil {
141 // If a block with a height greater than the best height of state is added to the index,
142 // It may cause a bug that the new block cant not be process properly.
143 if bh.Height > stateBestHeight {
147 var parent *state.BlockNode
148 if lastNode == nil || lastNode.Hash == bh.PreviousBlockHash {
151 parent = blockIndex.GetNode(&bh.PreviousBlockHash)
154 node, err := state.NewBlockNode(bh, parent)
159 blockIndex.AddNode(node)
163 log.WithFields(log.Fields{
165 "height": stateBestHeight,
166 "duration": time.Since(startTime),
167 }).Debug("initialize load history block index from database")
168 return blockIndex, nil
171 // SaveBlock persists a new block in the protocol.
172 func (s *Store) SaveBlock(block *types.Block, ts *bc.TransactionStatus) error {
173 startTime := time.Now()
174 binaryBlock, err := block.MarshalText()
176 return errors.Wrap(err, "Marshal block meta")
179 binaryBlockHeader, err := block.BlockHeader.MarshalText()
181 return errors.Wrap(err, "Marshal block header")
184 binaryTxStatus, err := proto.Marshal(ts)
186 return errors.Wrap(err, "marshal block transaction status")
189 blockHash := block.Hash()
190 batch := s.db.NewBatch()
191 batch.Set(calcBlockKey(&blockHash), binaryBlock)
192 batch.Set(calcBlockHeaderKey(block.Height, &blockHash), binaryBlockHeader)
193 batch.Set(calcTxStatusKey(&blockHash), binaryTxStatus)
196 log.WithFields(log.Fields{
198 "height": block.Height,
199 "hash": blockHash.String(),
200 "duration": time.Since(startTime),
201 }).Info("block saved on disk")
205 // SaveChainStatus save the core's newest status && delete old status
206 func (s *Store) SaveChainStatus(node *state.BlockNode, view *state.UtxoViewpoint) error {
207 batch := s.db.NewBatch()
208 if err := saveUtxoView(batch, view); err != nil {
212 bytes, err := json.Marshal(protocol.BlockStoreState{Height: node.Height, Hash: &node.Hash})
217 batch.Set(blockStoreKey, bytes)