9 "github.com/jinzhu/gorm"
10 log "github.com/sirupsen/logrus"
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"
23 type sidechainKeeper struct {
28 assetStore *database.AssetStore
31 func NewSidechainKeeper(db *gorm.DB, assetStore *database.AssetStore, cfg *config.Config) *sidechainKeeper {
32 return &sidechainKeeper{
35 node: service.NewNode(cfg.Sidechain.Upstream),
36 chainName: cfg.Sidechain.Name,
37 assetStore: assetStore,
41 func (s *sidechainKeeper) Run() {
42 ticker := time.NewTicker(time.Duration(s.cfg.SyncSeconds) * time.Second)
43 for ; true; <-ticker.C {
45 isUpdate, err := s.syncBlock()
47 log.WithField("error", err).Errorln("blockKeeper fail on process block")
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")
64 height, err := s.node.GetBlockCount()
69 if height <= chain.BlockHeight+s.cfg.Confirmations {
73 nextBlockStr, txStatus, err := s.node.GetBlockByHeight(chain.BlockHeight + 1)
78 nextBlock := &types.Block{}
79 if err := nextBlock.UnmarshalText([]byte(nextBlockStr)); err != nil {
80 return false, errors.New("Unmarshal nextBlock")
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
91 if err := s.tryAttachBlock(chain, nextBlock, txStatus); err != nil {
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")
102 if err := s.processBlock(chain, block, txStatus); err != nil {
107 return dbTx.Commit().Error
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 {
118 if s.isWithdrawalTx(tx) {
119 if err := s.processWithdrawalTx(chain, block, txStatus, uint64(i), tx); err != nil {
125 return s.processChainInfo(chain, block)
128 func (s *sidechainKeeper) isDepositTx(tx *types.Tx) bool {
129 for _, input := range tx.Inputs {
130 if input.InputType() == types.CrossChainInputType {
137 func (s *sidechainKeeper) isWithdrawalTx(tx *types.Tx) bool {
138 for _, output := range tx.Outputs {
139 if output.OutputType() == types.CrossChainOutputType {
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,
159 if stmt.Error != nil {
163 if stmt.RowsAffected != 1 {
164 log.Warnf("sidechainKeeper.processDepositTx(%v): rows affected != 1", tx.ID.String())
169 func (s *sidechainKeeper) processWithdrawalTx(chain *orm.Chain, block *types.Block, txStatus *bc.TransactionStatus, txIndex uint64, tx *types.Tx) error {
170 blockHash := block.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
180 muxID = *res.Source.Ref
185 rawTx, err := tx.MarshalText()
190 ormTx := &orm.CrossTransaction{
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,
206 if err := s.db.Create(ormTx).Error; err != nil {
207 return errors.Wrap(err, fmt.Sprintf("create sidechain WithdrawalTx %s", tx.ID.String()))
210 statusFail := txStatus.VerifyStatus[txIndex].StatusFail
211 crossChainOutputs, err := s.getCrossChainReqs(ormTx.ID, tx, statusFail)
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))
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 {
233 if statusFail && *rawOutput.OutputCommitment().AssetAmount.AssetId != *consensus.BTMAssetID {
237 asset, err := s.assetStore.GetByAssetID(rawOutput.OutputCommitment().AssetAmount.AssetId.String())
242 req := &orm.CrossTransactionReq{
243 CrossTransactionID: crossTransactionID,
244 SourcePos: uint64(i),
246 AssetAmount: rawOutput.OutputCommitment().AssetAmount.Amount,
247 Script: hex.EncodeToString(rawOutput.ControlProgram()),
249 reqs = append(reqs, req)
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 {
263 if res.RowsAffected != 1 {
264 return ErrInconsistentDB