10 btmConsensus "github.com/bytom/consensus"
11 btmBc "github.com/bytom/protocol/bc"
12 btmTypes "github.com/bytom/protocol/bc/types"
13 "github.com/jinzhu/gorm"
14 log "github.com/sirupsen/logrus"
16 "github.com/vapor/errors"
17 "github.com/vapor/federation/config"
18 "github.com/vapor/federation/database"
19 "github.com/vapor/federation/database/orm"
20 "github.com/vapor/federation/service"
21 "github.com/vapor/protocol/bc"
24 type mainchainKeeper struct {
29 assetCache *database.AssetCache
32 func NewMainchainKeeper(db *gorm.DB, chainCfg *config.Chain) *mainchainKeeper {
33 return &mainchainKeeper{
36 node: service.NewNode(chainCfg.Upstream),
37 chainName: chainCfg.Name,
38 assetCache: database.NewAssetCache(),
42 func (m *mainchainKeeper) Run() {
43 ticker := time.NewTicker(time.Duration(m.cfg.SyncSeconds) * time.Second)
44 for ; true; <-ticker.C {
46 isUpdate, err := m.syncBlock()
48 log.WithField("error", err).Errorln("blockKeeper fail on process block")
59 func (m *mainchainKeeper) syncBlock() (bool, error) {
60 chain := &orm.Chain{Name: m.chainName}
61 if err := m.db.Where(chain).First(chain).Error; err != nil {
62 return false, errors.Wrap(err, "query chain")
65 height, err := m.node.GetBlockCount()
70 if height <= chain.BlockHeight+m.cfg.Confirmations {
74 nextBlockStr, txStatus, err := m.node.GetBlockByHeight(chain.BlockHeight + 1)
79 nextBlock := &btmTypes.Block{}
80 if err := nextBlock.UnmarshalText([]byte(nextBlockStr)); err != nil {
81 return false, errors.New("Unmarshal nextBlock")
84 if nextBlock.PreviousBlockHash.String() != chain.BlockHash {
85 log.WithFields(log.Fields{
86 "remote PreviousBlockHash": nextBlock.PreviousBlockHash.String(),
87 "db block_hash": chain.BlockHash,
88 }).Fatal("BlockHash mismatch")
89 return false, ErrInconsistentDB
92 if err := m.tryAttachBlock(chain, nextBlock, txStatus); err != nil {
99 func (m *mainchainKeeper) tryAttachBlock(chain *orm.Chain, block *btmTypes.Block, txStatus *bc.TransactionStatus) error {
100 blockHash := block.Hash()
101 log.WithFields(log.Fields{"block_height": block.Height, "block_hash": blockHash.String()}).Info("start to attachBlock")
103 if err := m.processBlock(chain, block, txStatus); err != nil {
108 return m.db.Commit().Error
111 func (m *mainchainKeeper) processBlock(chain *orm.Chain, block *btmTypes.Block, txStatus *bc.TransactionStatus) error {
112 if err := m.processIssuing(block.Transactions); err != nil {
116 for i, tx := range block.Transactions {
117 if m.isDepositTx(tx) {
118 if err := m.processDepositTx(chain, block, txStatus, uint64(i), tx); err != nil {
123 if m.isWithdrawalTx(tx) {
124 if err := m.processWithdrawalTx(chain, block, uint64(i), tx); err != nil {
130 return m.processChainInfo(chain, block)
133 func (m *mainchainKeeper) isDepositTx(tx *btmTypes.Tx) bool {
134 for _, output := range tx.Outputs {
135 if bytes.Equal(output.OutputCommitment.ControlProgram, fedProg) {
142 func (m *mainchainKeeper) isWithdrawalTx(tx *btmTypes.Tx) bool {
143 for _, input := range tx.Inputs {
144 if bytes.Equal(input.ControlProgram(), fedProg) {
151 func (m *mainchainKeeper) processDepositTx(chain *orm.Chain, block *btmTypes.Block, txStatus *bc.TransactionStatus, txIndex uint64, tx *btmTypes.Tx) error {
152 blockHash := block.Hash()
155 isMuxIDFound := false
156 for _, resOutID := range tx.ResultIds {
157 resOut, ok := tx.Entries[*resOutID].(*btmBc.Output)
159 muxID = *resOut.Source.Ref
165 return errors.New("fail to get mux id")
168 rawTx, err := tx.MarshalText()
173 ormTx := &orm.CrossTransaction{
175 SourceBlockHeight: block.Height,
176 SourceBlockHash: blockHash.String(),
177 SourceTxIndex: txIndex,
178 SourceMuxID: muxID.String(),
179 SourceTxHash: tx.ID.String(),
180 SourceRawTransaction: string(rawTx),
181 DestBlockHeight: sql.NullInt64{Valid: false},
182 DestBlockHash: sql.NullString{Valid: false},
183 DestTxIndex: sql.NullInt64{Valid: false},
184 DestTxHash: sql.NullString{Valid: false},
188 if err := m.db.Create(ormTx).Error; err != nil {
189 return errors.Wrap(err, fmt.Sprintf("create mainchain DepositTx %s", tx.ID.String()))
192 statusFail := txStatus.VerifyStatus[txIndex].StatusFail
193 crossChainInputs, err := m.getCrossChainInputs(ormTx.ID, tx, statusFail)
198 for _, input := range crossChainInputs {
199 if err := m.db.Create(input).Error; err != nil {
200 return errors.Wrap(err, fmt.Sprintf("create DepositFromMainchain input: txid(%s), pos(%d)", tx.ID.String(), input.SourcePos))
207 func (m *mainchainKeeper) getCrossChainInputs(crossTransactionID uint64, tx *btmTypes.Tx, statusFail bool) ([]*orm.CrossTransactionReq, error) {
208 // assume inputs are from an identical owner
209 script := hex.EncodeToString(tx.Inputs[0].ControlProgram())
210 inputs := []*orm.CrossTransactionReq{}
211 for i, rawOutput := range tx.Outputs {
212 // check valid deposit
213 if !bytes.Equal(rawOutput.OutputCommitment.ControlProgram, fedProg) {
217 if statusFail && *rawOutput.OutputCommitment.AssetAmount.AssetId != *btmConsensus.BTMAssetID {
221 asset, err := m.getAsset(rawOutput.OutputCommitment.AssetAmount.AssetId.String())
226 input := &orm.CrossTransactionReq{
227 CrossTransactionID: crossTransactionID,
228 SourcePos: uint64(i),
230 AssetAmount: rawOutput.OutputCommitment.AssetAmount.Amount,
233 inputs = append(inputs, input)
238 func (m *mainchainKeeper) processWithdrawalTx(chain *orm.Chain, block *btmTypes.Block, txIndex uint64, tx *btmTypes.Tx) error {
240 ormTx := &orm.CrossTransaction{
242 DestBlockHeight: sql.NullInt64{Valid: false},
243 DestBlockHash: sql.NullString{Valid: false},
244 DestTxIndex: sql.NullInt64{Valid: false},
245 DestTxHash: sql.NullString{Valid: false},
253 // TODO: maybe common
254 func (m *mainchainKeeper) processChainInfo(chain *orm.Chain, block *btmTypes.Block) error {
255 blockHash := block.Hash()
256 chain.BlockHash = blockHash.String()
257 chain.BlockHeight = block.Height
258 res := m.db.Model(chain).Where("block_hash = ?", block.PreviousBlockHash.String()).Updates(chain)
259 if err := res.Error; err != nil {
263 if res.RowsAffected != 1 {
264 return ErrInconsistentDB
270 func (m *mainchainKeeper) processIssuing(txs []*btmTypes.Tx) error {
271 for _, tx := range txs {
272 for _, input := range tx.Inputs {
273 switch inp := input.TypedInput.(type) {
274 case *btmTypes.IssuanceInput:
275 assetID := inp.AssetID()
276 if _, err := m.getAsset(assetID.String()); err == nil {
281 AssetID: assetID.String(),
282 IssuanceProgram: hex.EncodeToString(inp.IssuanceProgram),
283 VMVersion: inp.VMVersion,
284 RawDefinitionByte: hex.EncodeToString(inp.AssetDefinition),
286 if err := m.db.Create(asset).Error; err != nil {
290 m.assetCache.Add(asset.AssetID, asset)
298 // TODO: maybe common
299 func (m *mainchainKeeper) getAsset(assetID string) (*orm.Asset, error) {
300 if asset := m.assetCache.Get(assetID); asset != nil {
304 asset := &orm.Asset{AssetID: assetID}
305 if err := m.db.Where(asset).First(asset).Error; err != nil {
306 return nil, errors.Wrap(err, "asset not found in memory and mysql")
309 m.assetCache.Add(assetID, asset)