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 {
27 assetStore *database.AssetStore
31 func NewSidechainKeeper(db *gorm.DB, assetStore *database.AssetStore, cfg *config.Config) *sidechainKeeper {
32 chain := &orm.Chain{Name: common.VaporChainName}
33 if err := db.Where(chain).First(chain).Error; err != nil {
34 log.WithField("err", err).Fatal("fail on get chain info")
37 return &sidechainKeeper{
40 node: service.NewNode(cfg.Sidechain.Upstream),
41 assetStore: assetStore,
45 func (s *sidechainKeeper) Run() {
46 ticker := time.NewTicker(time.Duration(s.cfg.SyncSeconds) * time.Second)
47 for ; true; <-ticker.C {
49 isUpdate, err := s.syncBlock()
51 log.WithField("error", err).Errorln("blockKeeper fail on process block")
62 func (s *sidechainKeeper) createCrossChainReqs(db *gorm.DB, crossTransactionID uint64, tx *types.Tx, statusFail bool) error {
63 fromAddress := common.ProgToAddress(tx.Inputs[0].ControlProgram(), &consensus.MainNetParams)
64 for i, rawOutput := range tx.Outputs {
65 if rawOutput.OutputType() != types.CrossChainOutputType {
69 if statusFail && *rawOutput.OutputCommitment().AssetAmount.AssetId != *consensus.BTMAssetID {
73 asset, err := s.assetStore.GetByAssetID(rawOutput.OutputCommitment().AssetAmount.AssetId.String())
78 prog := rawOutput.ControlProgram()
79 req := &orm.CrossTransactionReq{
80 CrossTransactionID: crossTransactionID,
83 AssetAmount: rawOutput.OutputCommitment().AssetAmount.Amount,
84 Script: hex.EncodeToString(prog),
85 FromAddress: fromAddress,
86 ToAddress: common.ProgToAddress(prog, &consensus.BytomMainNetParams),
89 if err := db.Create(req).Error; err != nil {
96 func (s *sidechainKeeper) isDepositTx(tx *types.Tx) bool {
97 for _, input := range tx.Inputs {
98 if input.InputType() == types.CrossChainInputType {
105 func (s *sidechainKeeper) isWithdrawalTx(tx *types.Tx) bool {
106 for _, output := range tx.Outputs {
107 if output.OutputType() == types.CrossChainOutputType {
114 func (s *sidechainKeeper) processBlock(db *gorm.DB, block *types.Block, txStatus *bc.TransactionStatus) error {
115 for i, tx := range block.Transactions {
116 if s.isDepositTx(tx) {
117 if err := s.processDepositTx(db, block, i); err != nil {
122 if s.isWithdrawalTx(tx) {
123 if err := s.processWithdrawalTx(db, block, txStatus, i); err != nil {
131 func (s *sidechainKeeper) processChainInfo(db *gorm.DB, block *types.Block) error {
132 blockHash := block.Hash()
133 res := db.Model(&orm.Chain{}).Where("block_hash = ?", block.PreviousBlockHash.String()).Updates(&orm.Chain{
134 BlockHash: blockHash.String(),
135 BlockHeight: block.Height,
137 if err := res.Error; err != nil {
141 if res.RowsAffected != 1 {
142 return ErrInconsistentDB
148 func (s *sidechainKeeper) processDepositTx(db *gorm.DB, block *types.Block, txIndex int) error {
149 tx := block.Transactions[txIndex]
150 sourceTxHash, err := s.locateMainChainTx(tx.Inputs[0])
155 blockHash := block.Hash()
156 stmt := db.Model(&orm.CrossTransaction{}).Where(&orm.CrossTransaction{
157 SourceTxHash: sourceTxHash,
158 Status: common.CrossTxPendingStatus,
159 }).UpdateColumn(&orm.CrossTransaction{
160 DestBlockHeight: sql.NullInt64{int64(block.Height), true},
161 DestBlockTimestamp: sql.NullInt64{int64(block.Timestamp), true},
162 DestBlockHash: sql.NullString{blockHash.String(), true},
163 DestTxIndex: sql.NullInt64{int64(txIndex), true},
164 DestTxHash: sql.NullString{tx.ID.String(), true},
165 Status: common.CrossTxCompletedStatus,
167 if stmt.Error != nil {
171 if stmt.RowsAffected != 1 {
172 return errors.Wrap(ErrInconsistentDB, "fail on find deposit data on database")
177 func (s *sidechainKeeper) processWithdrawalTx(db *gorm.DB, block *types.Block, txStatus *bc.TransactionStatus, txIndex int) error {
178 tx := block.Transactions[txIndex]
180 switch res := tx.Entries[*tx.ResultIds[0]].(type) {
181 case *bc.CrossChainOutput:
182 muxID = *res.Source.Ref
183 case *bc.IntraChainOutput:
184 muxID = *res.Source.Ref
186 muxID = *res.Source.Ref
188 muxID = *res.Source.Ref
193 rawTx, err := tx.MarshalText()
198 blockHash := block.Hash()
199 ormTx := &orm.CrossTransaction{
201 SourceBlockHeight: block.Height,
202 SourceBlockTimestamp: block.Timestamp,
203 SourceBlockHash: blockHash.String(),
204 SourceTxIndex: uint64(txIndex),
205 SourceMuxID: muxID.String(),
206 SourceTxHash: tx.ID.String(),
207 SourceRawTransaction: string(rawTx),
208 DestBlockHeight: sql.NullInt64{Valid: false},
209 DestBlockTimestamp: sql.NullInt64{Valid: false},
210 DestBlockHash: sql.NullString{Valid: false},
211 DestTxIndex: sql.NullInt64{Valid: false},
212 DestTxHash: sql.NullString{Valid: false},
213 Status: common.CrossTxPendingStatus,
215 if err := db.Create(ormTx).Error; err != nil {
216 return errors.Wrap(err, fmt.Sprintf("create sidechain WithdrawalTx %s", tx.ID.String()))
219 return s.createCrossChainReqs(db, ormTx.ID, tx, txStatus.VerifyStatus[txIndex].StatusFail)
222 func (s *sidechainKeeper) locateMainChainTx(input *types.TxInput) (string, error) {
223 if input.InputType() != types.CrossChainInputType {
224 return "", errors.New("found weird crossChain tx")
227 crossIn := input.TypedInput.(*types.CrossChainInput)
228 crossTx := &orm.CrossTransaction{SourceMuxID: crossIn.SpendCommitment.SourceID.String()}
229 if err := s.db.Where(crossTx).First(crossTx).Error; err != nil {
230 return "", errors.Wrap(err, "fail on find CrossTransaction")
232 return crossTx.SourceTxHash, nil
235 func (s *sidechainKeeper) syncBlock() (bool, error) {
236 chain := &orm.Chain{ID: s.chainID}
237 if err := s.db.First(chain).Error; err != nil {
238 return false, errors.Wrap(err, "query chain")
241 height, err := s.node.GetBlockCount()
246 if height <= chain.BlockHeight+s.cfg.Confirmations {
250 nextBlockStr, txStatus, err := s.node.GetBlockByHeight(chain.BlockHeight + 1)
255 nextBlock := &types.Block{}
256 if err := nextBlock.UnmarshalText([]byte(nextBlockStr)); err != nil {
257 return false, errors.New("Unmarshal nextBlock")
260 if nextBlock.PreviousBlockHash.String() != chain.BlockHash {
261 log.WithFields(log.Fields{
262 "remote previous_block_Hash": nextBlock.PreviousBlockHash.String(),
263 "db block_hash": chain.BlockHash,
264 }).Fatal("fail on block hash mismatch")
267 if err := s.tryAttachBlock(nextBlock, txStatus); err != nil {
274 func (s *sidechainKeeper) tryAttachBlock(block *types.Block, txStatus *bc.TransactionStatus) error {
275 blockHash := block.Hash()
276 log.WithFields(log.Fields{"block_height": block.Height, "block_hash": blockHash.String()}).Info("start to attachBlock")
279 if err := s.processBlock(dbTx, block, txStatus); err != nil {
284 if err := s.processChainInfo(dbTx, block); err != nil {
288 return dbTx.Commit().Error