OSDN Git Service

feat(federation): add address and timestamp (#223)
[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                 DestBlockTimestamp: sql.NullInt64{int64(block.Timestamp), true},
155                 DestBlockHash:      sql.NullString{blockHash.String(), true},
156                 DestTxIndex:        sql.NullInt64{int64(txIndex), true},
157                 Status:             common.CrossTxCompletedStatus,
158         })
159         if stmt.Error != nil {
160                 return stmt.Error
161         }
162
163         if stmt.RowsAffected != 1 {
164                 log.Warnf("sidechainKeeper.processDepositTx(%v): rows affected != 1", tx.ID.String())
165         }
166         return nil
167 }
168
169 func (s *sidechainKeeper) processWithdrawalTx(chain *orm.Chain, block *types.Block, txStatus *bc.TransactionStatus, txIndex uint64, tx *types.Tx) error {
170         blockHash := block.Hash()
171
172         var muxID bc.Hash
173         res0ID := tx.ResultIds[0]
174         switch res := tx.Entries[*res0ID].(type) {
175         case *bc.CrossChainOutput:
176                 muxID = *res.Source.Ref
177         case *bc.IntraChainOutput:
178                 muxID = *res.Source.Ref
179         case *bc.VoteOutput:
180                 muxID = *res.Source.Ref
181         default:
182                 return ErrOutputType
183         }
184
185         rawTx, err := tx.MarshalText()
186         if err != nil {
187                 return err
188         }
189
190         ormTx := &orm.CrossTransaction{
191                 ChainID:              chain.ID,
192                 SourceBlockHeight:    block.Height,
193                 SourceBlockTimestamp: block.Timestamp,
194                 SourceBlockHash:      blockHash.String(),
195                 SourceTxIndex:        txIndex,
196                 SourceMuxID:          muxID.String(),
197                 SourceTxHash:         tx.ID.String(),
198                 SourceRawTransaction: string(rawTx),
199                 DestBlockHeight:      sql.NullInt64{Valid: false},
200                 DestBlockTimestamp:   sql.NullInt64{Valid: false},
201                 DestBlockHash:        sql.NullString{Valid: false},
202                 DestTxIndex:          sql.NullInt64{Valid: false},
203                 DestTxHash:           sql.NullString{Valid: false},
204                 Status:               common.CrossTxPendingStatus,
205         }
206         if err := s.db.Create(ormTx).Error; err != nil {
207                 return errors.Wrap(err, fmt.Sprintf("create sidechain WithdrawalTx %s", tx.ID.String()))
208         }
209
210         statusFail := txStatus.VerifyStatus[txIndex].StatusFail
211         crossChainOutputs, err := s.getCrossChainReqs(ormTx.ID, tx, statusFail)
212         if err != nil {
213                 return err
214         }
215
216         for _, output := range crossChainOutputs {
217                 if err := s.db.Create(output).Error; err != nil {
218                         return errors.Wrap(err, fmt.Sprintf("create WithdrawalFromSidechain output: txid(%s), pos(%d)", tx.ID.String(), output.SourcePos))
219                 }
220         }
221
222         return nil
223 }
224
225 func (s *sidechainKeeper) getCrossChainReqs(crossTransactionID uint64, tx *types.Tx, statusFail bool) ([]*orm.CrossTransactionReq, error) {
226         reqs := []*orm.CrossTransactionReq{}
227         for i, rawOutput := range tx.Outputs {
228                 // check valid withdrawal
229                 if rawOutput.OutputType() != types.CrossChainOutputType {
230                         continue
231                 }
232
233                 if statusFail && *rawOutput.OutputCommitment().AssetAmount.AssetId != *consensus.BTMAssetID {
234                         continue
235                 }
236
237                 asset, err := s.assetStore.GetByAssetID(rawOutput.OutputCommitment().AssetAmount.AssetId.String())
238                 if err != nil {
239                         return nil, err
240                 }
241
242                 req := &orm.CrossTransactionReq{
243                         CrossTransactionID: crossTransactionID,
244                         SourcePos:          uint64(i),
245                         AssetID:            asset.ID,
246                         AssetAmount:        rawOutput.OutputCommitment().AssetAmount.Amount,
247                         Script:             hex.EncodeToString(rawOutput.ControlProgram()),
248                 }
249                 reqs = append(reqs, req)
250         }
251         return reqs, nil
252 }
253
254 func (s *sidechainKeeper) processChainInfo(chain *orm.Chain, block *types.Block) error {
255         blockHash := block.Hash()
256         chain.BlockHash = blockHash.String()
257         chain.BlockHeight = block.Height
258         res := s.db.Model(chain).Where("block_hash = ?", block.PreviousBlockHash.String()).Updates(chain)
259         if err := res.Error; err != nil {
260                 return err
261         }
262
263         if res.RowsAffected != 1 {
264                 return ErrInconsistentDB
265         }
266
267         return nil
268 }