OSDN Git Service

change the ts (#284)
[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         assetStore *database.AssetStore
28         chainID    uint64
29 }
30
31 func NewSidechainKeeper(db *gorm.DB, assetStore *database.AssetStore, cfg *config.Config) *sidechainKeeper {
32         chain := &orm.Chain{Name: common.VaporChainName}
33         if err := db.Where(chain).First(chain).Error; err != nil {
34                 log.WithField("err", err).Fatal("fail on get chain info")
35         }
36
37         return &sidechainKeeper{
38                 cfg:        &cfg.Sidechain,
39                 db:         db,
40                 node:       service.NewNode(cfg.Sidechain.Upstream),
41                 assetStore: assetStore,
42                 chainID:    chain.ID,
43         }
44 }
45
46 func (s *sidechainKeeper) Run() {
47         ticker := time.NewTicker(time.Duration(s.cfg.SyncSeconds) * time.Second)
48         for ; true; <-ticker.C {
49                 for {
50                         isUpdate, err := s.syncBlock()
51                         if err != nil {
52                                 log.WithField("error", err).Errorln("blockKeeper fail on process block")
53                                 break
54                         }
55
56                         if !isUpdate {
57                                 break
58                         }
59                 }
60         }
61 }
62
63 func (s *sidechainKeeper) createCrossChainReqs(db *gorm.DB, crossTransactionID uint64, tx *types.Tx, statusFail bool) error {
64         fromAddress := common.ProgToAddress(tx.Inputs[0].ControlProgram(), &consensus.MainNetParams)
65         for i, rawOutput := range tx.Outputs {
66                 if rawOutput.OutputType() != types.CrossChainOutputType {
67                         continue
68                 }
69
70                 if statusFail && *rawOutput.OutputCommitment().AssetAmount.AssetId != *consensus.BTMAssetID {
71                         continue
72                 }
73
74                 asset, err := s.assetStore.GetByAssetID(rawOutput.OutputCommitment().AssetAmount.AssetId.String())
75                 if err != nil {
76                         return err
77                 }
78
79                 prog := rawOutput.ControlProgram()
80                 req := &orm.CrossTransactionReq{
81                         CrossTransactionID: crossTransactionID,
82                         SourcePos:          uint64(i),
83                         AssetID:            asset.ID,
84                         AssetAmount:        rawOutput.OutputCommitment().AssetAmount.Amount,
85                         Script:             hex.EncodeToString(prog),
86                         FromAddress:        fromAddress,
87                         ToAddress:          common.ProgToAddress(prog, &consensus.BytomMainNetParams),
88                 }
89
90                 if err := db.Create(req).Error; err != nil {
91                         return err
92                 }
93         }
94         return nil
95 }
96
97 func (s *sidechainKeeper) isDepositTx(tx *types.Tx) bool {
98         for _, input := range tx.Inputs {
99                 if input.InputType() == types.CrossChainInputType {
100                         return true
101                 }
102         }
103         return false
104 }
105
106 func (s *sidechainKeeper) isWithdrawalTx(tx *types.Tx) bool {
107         for _, output := range tx.Outputs {
108                 if output.OutputType() == types.CrossChainOutputType {
109                         return true
110                 }
111         }
112         return false
113 }
114
115 func (s *sidechainKeeper) processBlock(db *gorm.DB, block *types.Block, txStatus *bc.TransactionStatus) error {
116         for i, tx := range block.Transactions {
117                 if s.isDepositTx(tx) {
118                         if err := s.processDepositTx(db, block, i); err != nil {
119                                 return err
120                         }
121                 }
122
123                 if s.isWithdrawalTx(tx) {
124                         if err := s.processWithdrawalTx(db, block, txStatus, i); err != nil {
125                                 return err
126                         }
127                 }
128         }
129         return nil
130 }
131
132 func (s *sidechainKeeper) processChainInfo(db *gorm.DB, block *types.Block) error {
133         blockHash := block.Hash()
134         res := db.Model(&orm.Chain{}).Where("block_hash = ?", block.PreviousBlockHash.String()).Updates(&orm.Chain{
135                 BlockHash:   blockHash.String(),
136                 BlockHeight: block.Height,
137         })
138         if err := res.Error; err != nil {
139                 return err
140         }
141
142         if res.RowsAffected != 1 {
143                 return ErrInconsistentDB
144         }
145
146         return nil
147 }
148
149 func (s *sidechainKeeper) processDepositTx(db *gorm.DB, block *types.Block, txIndex int) error {
150         tx := block.Transactions[txIndex]
151         sourceTxHash, err := s.locateMainChainTx(tx.Inputs[0])
152         if err != nil {
153                 return err
154         }
155
156         blockHash := block.Hash()
157         stmt := db.Model(&orm.CrossTransaction{}).Where(&orm.CrossTransaction{
158                 SourceTxHash: sourceTxHash,
159                 Status:       common.CrossTxPendingStatus,
160         }).UpdateColumn(&orm.CrossTransaction{
161                 DestBlockHeight:    sql.NullInt64{int64(block.Height), true},
162                 DestBlockTimestamp: sql.NullInt64{int64(block.Timestamp / 1000), true},
163                 DestBlockHash:      sql.NullString{blockHash.String(), true},
164                 DestTxIndex:        sql.NullInt64{int64(txIndex), true},
165                 DestTxHash:         sql.NullString{tx.ID.String(), true},
166                 Status:             common.CrossTxCompletedStatus,
167         })
168         if stmt.Error != nil {
169                 return stmt.Error
170         }
171
172         if stmt.RowsAffected != 1 {
173                 return errors.Wrap(ErrInconsistentDB, "fail on find deposit data on database")
174         }
175         return nil
176 }
177
178 func (s *sidechainKeeper) processWithdrawalTx(db *gorm.DB, block *types.Block, txStatus *bc.TransactionStatus, txIndex int) error {
179         tx := block.Transactions[txIndex]
180         var muxID bc.Hash
181         switch res := tx.Entries[*tx.ResultIds[0]].(type) {
182         case *bc.CrossChainOutput:
183                 muxID = *res.Source.Ref
184         case *bc.IntraChainOutput:
185                 muxID = *res.Source.Ref
186         case *bc.VoteOutput:
187                 muxID = *res.Source.Ref
188         case *bc.Retirement:
189                 muxID = *res.Source.Ref
190         default:
191                 return ErrOutputType
192         }
193
194         rawTx, err := tx.MarshalText()
195         if err != nil {
196                 return err
197         }
198
199         blockHash := block.Hash()
200         ormTx := &orm.CrossTransaction{
201                 ChainID:              s.chainID,
202                 SourceBlockHeight:    block.Height,
203                 SourceBlockTimestamp: block.Timestamp / 1000,
204                 SourceBlockHash:      blockHash.String(),
205                 SourceTxIndex:        uint64(txIndex),
206                 SourceMuxID:          muxID.String(),
207                 SourceTxHash:         tx.ID.String(),
208                 SourceRawTransaction: string(rawTx),
209                 DestBlockHeight:      sql.NullInt64{Valid: false},
210                 DestBlockTimestamp:   sql.NullInt64{Valid: false},
211                 DestBlockHash:        sql.NullString{Valid: false},
212                 DestTxIndex:          sql.NullInt64{Valid: false},
213                 DestTxHash:           sql.NullString{Valid: false},
214                 Status:               common.CrossTxPendingStatus,
215         }
216         if err := db.Create(ormTx).Error; err != nil {
217                 return errors.Wrap(err, fmt.Sprintf("create sidechain WithdrawalTx %s", tx.ID.String()))
218         }
219
220         return s.createCrossChainReqs(db, ormTx.ID, tx, txStatus.VerifyStatus[txIndex].StatusFail)
221 }
222
223 func (s *sidechainKeeper) locateMainChainTx(input *types.TxInput) (string, error) {
224         if input.InputType() != types.CrossChainInputType {
225                 return "", errors.New("found weird crossChain tx")
226         }
227
228         crossIn := input.TypedInput.(*types.CrossChainInput)
229         crossTx := &orm.CrossTransaction{SourceMuxID: crossIn.SpendCommitment.SourceID.String()}
230         if err := s.db.Where(crossTx).First(crossTx).Error; err != nil {
231                 return "", errors.Wrap(err, "fail on find CrossTransaction")
232         }
233         return crossTx.SourceTxHash, nil
234 }
235
236 func (s *sidechainKeeper) syncBlock() (bool, error) {
237         chain := &orm.Chain{ID: s.chainID}
238         if err := s.db.First(chain).Error; err != nil {
239                 return false, errors.Wrap(err, "query chain")
240         }
241
242         height, err := s.node.GetBlockCount()
243         if err != nil {
244                 return false, err
245         }
246
247         if height <= chain.BlockHeight+s.cfg.Confirmations {
248                 return false, nil
249         }
250
251         nextBlockStr, txStatus, err := s.node.GetBlockByHeight(chain.BlockHeight + 1)
252         if err != nil {
253                 return false, err
254         }
255
256         nextBlock := &types.Block{}
257         if err := nextBlock.UnmarshalText([]byte(nextBlockStr)); err != nil {
258                 return false, errors.New("Unmarshal nextBlock")
259         }
260
261         if nextBlock.PreviousBlockHash.String() != chain.BlockHash {
262                 log.WithFields(log.Fields{
263                         "remote previous_block_Hash": nextBlock.PreviousBlockHash.String(),
264                         "db block_hash":              chain.BlockHash,
265                 }).Fatal("fail on block hash mismatch")
266         }
267
268         if err := s.tryAttachBlock(nextBlock, txStatus); err != nil {
269                 return false, err
270         }
271
272         return true, nil
273 }
274
275 func (s *sidechainKeeper) tryAttachBlock(block *types.Block, txStatus *bc.TransactionStatus) error {
276         blockHash := block.Hash()
277         log.WithFields(log.Fields{"block_height": block.Height, "block_hash": blockHash.String()}).Info("start to attachBlock")
278
279         dbTx := s.db.Begin()
280         if err := s.processBlock(dbTx, block, txStatus); err != nil {
281                 dbTx.Rollback()
282                 return err
283         }
284
285         if err := s.processChainInfo(dbTx, block); err != nil {
286                 dbTx.Rollback()
287                 return err
288         }
289         return dbTx.Commit().Error
290 }