OSDN Git Service

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