9 "github.com/jinzhu/gorm"
10 log "github.com/sirupsen/logrus"
12 "github.com/vapor/consensus"
13 "github.com/vapor/consensus/segwit"
14 "github.com/vapor/errors"
15 "github.com/vapor/federation/common"
16 "github.com/vapor/federation/config"
17 "github.com/vapor/federation/database"
18 "github.com/vapor/federation/database/orm"
19 "github.com/vapor/federation/service"
20 "github.com/vapor/protocol/bc"
21 "github.com/vapor/protocol/bc/types"
22 "github.com/vapor/wallet"
25 type sidechainKeeper struct {
30 assetStore *database.AssetStore
33 func NewSidechainKeeper(db *gorm.DB, assetStore *database.AssetStore, cfg *config.Config) *sidechainKeeper {
34 return &sidechainKeeper{
37 node: service.NewNode(cfg.Sidechain.Upstream),
38 chainName: cfg.Sidechain.Name,
39 assetStore: assetStore,
43 func (s *sidechainKeeper) Run() {
44 ticker := time.NewTicker(time.Duration(s.cfg.SyncSeconds) * time.Second)
45 for ; true; <-ticker.C {
47 isUpdate, err := s.syncBlock()
49 log.WithField("error", err).Errorln("blockKeeper fail on process block")
60 func (s *sidechainKeeper) syncBlock() (bool, error) {
61 chain := &orm.Chain{Name: s.chainName}
62 if err := s.db.Where(chain).First(chain).Error; err != nil {
63 return false, errors.Wrap(err, "query chain")
66 height, err := s.node.GetBlockCount()
71 if height <= chain.BlockHeight+s.cfg.Confirmations {
75 nextBlockStr, txStatus, err := s.node.GetBlockByHeight(chain.BlockHeight + 1)
80 nextBlock := &types.Block{}
81 if err := nextBlock.UnmarshalText([]byte(nextBlockStr)); err != nil {
82 return false, errors.New("Unmarshal nextBlock")
85 if nextBlock.PreviousBlockHash.String() != chain.BlockHash {
86 log.WithFields(log.Fields{
87 "remote PreviousBlockHash": nextBlock.PreviousBlockHash.String(),
88 "db block_hash": chain.BlockHash,
89 }).Fatal("BlockHash mismatch")
90 return false, ErrInconsistentDB
93 if err := s.tryAttachBlock(chain, nextBlock, txStatus); err != nil {
100 func (s *sidechainKeeper) tryAttachBlock(chain *orm.Chain, block *types.Block, txStatus *bc.TransactionStatus) error {
101 blockHash := block.Hash()
102 log.WithFields(log.Fields{"block_height": block.Height, "block_hash": blockHash.String()}).Info("start to attachBlock")
104 if err := s.processBlock(chain, block, txStatus); err != nil {
109 return dbTx.Commit().Error
112 func (s *sidechainKeeper) processBlock(chain *orm.Chain, block *types.Block, txStatus *bc.TransactionStatus) error {
113 for i, tx := range block.Transactions {
114 if s.isDepositTx(tx) {
115 if err := s.processDepositTx(chain, block, uint64(i), tx); err != nil {
120 if s.isWithdrawalTx(tx) {
121 if err := s.processWithdrawalTx(chain, block, txStatus, uint64(i), tx); err != nil {
127 return s.processChainInfo(chain, block)
130 func (s *sidechainKeeper) isDepositTx(tx *types.Tx) bool {
131 for _, input := range tx.Inputs {
132 if input.InputType() == types.CrossChainInputType {
139 func (s *sidechainKeeper) isWithdrawalTx(tx *types.Tx) bool {
140 for _, output := range tx.Outputs {
141 if output.OutputType() == types.CrossChainOutputType {
148 func (s *sidechainKeeper) processDepositTx(chain *orm.Chain, block *types.Block, txIndex uint64, tx *types.Tx) error {
149 blockHash := block.Hash()
150 stmt := s.db.Model(&orm.CrossTransaction{}).Where("chain_id != ?", chain.ID).
151 Where(&orm.CrossTransaction{
152 DestTxHash: sql.NullString{tx.ID.String(), true},
153 Status: common.CrossTxPendingStatus,
154 }).UpdateColumn(&orm.CrossTransaction{
155 DestBlockHeight: sql.NullInt64{int64(block.Height), true},
156 DestBlockTimestamp: sql.NullInt64{int64(block.Timestamp), true},
157 DestBlockHash: sql.NullString{blockHash.String(), true},
158 DestTxIndex: sql.NullInt64{int64(txIndex), true},
159 Status: common.CrossTxCompletedStatus,
161 if stmt.Error != nil {
165 if stmt.RowsAffected != 1 {
166 log.Warnf("sidechainKeeper.processDepositTx(%v): rows affected != 1", tx.ID.String())
171 func (s *sidechainKeeper) processWithdrawalTx(chain *orm.Chain, block *types.Block, txStatus *bc.TransactionStatus, txIndex uint64, tx *types.Tx) error {
172 blockHash := block.Hash()
175 res0ID := tx.ResultIds[0]
176 switch res := tx.Entries[*res0ID].(type) {
177 case *bc.CrossChainOutput:
178 muxID = *res.Source.Ref
179 case *bc.IntraChainOutput:
180 muxID = *res.Source.Ref
182 muxID = *res.Source.Ref
187 rawTx, err := tx.MarshalText()
192 ormTx := &orm.CrossTransaction{
194 SourceBlockHeight: block.Height,
195 SourceBlockTimestamp: block.Timestamp,
196 SourceBlockHash: blockHash.String(),
197 SourceTxIndex: txIndex,
198 SourceMuxID: muxID.String(),
199 SourceTxHash: tx.ID.String(),
200 SourceRawTransaction: string(rawTx),
201 DestBlockHeight: sql.NullInt64{Valid: false},
202 DestBlockTimestamp: sql.NullInt64{Valid: false},
203 DestBlockHash: sql.NullString{Valid: false},
204 DestTxIndex: sql.NullInt64{Valid: false},
205 DestTxHash: sql.NullString{Valid: false},
206 Status: common.CrossTxPendingStatus,
208 if err := s.db.Create(ormTx).Error; err != nil {
209 return errors.Wrap(err, fmt.Sprintf("create sidechain WithdrawalTx %s", tx.ID.String()))
212 statusFail := txStatus.VerifyStatus[txIndex].StatusFail
213 crossChainOutputs, err := s.getCrossChainReqs(ormTx.ID, tx, statusFail)
218 for _, output := range crossChainOutputs {
219 if err := s.db.Create(output).Error; err != nil {
220 return errors.Wrap(err, fmt.Sprintf("create WithdrawalFromSidechain output: txid(%s), pos(%d)", tx.ID.String(), output.SourcePos))
227 func (s *sidechainKeeper) getCrossChainReqs(crossTransactionID uint64, tx *types.Tx, statusFail bool) ([]*orm.CrossTransactionReq, error) {
228 var fromAddress string
229 inputCP := tx.Inputs[0].ControlProgram()
231 case segwit.IsP2WPKHScript(inputCP):
232 if pubHash, err := segwit.GetHashFromStandardProg(inputCP); err == nil {
233 fromAddress = wallet.BuildP2PKHAddress(pubHash, &consensus.MainNetParams)
235 case segwit.IsP2WSHScript(inputCP):
236 if scriptHash, err := segwit.GetHashFromStandardProg(inputCP); err == nil {
237 fromAddress = wallet.BuildP2SHAddress(scriptHash, &consensus.MainNetParams)
241 reqs := []*orm.CrossTransactionReq{}
242 for i, rawOutput := range tx.Outputs {
243 // check valid withdrawal
244 if rawOutput.OutputType() != types.CrossChainOutputType {
248 if statusFail && *rawOutput.OutputCommitment().AssetAmount.AssetId != *consensus.BTMAssetID {
252 asset, err := s.assetStore.GetByAssetID(rawOutput.OutputCommitment().AssetAmount.AssetId.String())
258 outputCP := rawOutput.ControlProgram()
260 case segwit.IsP2WPKHScript(outputCP):
261 if pubHash, err := segwit.GetHashFromStandardProg(outputCP); err == nil {
262 toAddress = wallet.BuildP2PKHAddress(pubHash, &consensus.BytomMainNetParams)
264 case segwit.IsP2WSHScript(outputCP):
265 if scriptHash, err := segwit.GetHashFromStandardProg(outputCP); err == nil {
266 toAddress = wallet.BuildP2SHAddress(scriptHash, &consensus.BytomMainNetParams)
270 req := &orm.CrossTransactionReq{
271 CrossTransactionID: crossTransactionID,
272 SourcePos: uint64(i),
274 AssetAmount: rawOutput.OutputCommitment().AssetAmount.Amount,
275 Script: hex.EncodeToString(rawOutput.ControlProgram()),
276 FromAddress: fromAddress,
277 ToAddress: toAddress,
279 reqs = append(reqs, req)
284 func (s *sidechainKeeper) processChainInfo(chain *orm.Chain, block *types.Block) error {
285 blockHash := block.Hash()
286 chain.BlockHash = blockHash.String()
287 chain.BlockHeight = block.Height
288 res := s.db.Model(chain).Where("block_hash = ?", block.PreviousBlockHash.String()).Updates(chain)
289 if err := res.Error; err != nil {
293 if res.RowsAffected != 1 {
294 return ErrInconsistentDB