OSDN Git Service

feat(warder): add warder backbone (#181)
[bytom/vapor.git] / federation / synchron / sidechain_keeper.go
1 package synchron
2
3 import (
4         "database/sql"
5         "encoding/hex"
6         "fmt"
7         "time"
8
9         "github.com/jinzhu/gorm"
10         log "github.com/sirupsen/logrus"
11
12         "github.com/vapor/consensus"
13         "github.com/vapor/errors"
14         "github.com/vapor/federation/common"
15         "github.com/vapor/federation/config"
16         "github.com/vapor/federation/database"
17         "github.com/vapor/federation/database/orm"
18         "github.com/vapor/federation/service"
19         "github.com/vapor/protocol/bc"
20         "github.com/vapor/protocol/bc/types"
21 )
22
23 type sidechainKeeper struct {
24         cfg        *config.Chain
25         db         *gorm.DB
26         node       *service.Node
27         chainName  string
28         assetStore *database.AssetStore
29 }
30
31 func NewSidechainKeeper(db *gorm.DB, assetStore *database.AssetStore, cfg *config.Config) *sidechainKeeper {
32         return &sidechainKeeper{
33                 cfg:        &cfg.Sidechain,
34                 db:         db,
35                 node:       service.NewNode(cfg.Sidechain.Upstream),
36                 chainName:  cfg.Sidechain.Name,
37                 assetStore: assetStore,
38         }
39 }
40
41 func (s *sidechainKeeper) Run() {
42         ticker := time.NewTicker(time.Duration(s.cfg.SyncSeconds) * time.Second)
43         for ; true; <-ticker.C {
44                 for {
45                         isUpdate, err := s.syncBlock()
46                         if err != nil {
47                                 log.WithField("error", err).Errorln("blockKeeper fail on process block")
48                                 break
49                         }
50
51                         if !isUpdate {
52                                 break
53                         }
54                 }
55         }
56 }
57
58 func (s *sidechainKeeper) syncBlock() (bool, error) {
59         chain := &orm.Chain{Name: s.chainName}
60         if err := s.db.Where(chain).First(chain).Error; err != nil {
61                 return false, errors.Wrap(err, "query chain")
62         }
63
64         height, err := s.node.GetBlockCount()
65         if err != nil {
66                 return false, err
67         }
68
69         if height <= chain.BlockHeight+s.cfg.Confirmations {
70                 return false, nil
71         }
72
73         nextBlockStr, txStatus, err := s.node.GetBlockByHeight(chain.BlockHeight + 1)
74         if err != nil {
75                 return false, err
76         }
77
78         nextBlock := &types.Block{}
79         if err := nextBlock.UnmarshalText([]byte(nextBlockStr)); err != nil {
80                 return false, errors.New("Unmarshal nextBlock")
81         }
82
83         if nextBlock.PreviousBlockHash.String() != chain.BlockHash {
84                 log.WithFields(log.Fields{
85                         "remote PreviousBlockHash": nextBlock.PreviousBlockHash.String(),
86                         "db block_hash":            chain.BlockHash,
87                 }).Fatal("BlockHash mismatch")
88                 return false, ErrInconsistentDB
89         }
90
91         if err := s.tryAttachBlock(chain, nextBlock, txStatus); err != nil {
92                 return false, err
93         }
94
95         return true, nil
96 }
97
98 func (s *sidechainKeeper) tryAttachBlock(chain *orm.Chain, block *types.Block, txStatus *bc.TransactionStatus) error {
99         blockHash := block.Hash()
100         log.WithFields(log.Fields{"block_height": block.Height, "block_hash": blockHash.String()}).Info("start to attachBlock")
101         dbTx := s.db.Begin()
102         if err := s.processBlock(chain, block, txStatus); err != nil {
103                 dbTx.Rollback()
104                 return err
105         }
106
107         return dbTx.Commit().Error
108 }
109
110 func (s *sidechainKeeper) processBlock(chain *orm.Chain, block *types.Block, txStatus *bc.TransactionStatus) error {
111         for i, tx := range block.Transactions {
112                 if s.isDepositTx(tx) {
113                         if err := s.processDepositTx(chain, block, uint64(i), tx); err != nil {
114                                 return err
115                         }
116                 }
117
118                 if s.isWithdrawalTx(tx) {
119                         if err := s.processWithdrawalTx(chain, block, txStatus, uint64(i), tx); err != nil {
120                                 return err
121                         }
122                 }
123         }
124
125         return s.processChainInfo(chain, block)
126 }
127
128 func (s *sidechainKeeper) isDepositTx(tx *types.Tx) bool {
129         for _, input := range tx.Inputs {
130                 if input.InputType() == types.CrossChainInputType {
131                         return true
132                 }
133         }
134         return false
135 }
136
137 func (s *sidechainKeeper) isWithdrawalTx(tx *types.Tx) bool {
138         for _, output := range tx.Outputs {
139                 if output.OutputType() == types.CrossChainOutputType {
140                         return true
141                 }
142         }
143         return false
144 }
145
146 func (s *sidechainKeeper) processDepositTx(chain *orm.Chain, block *types.Block, txIndex uint64, tx *types.Tx) error {
147         blockHash := block.Hash()
148         stmt := s.db.Model(&orm.CrossTransaction{}).Where("chain_id != ?", chain.ID).
149                 Where(&orm.CrossTransaction{
150                         DestTxHash: sql.NullString{tx.ID.String(), true},
151                         Status:     common.CrossTxPendingStatus,
152                 }).UpdateColumn(&orm.CrossTransaction{
153                 DestBlockHeight: sql.NullInt64{int64(block.Height), true},
154                 DestBlockHash:   sql.NullString{blockHash.String(), true},
155                 DestTxIndex:     sql.NullInt64{int64(txIndex), true},
156                 Status:          common.CrossTxCompletedStatus,
157         })
158         if stmt.Error != nil {
159                 return stmt.Error
160         }
161
162         if stmt.RowsAffected != 1 {
163                 log.Warnf("sidechainKeeper.processDepositTx(%v): rows affected != 1", tx.ID.String())
164         }
165         return nil
166 }
167
168 func (s *sidechainKeeper) processWithdrawalTx(chain *orm.Chain, block *types.Block, txStatus *bc.TransactionStatus, txIndex uint64, tx *types.Tx) error {
169         blockHash := block.Hash()
170
171         var muxID bc.Hash
172         res0ID := tx.ResultIds[0]
173         switch res := tx.Entries[*res0ID].(type) {
174         case *bc.CrossChainOutput:
175                 muxID = *res.Source.Ref
176         case *bc.IntraChainOutput:
177                 muxID = *res.Source.Ref
178         case *bc.VoteOutput:
179                 muxID = *res.Source.Ref
180         default:
181                 return ErrOutputType
182         }
183
184         rawTx, err := tx.MarshalText()
185         if err != nil {
186                 return err
187         }
188
189         ormTx := &orm.CrossTransaction{
190                 ChainID:              chain.ID,
191                 SourceBlockHeight:    block.Height,
192                 SourceBlockHash:      blockHash.String(),
193                 SourceTxIndex:        txIndex,
194                 SourceMuxID:          muxID.String(),
195                 SourceTxHash:         tx.ID.String(),
196                 SourceRawTransaction: string(rawTx),
197                 DestBlockHeight:      sql.NullInt64{Valid: false},
198                 DestBlockHash:        sql.NullString{Valid: false},
199                 DestTxIndex:          sql.NullInt64{Valid: false},
200                 DestTxHash:           sql.NullString{Valid: false},
201                 Status:               common.CrossTxPendingStatus,
202         }
203         if err := s.db.Create(ormTx).Error; err != nil {
204                 return errors.Wrap(err, fmt.Sprintf("create sidechain WithdrawalTx %s", tx.ID.String()))
205         }
206
207         statusFail := txStatus.VerifyStatus[txIndex].StatusFail
208         crossChainOutputs, err := s.getCrossChainReqs(ormTx.ID, tx, statusFail)
209         if err != nil {
210                 return err
211         }
212
213         for _, output := range crossChainOutputs {
214                 if err := s.db.Create(output).Error; err != nil {
215                         return errors.Wrap(err, fmt.Sprintf("create WithdrawalFromSidechain output: txid(%s), pos(%d)", tx.ID.String(), output.SourcePos))
216                 }
217         }
218
219         return nil
220 }
221
222 func (s *sidechainKeeper) getCrossChainReqs(crossTransactionID uint64, tx *types.Tx, statusFail bool) ([]*orm.CrossTransactionReq, error) {
223         reqs := []*orm.CrossTransactionReq{}
224         for i, rawOutput := range tx.Outputs {
225                 // check valid withdrawal
226                 if rawOutput.OutputType() != types.CrossChainOutputType {
227                         continue
228                 }
229
230                 if statusFail && *rawOutput.OutputCommitment().AssetAmount.AssetId != *consensus.BTMAssetID {
231                         continue
232                 }
233
234                 asset, err := s.assetStore.GetByAssetID(rawOutput.OutputCommitment().AssetAmount.AssetId.String())
235                 if err != nil {
236                         return nil, err
237                 }
238
239                 req := &orm.CrossTransactionReq{
240                         CrossTransactionID: crossTransactionID,
241                         SourcePos:          uint64(i),
242                         AssetID:            asset.ID,
243                         AssetAmount:        rawOutput.OutputCommitment().AssetAmount.Amount,
244                         Script:             hex.EncodeToString(rawOutput.ControlProgram()),
245                 }
246                 reqs = append(reqs, req)
247         }
248         return reqs, nil
249 }
250
251 func (s *sidechainKeeper) processChainInfo(chain *orm.Chain, block *types.Block) error {
252         blockHash := block.Hash()
253         chain.BlockHash = blockHash.String()
254         chain.BlockHeight = block.Height
255         res := s.db.Model(chain).Where("block_hash = ?", block.PreviousBlockHash.String()).Updates(chain)
256         if err := res.Error; err != nil {
257                 return err
258         }
259
260         if res.RowsAffected != 1 {
261                 return ErrInconsistentDB
262         }
263
264         return nil
265 }