OSDN Git Service

fix
[bytom/vapor.git] / federation / warder.go
1 package federation
2
3 import (
4         "database/sql"
5         "encoding/hex"
6         "time"
7
8         btmTypes "github.com/bytom/protocol/bc/types"
9         "github.com/jinzhu/gorm"
10         log "github.com/sirupsen/logrus"
11
12         "github.com/vapor/crypto/ed25519/chainkd"
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/federation/util"
20         vaporBc "github.com/vapor/protocol/bc"
21         vaporTypes "github.com/vapor/protocol/bc/types"
22 )
23
24 var collectInterval = 5 * time.Second
25
26 type warder struct {
27         db            *gorm.DB
28         assetStore    *database.AssetStore
29         txCh          chan *orm.CrossTransaction
30         fedProg       []byte
31         position      uint8
32         xpub          chainkd.XPub
33         xprv          chainkd.XPrv
34         mainchainNode *service.Node
35         sidechainNode *service.Node
36         remotes       []*service.Warder
37 }
38
39 func NewWarder(db *gorm.DB, assetStore *database.AssetStore, cfg *config.Config) *warder {
40         local, remotes := parseWarders(cfg)
41         return &warder{
42                 db:            db,
43                 assetStore:    assetStore,
44                 txCh:          make(chan *orm.CrossTransaction),
45                 fedProg:       util.ParseFedProg(cfg.Warders, cfg.Quorum),
46                 position:      local.Position,
47                 xpub:          local.XPub,
48                 xprv:          string2xprv(xprvStr),
49                 mainchainNode: service.NewNode(cfg.Mainchain.Upstream),
50                 sidechainNode: service.NewNode(cfg.Sidechain.Upstream),
51                 remotes:       remotes,
52         }
53 }
54
55 func parseWarders(cfg *config.Config) (*service.Warder, []*service.Warder) {
56         var local *service.Warder
57         var remotes []*service.Warder
58         for _, warderCfg := range cfg.Warders {
59                 if warderCfg.IsLocal {
60                         local = service.NewWarder(&warderCfg)
61                 } else {
62                         remote := service.NewWarder(&warderCfg)
63                         remotes = append(remotes, remote)
64                 }
65         }
66
67         if local == nil {
68                 log.Fatal("none local warder set")
69         }
70
71         return local, remotes
72 }
73
74 func (w *warder) Run() {
75         ticker := time.NewTicker(collectInterval)
76         for ; true; <-ticker.C {
77                 txs := []*orm.CrossTransaction{}
78                 if err := w.db.Preload("Chain").Preload("Reqs").
79                         // do not use "Where(&orm.CrossTransaction{Status: common.CrossTxPendingStatus})" directly,
80                         // otherwise the field "status" will be ignored
81                         Model(&orm.CrossTransaction{}).Where("status = ?", common.CrossTxPendingStatus).
82                         Find(&txs).Error; err == gorm.ErrRecordNotFound {
83                         continue
84                 } else if err != nil {
85                         log.Warnln("collectPendingTx", err)
86                 }
87
88                 for _, tx := range txs {
89                         go w.processCrossTx(tx)
90                 }
91         }
92 }
93
94 func (w *warder) processCrossTx(ormTx *orm.CrossTransaction) {
95         if err := w.validateCrossTx(ormTx); err != nil {
96                 log.Warnln("invalid cross-chain tx", ormTx)
97                 return
98         }
99
100         destTx, destTxID, err := w.proposeDestTx(ormTx)
101         if err != nil {
102                 log.WithFields(log.Fields{"err": err, "cross-chain tx": ormTx}).Warnln("proposeDestTx")
103                 return
104         }
105
106         if err := w.initDestTxSigns(destTx, ormTx); err != nil {
107                 log.WithFields(log.Fields{"err": err, "cross-chain tx": ormTx}).Warnln("initDestTxSigns")
108                 return
109         }
110
111         if err := w.signDestTx(destTx, ormTx); err != nil {
112                 log.WithFields(log.Fields{"err": err, "cross-chain tx": ormTx}).Warnln("signDestTx")
113                 return
114         }
115
116         for _, remote := range w.remotes {
117                 signs, err := remote.RequestSign(destTx, ormTx)
118                 if err != nil {
119                         log.WithFields(log.Fields{"err": err, "remote": remote, "cross-chain tx": ormTx}).Warnln("RequestSign")
120                         return
121                 }
122
123                 w.attachSignsForTx(destTx, ormTx, remote.Position, signs)
124         }
125
126         if w.isTxSignsReachQuorum(destTx) && w.isLeader() {
127                 submittedTxID, err := w.submitTx(destTx)
128                 if err != nil {
129                         log.WithFields(log.Fields{"err": err, "cross-chain tx": ormTx, "dest tx": destTx}).Warnln("submitTx")
130                         return
131                 }
132
133                 if submittedTxID != destTxID {
134                         log.WithFields(log.Fields{"err": err, "cross-chain tx": ormTx, "builtTx ID": destTxID, "submittedTx ID": submittedTxID}).Warnln("submitTx ID mismatch")
135                         return
136                 }
137
138                 if err := w.updateSubmission(ormTx); err != nil {
139                         log.WithFields(log.Fields{"err": err, "cross-chain tx": ormTx}).Warnln("updateSubmission")
140                         return
141                 }
142         }
143 }
144
145 func (w *warder) validateCrossTx(tx *orm.CrossTransaction) error {
146         switch tx.Status {
147         case common.CrossTxRejectedStatus:
148                 return errors.New("cross-chain tx rejected")
149         case common.CrossTxSubmittedStatus:
150                 return errors.New("cross-chain tx submitted")
151         case common.CrossTxCompletedStatus:
152                 return errors.New("cross-chain tx completed")
153         default:
154                 return nil
155         }
156 }
157
158 func (w *warder) proposeDestTx(tx *orm.CrossTransaction) (interface{}, string, error) {
159         switch tx.Chain.Name {
160         case "bytom":
161                 return w.buildSidechainTx(tx)
162         case "vapor":
163                 return w.buildMainchainTx(tx)
164         default:
165                 return nil, "", errors.New("unknown source chain")
166         }
167 }
168
169 func (w *warder) buildSidechainTx(ormTx *orm.CrossTransaction) (*vaporTypes.Tx, string, error) {
170         destTxData := &vaporTypes.TxData{Version: 1, TimeRange: 0}
171         muxID := &vaporBc.Hash{}
172         if err := muxID.UnmarshalText([]byte(ormTx.SourceMuxID)); err != nil {
173                 return nil, "", errors.Wrap(err, "Unmarshal muxID")
174         }
175
176         for _, req := range ormTx.Reqs {
177                 // getAsset from assetStore instead of preload asset, in order to save db query overload
178                 asset, err := w.assetStore.GetByOrmID(req.AssetID)
179                 if err != nil {
180                         return nil, "", errors.Wrap(err, "get asset by ormAsset ID")
181                 }
182
183                 assetID := &vaporBc.AssetID{}
184                 if err := assetID.UnmarshalText([]byte(asset.AssetID)); err != nil {
185                         return nil, "", errors.Wrap(err, "Unmarshal muxID")
186                 }
187
188                 rawDefinitionByte, err := hex.DecodeString(asset.RawDefinitionByte)
189                 if err != nil {
190                         return nil, "", errors.Wrap(err, "decode rawDefinitionByte")
191                 }
192
193                 issuanceProgramByte, err := hex.DecodeString(asset.IssuanceProgram)
194                 if err != nil {
195                         return nil, "", errors.Wrap(err, "decode issuanceProgramByte")
196                 }
197
198                 input := vaporTypes.NewCrossChainInput(nil, *muxID, *assetID, req.AssetAmount, req.SourcePos, 1, rawDefinitionByte, issuanceProgramByte)
199                 destTxData.Inputs = append(destTxData.Inputs, input)
200
201                 controlProgram, err := hex.DecodeString(req.Script)
202                 if err != nil {
203                         return nil, "", errors.Wrap(err, "decode req.Script")
204                 }
205
206                 output := vaporTypes.NewIntraChainOutput(*assetID, req.AssetAmount, controlProgram)
207                 destTxData.Outputs = append(destTxData.Outputs, output)
208         }
209
210         destTx := vaporTypes.NewTx(*destTxData)
211         w.addInputWitness(destTx)
212
213         if err := w.db.Where(ormTx).UpdateColumn(&orm.CrossTransaction{
214                 DestTxHash: sql.NullString{destTx.ID.String(), true},
215         }).Error; err != nil {
216                 return nil, "", err
217         }
218
219         return destTx, destTx.ID.String(), nil
220 }
221
222 func (w *warder) buildMainchainTx(ormTx *orm.CrossTransaction) (*btmTypes.Tx, string, error) {
223         return nil, "", errors.New("buildMainchainTx not implemented yet")
224 }
225
226 // tx is a pointer to types.Tx, so the InputArguments can be set and be valid afterward
227 func (w *warder) addInputWitness(tx interface{}) {
228         witness := [][]byte{w.fedProg}
229         switch tx := tx.(type) {
230         case *vaporTypes.Tx:
231                 for i := range tx.Inputs {
232                         tx.SetInputArguments(uint32(i), witness)
233                 }
234
235         case *btmTypes.Tx:
236                 for i := range tx.Inputs {
237                         tx.SetInputArguments(uint32(i), witness)
238                 }
239         }
240 }
241
242 func (w *warder) initDestTxSigns(destTx interface{}, ormTx *orm.CrossTransaction) error {
243         crossTxSigns := []*orm.CrossTransactionSign{}
244         for i := 1; i <= len(w.remotes)+1; i++ {
245                 crossTxSigns = append(crossTxSigns, &orm.CrossTransactionSign{
246                         CrossTransactionID: ormTx.ID,
247                         WarderID:           uint8(i),
248                         Status:             common.CrossTxSignPendingStatus,
249                 })
250         }
251         return w.db.Create(crossTxSigns).Error
252 }
253
254 // TODO:
255 func (w *warder) signDestTx(destTx interface{}, tx *orm.CrossTransaction) error {
256         if tx.Status != common.CrossTxPendingStatus || !tx.DestTxHash.Valid {
257                 return errors.New("cross-chain tx status error")
258         }
259
260         return nil
261 }
262
263 // TODO:
264 func (w *warder) attachSignsForTx(destTx interface{}, ormTx *orm.CrossTransaction, position uint8, signs string) {
265 }
266
267 // TODO:
268 func (w *warder) isTxSignsReachQuorum(destTx interface{}) bool {
269         return false
270 }
271
272 func (w *warder) isLeader() bool {
273         return w.position == 1
274 }
275
276 func (w *warder) submitTx(destTx interface{}) (string, error) {
277         switch tx := destTx.(type) {
278         case *btmTypes.Tx:
279                 return w.mainchainNode.SubmitTx(tx)
280         case *vaporTypes.Tx:
281                 return w.sidechainNode.SubmitTx(tx)
282         default:
283                 return "", errors.New("unknown destTx type")
284         }
285 }
286
287 func (w *warder) updateSubmission(tx *orm.CrossTransaction) error {
288         if err := w.db.Where(tx).UpdateColumn(&orm.CrossTransaction{
289                 Status: common.CrossTxSubmittedStatus,
290         }).Error; err != nil {
291                 return err
292         }
293
294         for _, remote := range w.remotes {
295                 remote.NotifySubmission(tx)
296         }
297         return nil
298 }