9 "github.com/golang/protobuf/proto"
10 log "github.com/sirupsen/logrus"
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"
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 // 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)
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)]...)
174 batch := s.db.NewBatch()
175 if len(blockHashes) == 0 {
176 batch.Delete(calcBlockHashesPrefix(block.Height))
178 binaryBlockHashes, err := json.Marshal(blockHashes)
180 return errors.Wrap(err, "Marshal block hashes")
183 batch.Set(calcBlockHashesPrefix(block.Height), binaryBlockHashes)
186 batch.Delete(calcBlockHeaderKey(&blockHash))
187 batch.Delete(calcBlockTransactionsKey(&blockHash))
188 batch.Delete(calcTxStatusKey(&blockHash))
191 s.cache.removeBlockHashes(block.Height)
192 s.cache.removeBlockHeader(&block.BlockHeader)
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)
202 fillBlockTxsFn := func(hash *bc.Hash) ([]*types.Tx, error) {
203 return GetBlockTransactions(db, hash)
206 fillBlockHashesFn := func(height uint64) ([]*bc.Hash, error) {
207 return GetBlockHashesByHeight(db, height)
210 fillMainChainHashFn := func(height uint64) (*bc.Hash, error) {
211 return GetMainChainHash(db, height)
214 fillConsensusResultFn := func(seq uint64) (*state.ConsensusResult, error) {
215 return GetConsensusResult(db, seq)
218 cache := newCache(fillBlockHeaderFn, fillBlockTxsFn, fillBlockHashesFn, fillMainChainHashFn, fillConsensusResultFn)
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)
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)
238 txs, err := s.GetBlockTransactions(hash)
244 BlockHeader: *blockHeader,
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)
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)
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)
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)
269 // GetStoreStatus return the BlockStoreStateJSON
270 func (s *Store) GetStoreStatus() *protocol.BlockStoreState {
271 return loadBlockStoreStateJSON(s.db)
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)
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))
283 return nil, errors.New("can't find the transaction status by given hash")
286 ts := &bc.TransactionStatus{}
287 if err := proto.Unmarshal(data, ts); err != nil {
288 return nil, errors.Wrap(err, "unmarshaling transaction status")
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)
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)
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()
308 return errors.Wrap(err, "Marshal block header")
311 binaryBlockTxs, err := block.MarshalTextForTransactions()
313 return errors.Wrap(err, "Marshal block transactions")
316 binaryTxStatus, err := proto.Marshal(ts)
318 return errors.Wrap(err, "Marshal block transaction status")
321 blockHashes := []*bc.Hash{}
322 hashes, err := s.GetBlockHashesByHeight(block.Height)
326 blockHashes = append(blockHashes, hashes...)
327 blockHash := block.Hash()
328 blockHashes = append(blockHashes, &blockHash)
329 binaryBlockHashes, err := json.Marshal(blockHashes)
331 return errors.Wrap(err, "Marshal block hashes")
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)
341 s.cache.removeBlockHashes(block.Height)
342 log.WithFields(log.Fields{
344 "height": block.Height,
345 "hash": blockHash.String(),
346 "duration": time.Since(startTime),
347 }).Info("block saved on disk")
351 // SaveBlockHeader persists a new block header in the protocol.
352 func (s *Store) SaveBlockHeader(blockHeader *types.BlockHeader) error {
353 binaryBlockHeader, err := blockHeader.MarshalText()
355 return errors.Wrap(err, "Marshal block header")
358 blockHash := blockHeader.Hash()
359 s.db.Set(calcBlockHeaderKey(&blockHash), binaryBlockHeader)
360 s.cache.removeBlockHeader(blockHeader)
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 {
372 var clearCacheFuncs []func()
373 for _, consensusResult := range consensusResults {
374 result := consensusResult
375 bytes, err := json.Marshal(result)
380 batch.Set(calcConsensusResultKey(result.Seq), bytes)
381 clearCacheFuncs = append(clearCacheFuncs, func() {
382 s.cache.removeConsensusResult(result)
386 blockHash := blockHeader.Hash()
387 irrBlockHash := irrBlockHeader.Hash()
388 bytes, err := json.Marshal(protocol.BlockStoreState{
389 Height: blockHeader.Height,
391 IrreversibleHeight: irrBlockHeader.Height,
392 IrreversibleHash: &irrBlockHash,
397 batch.Set([]byte{blockStore}, bytes)
399 // save main chain blockHeaders
400 for _, blockHeader := range mainBlockHeaders {
402 blockHash := bh.Hash()
403 binaryBlockHash, err := blockHash.MarshalText()
405 return errors.Wrap(err, "Marshal block hash")
408 batch.Set(calcMainChainIndexPrefix(bh.Height), binaryBlockHash)
409 clearCacheFuncs = append(clearCacheFuncs, func() {
410 s.cache.removeMainChainHash(bh.Height)
414 if currentStatus != nil {
415 for i := blockHeader.Height + 1; i <= currentStatus.Height; i++ {
417 batch.Delete(calcMainChainIndexPrefix(index))
418 clearCacheFuncs = append(clearCacheFuncs, func() {
419 s.cache.removeMainChainHash(index)
425 for _, clearCacheFunc := range clearCacheFuncs {