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,
46 func (s *sidechainKeeper) Run() {
47 ticker := time.NewTicker(time.Duration(s.cfg.SyncSeconds) * time.Second)
48 for ; true; <-ticker.C {
50 isUpdate, err := s.syncBlock()
52 log.WithField("error", err).Errorln("blockKeeper fail on process block")
63 func (s *sidechainKeeper) createCrossChainReqs(db *gorm.DB, crossTransactionID uint64, tx *types.Tx, statusFail bool) error {
64 fromAddress := common.ProgToAddress(tx.Inputs[0].ControlProgram(), &consensus.MainNetParams)
65 for i, rawOutput := range tx.Outputs {
66 if rawOutput.OutputType() != types.CrossChainOutputType {
70 if statusFail && *rawOutput.OutputCommitment().AssetAmount.AssetId != *consensus.BTMAssetID {
74 asset, err := s.assetStore.GetByAssetID(rawOutput.OutputCommitment().AssetAmount.AssetId.String())
79 prog := rawOutput.ControlProgram()
80 req := &orm.CrossTransactionReq{
81 CrossTransactionID: crossTransactionID,
84 AssetAmount: rawOutput.OutputCommitment().AssetAmount.Amount,
85 Script: hex.EncodeToString(prog),
86 FromAddress: fromAddress,
87 ToAddress: common.ProgToAddress(prog, &consensus.BytomMainNetParams),
90 if err := db.Create(req).Error; err != nil {
97 func (s *sidechainKeeper) isDepositTx(tx *types.Tx) bool {
98 for _, input := range tx.Inputs {
99 if input.InputType() == types.CrossChainInputType {
106 func (s *sidechainKeeper) isWithdrawalTx(tx *types.Tx) bool {
107 for _, output := range tx.Outputs {
108 if output.OutputType() == types.CrossChainOutputType {
115 func (s *sidechainKeeper) processBlock(db *gorm.DB, block *types.Block, txStatus *bc.TransactionStatus) error {
116 for i, tx := range block.Transactions {
117 if s.isDepositTx(tx) {
118 if err := s.processDepositTx(db, block, i); err != nil {
123 if s.isWithdrawalTx(tx) {
124 if err := s.processWithdrawalTx(db, block, txStatus, i); err != nil {
132 func (s *sidechainKeeper) processChainInfo(db *gorm.DB, block *types.Block) error {
133 blockHash := block.Hash()
134 res := db.Model(&orm.Chain{}).Where("block_hash = ?", block.PreviousBlockHash.String()).Updates(&orm.Chain{
135 BlockHash: blockHash.String(),
136 BlockHeight: block.Height,
138 if err := res.Error; err != nil {
142 if res.RowsAffected != 1 {
143 return ErrInconsistentDB
149 func (s *sidechainKeeper) processDepositTx(db *gorm.DB, block *types.Block, txIndex int) error {
150 tx := block.Transactions[txIndex]
151 sourceTxHash, err := s.locateMainChainTx(tx.Inputs[0])
156 blockHash := block.Hash()
157 stmt := db.Model(&orm.CrossTransaction{}).Where(&orm.CrossTransaction{
158 SourceTxHash: sourceTxHash,
159 Status: common.CrossTxPendingStatus,
160 }).UpdateColumn(&orm.CrossTransaction{
161 DestBlockHeight: sql.NullInt64{int64(block.Height), true},
162 DestBlockTimestamp: sql.NullInt64{int64(block.Timestamp), true},
163 DestBlockHash: sql.NullString{blockHash.String(), true},
164 DestTxIndex: sql.NullInt64{int64(txIndex), true},
165 DestTxHash: sql.NullString{tx.ID.String(), true},
166 Status: common.CrossTxCompletedStatus,
168 if stmt.Error != nil {
172 if stmt.RowsAffected != 1 {
173 return errors.Wrap(ErrInconsistentDB, "fail on find deposit data on database")
178 func (s *sidechainKeeper) processWithdrawalTx(db *gorm.DB, block *types.Block, txStatus *bc.TransactionStatus, txIndex int) error {
179 tx := block.Transactions[txIndex]
181 switch res := tx.Entries[*tx.ResultIds[0]].(type) {
182 case *bc.CrossChainOutput:
183 muxID = *res.Source.Ref
184 case *bc.IntraChainOutput:
185 muxID = *res.Source.Ref
187 muxID = *res.Source.Ref
189 muxID = *res.Source.Ref
194 rawTx, err := tx.MarshalText()
199 blockHash := block.Hash()
200 ormTx := &orm.CrossTransaction{
202 SourceBlockHeight: block.Height,
203 SourceBlockTimestamp: block.Timestamp,
204 SourceBlockHash: blockHash.String(),
205 SourceTxIndex: uint64(txIndex),
206 SourceMuxID: muxID.String(),
207 SourceTxHash: tx.ID.String(),
208 SourceRawTransaction: string(rawTx),
209 DestBlockHeight: sql.NullInt64{Valid: false},
210 DestBlockTimestamp: sql.NullInt64{Valid: false},
211 DestBlockHash: sql.NullString{Valid: false},
212 DestTxIndex: sql.NullInt64{Valid: false},
213 DestTxHash: sql.NullString{Valid: false},
214 Status: common.CrossTxPendingStatus,
216 if err := db.Create(ormTx).Error; err != nil {
217 return errors.Wrap(err, fmt.Sprintf("create sidechain WithdrawalTx %s", tx.ID.String()))
220 return s.createCrossChainReqs(db, ormTx.ID, tx, txStatus.VerifyStatus[txIndex].StatusFail)
223 func (s *sidechainKeeper) locateMainChainTx(input *types.TxInput) (string, error) {
224 if input.InputType() != types.CrossChainInputType {
225 return "", errors.New("found weird crossChain tx")
228 crossIn := input.TypedInput.(*types.CrossChainInput)
229 crossTx := &orm.CrossTransaction{SourceMuxID: crossIn.SpendCommitment.SourceID.String()}
230 if err := s.db.Where(crossTx).First(crossTx).Error; err != nil {
231 return "", errors.Wrap(err, "fail on find CrossTransaction")
233 return crossTx.SourceTxHash, nil
236 func (s *sidechainKeeper) syncBlock() (bool, error) {
237 chain := &orm.Chain{ID: s.chainID}
238 if err := s.db.First(chain).Error; err != nil {
239 return false, errors.Wrap(err, "query chain")
242 height, err := s.node.GetBlockCount()
247 if height <= chain.BlockHeight+s.cfg.Confirmations {
251 nextBlockStr, txStatus, err := s.node.GetBlockByHeight(chain.BlockHeight + 1)
256 nextBlock := &types.Block{}
257 if err := nextBlock.UnmarshalText([]byte(nextBlockStr)); err != nil {
258 return false, errors.New("Unmarshal nextBlock")
261 if nextBlock.PreviousBlockHash.String() != chain.BlockHash {
262 log.WithFields(log.Fields{
263 "remote previous_block_Hash": nextBlock.PreviousBlockHash.String(),
264 "db block_hash": chain.BlockHash,
265 }).Fatal("fail on block hash mismatch")
268 if err := s.tryAttachBlock(nextBlock, txStatus); err != nil {
275 func (s *sidechainKeeper) tryAttachBlock(block *types.Block, txStatus *bc.TransactionStatus) error {
276 blockHash := block.Hash()
277 log.WithFields(log.Fields{"block_height": block.Height, "block_hash": blockHash.String()}).Info("start to attachBlock")
280 if err := s.processBlock(dbTx, block, txStatus); err != nil {
285 if err := s.processChainInfo(dbTx, block); err != nil {
289 return dbTx.Commit().Error