OSDN Git Service

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