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.Model(&orm.CrossTransaction{}).
214                 Where(&orm.CrossTransaction{ID: ormTx.ID}).
215                 UpdateColumn(&orm.CrossTransaction{
216                         DestTxHash: sql.NullString{destTx.ID.String(), true},
217                 }).Error; err != nil {
218                 return nil, "", err
219         }
220
221         return destTx, destTx.ID.String(), nil
222 }
223
224 func (w *warder) buildMainchainTx(ormTx *orm.CrossTransaction) (*btmTypes.Tx, string, error) {
225         return nil, "", errors.New("buildMainchainTx not implemented yet")
226 }
227
228 // TODO: review logic
229 // tx is a pointer to types.Tx, so the InputArguments can be set and be valid afterward
230 func (w *warder) addInputWitness(tx interface{}) {
231         switch tx := tx.(type) {
232         case *vaporTypes.Tx:
233                 args := [][]byte{w.fedProg}
234                 for i := range tx.Inputs {
235                         tx.SetInputArguments(uint32(i), args)
236                 }
237
238         case *btmTypes.Tx:
239                 args := [][]byte{util.SegWitWrap(w.fedProg)}
240                 for i := range tx.Inputs {
241                         tx.SetInputArguments(uint32(i), args)
242                 }
243         }
244 }
245
246 func (w *warder) initDestTxSigns(destTx interface{}, ormTx *orm.CrossTransaction) error {
247         for i := 1; i <= len(w.remotes)+1; i++ {
248                 if err := w.db.Create(&orm.CrossTransactionSign{
249                         CrossTransactionID: ormTx.ID,
250                         WarderID:           uint8(i),
251                         Status:             common.CrossTxSignPendingStatus,
252                 }).Error; err != nil {
253                         return err
254                 }
255         }
256         return nil
257 }
258
259 // TODO:
260 func (w *warder) signDestTx(destTx interface{}, tx *orm.CrossTransaction) error {
261         if tx.Status != common.CrossTxPendingStatus || !tx.DestTxHash.Valid {
262                 return errors.New("cross-chain tx status error")
263         }
264
265         return nil
266 }
267
268 // TODO:
269 func (w *warder) attachSignsForTx(destTx interface{}, ormTx *orm.CrossTransaction, position uint8, signs string) {
270 }
271
272 // TODO:
273 func (w *warder) isTxSignsReachQuorum(destTx interface{}) bool {
274         return false
275 }
276
277 func (w *warder) isLeader() bool {
278         return w.position == 1
279 }
280
281 func (w *warder) submitTx(destTx interface{}) (string, error) {
282         switch tx := destTx.(type) {
283         case *btmTypes.Tx:
284                 return w.mainchainNode.SubmitTx(tx)
285         case *vaporTypes.Tx:
286                 return w.sidechainNode.SubmitTx(tx)
287         default:
288                 return "", errors.New("unknown destTx type")
289         }
290 }
291
292 func (w *warder) updateSubmission(ormTx *orm.CrossTransaction) error {
293         if err := w.db.Model(&orm.CrossTransaction{}).
294                 Where(&orm.CrossTransaction{ID: ormTx.ID}).
295                 UpdateColumn(&orm.CrossTransaction{
296                         Status: common.CrossTxSubmittedStatus,
297                 }).Error; err != nil {
298                 return err
299         }
300
301         for _, remote := range w.remotes {
302                 remote.NotifySubmission(ormTx)
303         }
304         return nil
305 }