OSDN Git Service

fed458e7ce6705c5b60bd2734666a0fbd7ff258b
[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         assetCache *database.AssetCache
29 }
30
31 func NewSidechainKeeper(db *gorm.DB, chainCfg *config.Chain) *sidechainKeeper {
32         return &sidechainKeeper{
33                 cfg:        chainCfg,
34                 db:         db,
35                 node:       service.NewNode(chainCfg.Upstream),
36                 chainName:  chainCfg.Name,
37                 assetCache: database.NewAssetCache(),
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         s.db.Begin()
102         if err := s.processBlock(chain, block, txStatus); err != nil {
103                 s.db.Rollback()
104                 return err
105         }
106
107         return s.db.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.CrossTxSubmittedStatus,
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         // assume inputs are from an identical owner
224         script := hex.EncodeToString(tx.Inputs[0].ControlProgram())
225         inputs := []*orm.CrossTransactionReq{}
226         for i, rawOutput := range tx.Outputs {
227                 // check valid withdrawal
228                 if rawOutput.OutputType() != types.CrossChainOutputType {
229                         continue
230                 }
231
232                 if statusFail && *rawOutput.OutputCommitment().AssetAmount.AssetId != *consensus.BTMAssetID {
233                         continue
234                 }
235
236                 asset, err := s.getAsset(rawOutput.OutputCommitment().AssetAmount.AssetId.String())
237                 if err != nil {
238                         return nil, err
239                 }
240
241                 input := &orm.CrossTransactionReq{
242                         CrossTransactionID: crossTransactionID,
243                         SourcePos:          uint64(i),
244                         AssetID:            asset.ID,
245                         AssetAmount:        rawOutput.OutputCommitment().AssetAmount.Amount,
246                         Script:             script,
247                 }
248                 inputs = append(inputs, input)
249         }
250         return inputs, nil
251 }
252
253 func (s *sidechainKeeper) processChainInfo(chain *orm.Chain, block *types.Block) error {
254         blockHash := block.Hash()
255         chain.BlockHash = blockHash.String()
256         chain.BlockHeight = block.Height
257         res := s.db.Model(chain).Where("block_hash = ?", block.PreviousBlockHash.String()).Updates(chain)
258         if err := res.Error; err != nil {
259                 return err
260         }
261
262         if res.RowsAffected != 1 {
263                 return ErrInconsistentDB
264         }
265
266         return nil
267 }
268
269 func (s *sidechainKeeper) getAsset(assetID string) (*orm.Asset, error) {
270         if asset := s.assetCache.Get(assetID); asset != nil {
271                 return asset, nil
272         }
273
274         asset := &orm.Asset{AssetID: assetID}
275         if err := s.db.Where(asset).First(asset).Error; err != nil {
276                 return nil, errors.Wrap(err, "asset not found in memory and mysql")
277         }
278
279         s.assetCache.Add(assetID, asset)
280         return asset, nil
281 }