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 DestBlockHash: sql.NullString{blockHash.String(), true},
155 DestTxIndex: sql.NullInt64{int64(txIndex), true},
156 Status: common.CrossTxCompletedStatus,
158 if stmt.Error != nil {
162 if stmt.RowsAffected != 1 {
163 log.Warnf("sidechainKeeper.processDepositTx(%v): rows affected != 1", tx.ID.String())
168 func (s *sidechainKeeper) processWithdrawalTx(chain *orm.Chain, block *types.Block, txStatus *bc.TransactionStatus, txIndex uint64, tx *types.Tx) error {
169 blockHash := block.Hash()
172 res0ID := tx.ResultIds[0]
173 switch res := tx.Entries[*res0ID].(type) {
174 case *bc.CrossChainOutput:
175 muxID = *res.Source.Ref
176 case *bc.IntraChainOutput:
177 muxID = *res.Source.Ref
179 muxID = *res.Source.Ref
184 rawTx, err := tx.MarshalText()
189 ormTx := &orm.CrossTransaction{
191 SourceBlockHeight: block.Height,
192 SourceBlockHash: blockHash.String(),
193 SourceTxIndex: txIndex,
194 SourceMuxID: muxID.String(),
195 SourceTxHash: tx.ID.String(),
196 SourceRawTransaction: string(rawTx),
197 DestBlockHeight: sql.NullInt64{Valid: false},
198 DestBlockHash: sql.NullString{Valid: false},
199 DestTxIndex: sql.NullInt64{Valid: false},
200 DestTxHash: sql.NullString{Valid: false},
201 Status: common.CrossTxPendingStatus,
203 if err := s.db.Create(ormTx).Error; err != nil {
204 return errors.Wrap(err, fmt.Sprintf("create sidechain WithdrawalTx %s", tx.ID.String()))
207 statusFail := txStatus.VerifyStatus[txIndex].StatusFail
208 crossChainOutputs, err := s.getCrossChainReqs(ormTx.ID, tx, statusFail)
213 for _, output := range crossChainOutputs {
214 if err := s.db.Create(output).Error; err != nil {
215 return errors.Wrap(err, fmt.Sprintf("create WithdrawalFromSidechain output: txid(%s), pos(%d)", tx.ID.String(), output.SourcePos))
222 func (s *sidechainKeeper) getCrossChainReqs(crossTransactionID uint64, tx *types.Tx, statusFail bool) ([]*orm.CrossTransactionReq, error) {
223 reqs := []*orm.CrossTransactionReq{}
224 for i, rawOutput := range tx.Outputs {
225 // check valid withdrawal
226 if rawOutput.OutputType() != types.CrossChainOutputType {
230 if statusFail && *rawOutput.OutputCommitment().AssetAmount.AssetId != *consensus.BTMAssetID {
234 asset, err := s.assetStore.GetByAssetID(rawOutput.OutputCommitment().AssetAmount.AssetId.String())
239 req := &orm.CrossTransactionReq{
240 CrossTransactionID: crossTransactionID,
241 SourcePos: uint64(i),
243 AssetAmount: rawOutput.OutputCommitment().AssetAmount.Amount,
244 Script: hex.EncodeToString(rawOutput.ControlProgram()),
246 reqs = append(reqs, req)
251 func (s *sidechainKeeper) processChainInfo(chain *orm.Chain, block *types.Block) error {
252 blockHash := block.Hash()
253 chain.BlockHash = blockHash.String()
254 chain.BlockHeight = block.Height
255 res := s.db.Model(chain).Where("block_hash = ?", block.PreviousBlockHash.String()).Updates(chain)
256 if err := res.Error; err != nil {
260 if res.RowsAffected != 1 {
261 return ErrInconsistentDB