OSDN Git Service

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