9 "github.com/golang/protobuf/proto"
10 log "github.com/sirupsen/logrus"
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"
24 // the byte of colon(:)
29 blockStore byte = iota
38 func loadBlockStoreStateJSON(db dbm.DB) *protocol.BlockStoreState {
39 bytes := db.Get([]byte{blockStore})
44 bsj := &protocol.BlockStoreState{}
45 if err := json.Unmarshal(bytes, bsj); err != nil {
46 log.WithField("err", err).Panic("fail on unmarshal BlockStoreStateJSON")
51 // A Store encapsulates storage for blockchain validation.
52 // It satisfies the interface protocol.Store, and provides additional
53 // methods for querying current data.
59 func calcMainChainIndexPrefix(height uint64) []byte {
61 binary.BigEndian.PutUint64(buf[:], height)
62 return append([]byte{mainChainIndex, colon}, buf[:]...)
65 func calcBlockHashesPrefix(height uint64) []byte {
67 binary.BigEndian.PutUint64(buf[:], height)
68 return append([]byte{blockHashes, colon}, buf[:]...)
71 func calcBlockHeaderKey(hash *bc.Hash) []byte {
72 return append([]byte{blockHeader, colon}, hash.Bytes()...)
75 func calcBlockTransactionsKey(hash *bc.Hash) []byte {
76 return append([]byte{blockTransactons, colon}, hash.Bytes()...)
79 func calcTxStatusKey(hash *bc.Hash) []byte {
80 return append([]byte{txStatus, colon}, hash.Bytes()...)
83 func calcConsensusResultKey(seq uint64) []byte {
85 binary.BigEndian.PutUint64(buf[:], seq)
86 return append([]byte{consensusResult, colon}, buf[:]...)
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())
96 blockHeader := &types.BlockHeader{}
97 if err := blockHeader.UnmarshalText(binaryBlockHeader); err != nil {
100 return blockHeader, nil
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())
110 block := &types.Block{}
111 if err := block.UnmarshalText(binaryBlockTxs); err != nil {
114 return block.Transactions, nil
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
124 hashes := []*bc.Hash{}
125 if err := json.Unmarshal(binaryHashes, &hashes); err != nil {
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)
139 if err := hash.UnmarshalText(binaryHash); err != nil {
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))
149 return nil, protocol.ErrNotFoundConsensusResult
152 consensusResult := new(state.ConsensusResult)
153 if err := json.Unmarshal(data, consensusResult); err != nil {
154 return nil, errors.Wrap(err, "unmarshaling vote result")
156 return consensusResult, nil
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)
164 fillBlockTxsFn := func(hash *bc.Hash) ([]*types.Tx, error) {
165 return GetBlockTransactions(db, hash)
168 fillBlockHashesFn := func(height uint64) ([]*bc.Hash, error) {
169 return GetBlockHashesByHeight(db, height)
172 fillMainChainHashFn := func(height uint64) (*bc.Hash, error) {
173 return GetMainChainHash(db, height)
176 fillConsensusResultFn := func(seq uint64) (*state.ConsensusResult, error) {
177 return GetConsensusResult(db, seq)
180 cache := newCache(fillBlockHeaderFn, fillBlockTxsFn, fillBlockHashesFn, fillMainChainHashFn, fillConsensusResultFn)
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)
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)
200 txs, err := s.GetBlockTransactions(hash)
206 BlockHeader: *blockHeader,
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)
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)
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)
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)
231 // GetStoreStatus return the BlockStoreStateJSON
232 func (s *Store) GetStoreStatus() *protocol.BlockStoreState {
233 return loadBlockStoreStateJSON(s.db)
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)
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))
245 return nil, errors.New("can't find the transaction status by given hash")
248 ts := &bc.TransactionStatus{}
249 if err := proto.Unmarshal(data, ts); err != nil {
250 return nil, errors.Wrap(err, "unmarshaling transaction status")
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)
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)
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()
270 return errors.Wrap(err, "Marshal block header")
273 binaryBlockTxs, err := block.MarshalTextForTransactions()
275 return errors.Wrap(err, "Marshal block transactions")
278 binaryTxStatus, err := proto.Marshal(ts)
280 return errors.Wrap(err, "Marshal block transaction status")
283 blockHashes := []*bc.Hash{}
284 hashes, err := s.GetBlockHashesByHeight(block.Height)
288 blockHashes = append(blockHashes, hashes...)
289 blockHash := block.Hash()
290 blockHashes = append(blockHashes, &blockHash)
291 binaryBlockHashes, err := json.Marshal(blockHashes)
293 return errors.Wrap(err, "Marshal block hashes")
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)
303 s.cache.removeBlockHashes(block.Height)
304 log.WithFields(log.Fields{
306 "height": block.Height,
307 "hash": blockHash.String(),
308 "duration": time.Since(startTime),
309 }).Info("block saved on disk")
313 // SaveBlockHeader persists a new block header in the protocol.
314 func (s *Store) SaveBlockHeader(blockHeader *types.BlockHeader) error {
315 binaryBlockHeader, err := blockHeader.MarshalText()
317 return errors.Wrap(err, "Marshal block header")
320 blockHash := blockHeader.Hash()
321 s.db.Set(calcBlockHeaderKey(&blockHash), binaryBlockHeader)
322 s.cache.removeBlockHeader(blockHeader)
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 batch := s.db.NewBatch()
329 if err := saveUtxoView(batch, view); err != nil {
333 for _, result := range consensusResults {
334 bytes, err := json.Marshal(result)
339 batch.Set(calcConsensusResultKey(result.Seq), bytes)
340 s.cache.removeConsensusResult(result)
343 blockHash := blockHeader.Hash()
344 irrBlockHash := irrBlockHeader.Hash()
345 bytes, err := json.Marshal(protocol.BlockStoreState{
346 Height: blockHeader.Height,
348 IrreversibleHeight: irrBlockHeader.Height,
349 IrreversibleHash: &irrBlockHash,
354 batch.Set([]byte{blockStore}, bytes)
356 // save main chain blockHeaders
357 for _, bh := range mainBlockHeaders {
358 blockHash := bh.Hash()
359 binaryBlockHash, err := blockHash.MarshalText()
361 return errors.Wrap(err, "Marshal block hash")
364 batch.Set(calcMainChainIndexPrefix(bh.Height), binaryBlockHash)
365 s.cache.removeMainChainHash(bh.Height)