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/protocol/bc"
15 "github.com/vapor/protocol/bc/types"
16 "github.com/vapor/toolbar/federation/common"
17 "github.com/vapor/toolbar/federation/config"
18 "github.com/vapor/toolbar/federation/database"
19 "github.com/vapor/toolbar/federation/database/orm"
20 "github.com/vapor/toolbar/federation/service"
23 type sidechainKeeper struct {
27 assetStore *database.AssetStore
29 netParams consensus.Params
32 func NewSidechainKeeper(db *gorm.DB, assetStore *database.AssetStore, cfg *config.Config) *sidechainKeeper {
33 chain := &orm.Chain{Name: common.VaporChainName}
34 if err := db.Where(chain).First(chain).Error; err != nil {
35 log.WithField("err", err).Fatal("fail on get chain info")
38 return &sidechainKeeper{
41 node: service.NewNode(cfg.Sidechain.Upstream),
42 assetStore: assetStore,
44 netParams: consensus.NetParams[cfg.Network],
48 func (s *sidechainKeeper) Run() {
49 ticker := time.NewTicker(time.Duration(s.cfg.SyncSeconds) * time.Second)
50 for ; true; <-ticker.C {
52 isUpdate, err := s.syncBlock()
54 log.WithField("error", err).Errorln("blockKeeper fail on process block")
65 func (s *sidechainKeeper) createCrossChainReqs(db *gorm.DB, crossTransactionID uint64, tx *types.Tx, statusFail bool) error {
66 fromAddress := common.ProgToAddress(tx.Inputs[0].ControlProgram(), &s.netParams)
67 for i, rawOutput := range tx.Outputs {
68 if rawOutput.OutputType() != types.CrossChainOutputType {
72 if statusFail && *rawOutput.OutputCommitment().AssetAmount.AssetId != *consensus.BTMAssetID {
76 asset, err := s.assetStore.GetByAssetID(rawOutput.OutputCommitment().AssetAmount.AssetId.String())
81 prog := rawOutput.ControlProgram()
82 req := &orm.CrossTransactionReq{
83 CrossTransactionID: crossTransactionID,
86 AssetAmount: rawOutput.OutputCommitment().AssetAmount.Amount,
87 Script: hex.EncodeToString(prog),
88 FromAddress: fromAddress,
89 ToAddress: common.ProgToAddress(prog, consensus.BytomMainNetParams(&s.netParams)),
92 if err := db.Create(req).Error; err != nil {
99 func (s *sidechainKeeper) isDepositTx(tx *types.Tx) bool {
100 for _, input := range tx.Inputs {
101 if input.InputType() == types.CrossChainInputType {
108 func (s *sidechainKeeper) isWithdrawalTx(tx *types.Tx) bool {
109 for _, output := range tx.Outputs {
110 if output.OutputType() == types.CrossChainOutputType {
117 func (s *sidechainKeeper) processBlock(db *gorm.DB, block *types.Block, txStatus *bc.TransactionStatus) error {
118 for i, tx := range block.Transactions {
119 if s.isDepositTx(tx) {
120 if err := s.processDepositTx(db, block, i); err != nil {
125 if s.isWithdrawalTx(tx) {
126 if err := s.processWithdrawalTx(db, block, txStatus, i); err != nil {
134 func (s *sidechainKeeper) processChainInfo(db *gorm.DB, block *types.Block) error {
135 blockHash := block.Hash()
136 res := db.Model(&orm.Chain{}).Where("block_hash = ?", block.PreviousBlockHash.String()).Updates(&orm.Chain{
137 BlockHash: blockHash.String(),
138 BlockHeight: block.Height,
140 if err := res.Error; err != nil {
144 if res.RowsAffected != 1 {
145 return ErrInconsistentDB
151 func (s *sidechainKeeper) processDepositTx(db *gorm.DB, block *types.Block, txIndex int) error {
152 tx := block.Transactions[txIndex]
153 sourceTxHash, err := s.locateMainChainTx(tx.Inputs[0])
158 blockHash := block.Hash()
159 stmt := db.Model(&orm.CrossTransaction{}).Where(&orm.CrossTransaction{
160 SourceTxHash: sourceTxHash,
161 Status: common.CrossTxPendingStatus,
162 }).UpdateColumn(&orm.CrossTransaction{
163 DestBlockHeight: sql.NullInt64{int64(block.Height), true},
164 DestBlockTimestamp: sql.NullInt64{int64(block.Timestamp / 1000), true},
165 DestBlockHash: sql.NullString{blockHash.String(), true},
166 DestTxIndex: sql.NullInt64{int64(txIndex), true},
167 DestTxHash: sql.NullString{tx.ID.String(), true},
168 Status: common.CrossTxCompletedStatus,
170 if stmt.Error != nil {
174 if stmt.RowsAffected != 1 {
175 return errors.Wrap(ErrInconsistentDB, "fail on find deposit data on database")
180 func (s *sidechainKeeper) processWithdrawalTx(db *gorm.DB, block *types.Block, txStatus *bc.TransactionStatus, txIndex int) error {
181 tx := block.Transactions[txIndex]
183 switch res := tx.Entries[*tx.ResultIds[0]].(type) {
184 case *bc.CrossChainOutput:
185 muxID = *res.Source.Ref
186 case *bc.IntraChainOutput:
187 muxID = *res.Source.Ref
189 muxID = *res.Source.Ref
191 muxID = *res.Source.Ref
196 rawTx, err := tx.MarshalText()
201 blockHash := block.Hash()
202 ormTx := &orm.CrossTransaction{
204 SourceBlockHeight: block.Height,
205 SourceBlockTimestamp: block.Timestamp / 1000,
206 SourceBlockHash: blockHash.String(),
207 SourceTxIndex: uint64(txIndex),
208 SourceMuxID: muxID.String(),
209 SourceTxHash: tx.ID.String(),
210 SourceRawTransaction: string(rawTx),
211 DestBlockHeight: sql.NullInt64{Valid: false},
212 DestBlockTimestamp: sql.NullInt64{Valid: false},
213 DestBlockHash: sql.NullString{Valid: false},
214 DestTxIndex: sql.NullInt64{Valid: false},
215 DestTxHash: sql.NullString{Valid: false},
216 Status: common.CrossTxPendingStatus,
218 if err := db.Create(ormTx).Error; err != nil {
219 return errors.Wrap(err, fmt.Sprintf("create sidechain WithdrawalTx %s", tx.ID.String()))
222 return s.createCrossChainReqs(db, ormTx.ID, tx, txStatus.VerifyStatus[txIndex].StatusFail)
225 func (s *sidechainKeeper) locateMainChainTx(input *types.TxInput) (string, error) {
226 if input.InputType() != types.CrossChainInputType {
227 return "", errors.New("found weird crossChain tx")
230 crossIn := input.TypedInput.(*types.CrossChainInput)
231 crossTx := &orm.CrossTransaction{SourceMuxID: crossIn.SpendCommitment.SourceID.String()}
232 if err := s.db.Where(crossTx).First(crossTx).Error; err != nil {
233 return "", errors.Wrap(err, "fail on find CrossTransaction")
235 return crossTx.SourceTxHash, nil
238 func (s *sidechainKeeper) syncBlock() (bool, error) {
239 chain := &orm.Chain{ID: s.chainID}
240 if err := s.db.First(chain).Error; err != nil {
241 return false, errors.Wrap(err, "query chain")
244 height, err := s.node.GetBlockCount()
249 if height <= chain.BlockHeight+s.cfg.Confirmations {
253 nextBlockStr, txStatus, err := s.node.GetBlockByHeight(chain.BlockHeight + 1)
258 nextBlock := &types.Block{}
259 if err := nextBlock.UnmarshalText([]byte(nextBlockStr)); err != nil {
260 return false, errors.New("Unmarshal nextBlock")
263 if nextBlock.PreviousBlockHash.String() != chain.BlockHash {
264 log.WithFields(log.Fields{
265 "remote previous_block_Hash": nextBlock.PreviousBlockHash.String(),
266 "db block_hash": chain.BlockHash,
267 }).Fatal("fail on block hash mismatch")
270 if err := s.tryAttachBlock(nextBlock, txStatus); err != nil {
277 func (s *sidechainKeeper) tryAttachBlock(block *types.Block, txStatus *bc.TransactionStatus) error {
278 blockHash := block.Hash()
279 log.WithFields(log.Fields{"block_height": block.Height, "block_hash": blockHash.String()}).Info("start to attachBlock")
282 if err := s.processBlock(dbTx, block, txStatus); err != nil {
287 if err := s.processChainInfo(dbTx, block); err != nil {
291 return dbTx.Commit().Error