/
app.go
268 lines (237 loc) · 7.67 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package main
import (
"context"
"crypto/rsa"
"encoding/json"
"io/ioutil"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/DaoCasino/casino-backend/metrics"
"github.com/DaoCasino/casino-backend/utils"
broker "github.com/DaoCasino/platform-action-monitor-client"
"github.com/eoscanada/eos-go"
"github.com/eoscanada/eos-go/ecc"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
"github.com/zenazn/goji/graceful"
"golang.org/x/sync/errgroup"
)
type ResponseWriter = http.ResponseWriter
type Request = http.Request
type JSONResponse = map[string]interface{}
type BrokerConfig struct {
TopicID broker.EventType
TopicOffset uint64
}
type PubKeys struct {
Deposit ecc.PublicKey
SigniDice ecc.PublicKey
}
type BlockChainConfig struct {
ChainID eos.Checksum256
CasinoAccountName eos.AccountName
EosPubKeys PubKeys
RSAKey *rsa.PrivateKey
PlatformAccountName eos.AccountName
PlatformPubKey ecc.PublicKey
}
type HTTPConfig struct {
RetryAmount int
RetryDelay time.Duration
Timeout time.Duration
}
type AppConfig struct {
Broker BrokerConfig
BlockChain BlockChainConfig
HTTP HTTPConfig
}
type App struct {
bcAPI *eos.API
BrokerClient EventListener
OffsetHandler utils.FileStorage
EventMessages chan *broker.EventMessage
*AppConfig
}
type EventListener interface {
ListenAndServe(ctx context.Context) error
Subscribe(eventType broker.EventType, offset uint64) (bool, error)
Unsubscribe(eventType broker.EventType) (bool, error)
Run(ctx context.Context)
}
func NewApp(bcAPI *eos.API, brokerClient EventListener, eventMessages chan *broker.EventMessage,
offsetHandler utils.FileStorage,
cfg *AppConfig) *App {
return &App{bcAPI: bcAPI, BrokerClient: brokerClient, OffsetHandler: offsetHandler,
EventMessages: eventMessages, AppConfig: cfg}
}
func (app *App) processEvent(event *broker.Event) *string {
log.Debug().Msgf("Processing event %+v", event)
start := time.Now()
defer func() {
elapsed := time.Since(start)
metrics.SigniDiceProcessingTimeMs.Observe(elapsed.Seconds() * 1000)
}()
var data struct {
Digest eos.Checksum256 `json:"digest"`
}
parseError := json.Unmarshal(event.Data, &data)
if parseError != nil {
log.Error().Msgf("Couldnt get digest from event, reason: %s", parseError.Error())
return nil
}
api := app.bcAPI
signature, signError := utils.RsaSign(data.Digest, app.BlockChain.RSAKey)
if signError != nil {
log.Error().Msgf("Couldnt sign signidice_part_2, reason: %s", signError.Error())
return nil
}
txOpts := &eos.TxOptions{}
err := utils.RetryWithTimeout(func() error {
return txOpts.FillFromChain(api)
}, app.HTTP.RetryAmount, app.HTTP.Timeout, app.HTTP.RetryDelay)
if err != nil {
log.Error().Msgf("failed to get blockchain state, reason: %s", err.Error())
return nil
}
packedTx, err := GetSigndiceTransaction(api, eos.AN(event.Sender), app.BlockChain.CasinoAccountName,
event.RequestID, signature, app.BlockChain.EosPubKeys.SigniDice, txOpts)
if err != nil {
log.Error().Msgf("couldn't form transaction, reason: %s", err.Error())
return nil
}
result, sendError := api.PushTransaction(packedTx)
if sendError != nil {
log.Error().Msg("Failed to send transaction, reason: " + sendError.Error())
return nil
}
log.Debug().Msg("Successfully signed and sent txn, id: " + result.TransactionID)
return &result.TransactionID
}
func (app *App) RunEventProcessor(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case eventMessage, ok := <-app.EventMessages:
if !ok {
log.Debug().Msg("Failed to read events")
break
}
if len(eventMessage.Events) == 0 {
log.Debug().Msg("Gotta event message with no events")
break
}
log.Debug().Msgf("Processing %+v events", len(eventMessage.Events))
for _, event := range eventMessage.Events {
go app.processEvent(event)
}
offset := eventMessage.Offset + 1
if err := utils.WriteOffset(app.OffsetHandler, offset); err != nil {
log.Error().Msgf("Failed to write offset, reason: %s", err.Error())
}
}
}
}
func (app *App) Run(addr string) error {
ctx, cancel := context.WithCancel(context.Background())
errGroup, ctx := errgroup.WithContext(ctx)
defer cancel()
// no errGroup because ctx close cannot be handled
go func() {
defer cancel()
log.Debug().Msg("starting http server")
log.Panic().Msg(graceful.ListenAndServe(addr, app.GetRouter()).Error())
}()
errGroup.Go(func() error {
defer cancel()
log.Debug().Msg("starting event listener")
go app.BrokerClient.Run(ctx)
if _, err := app.BrokerClient.Subscribe(app.Broker.TopicID, app.Broker.TopicOffset); err != nil {
return err
}
log.Debug().Msgf("starting event processor with offset %v", app.Broker.TopicOffset)
app.RunEventProcessor(ctx)
return nil
})
errGroup.Go(func() error {
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
select {
case <-ctx.Done():
return nil
case <-quit:
cancel()
}
return nil
})
return errGroup.Wait()
}
func respondWithError(writer ResponseWriter, code int, message string) {
respondWithJSON(writer, code, JSONResponse{"error": message})
}
func respondWithJSON(writer ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(code)
_, err := writer.Write(response)
if err != nil {
log.Warn().Msg("Failed to respond to client")
}
}
func (app *App) PingQuery(writer ResponseWriter, req *Request) {
respondWithJSON(writer, http.StatusOK, JSONResponse{"result": "pong"})
}
func (app *App) SignQuery(writer ResponseWriter, req *Request) {
log.Info().Msg("Called /sign_transaction")
start := time.Now()
defer func() {
elapsed := time.Since(start)
metrics.SignTransactionProcessingTimeMs.Observe(elapsed.Seconds() * 1000)
}()
rawTransaction, _ := ioutil.ReadAll(req.Body)
tx := &eos.SignedTransaction{}
err := json.Unmarshal(rawTransaction, tx)
if err != nil {
log.Debug().Msgf("failed to deserialize transaction, reason: %s", err.Error())
respondWithError(writer, http.StatusBadRequest, "failed to deserialize transaction")
return
}
if err := ValidateDepositTransaction(tx, app.BlockChain.CasinoAccountName, app.BlockChain.PlatformAccountName,
app.BlockChain.PlatformPubKey,
app.BlockChain.ChainID); err != nil {
log.Debug().Msgf("invalid transaction supplied, reason: %s", err.Error())
respondWithError(writer, http.StatusBadRequest, "invalid transaction supplied")
return
}
signedTx, signError := app.bcAPI.Signer.Sign(tx, app.BlockChain.ChainID, app.BlockChain.EosPubKeys.Deposit)
if signError != nil {
log.Warn().Msgf("failed to sign transaction, reason: %s", signError.Error())
respondWithError(writer, http.StatusInternalServerError, "failed to sign transaction")
return
}
log.Debug().Msg(signedTx.String())
packedTrx, _ := signedTx.Pack(eos.CompressionNone)
var result *eos.PushTransactionFullResp
sendError := utils.RetryWithTimeout(func() error {
var e error
result, e = app.bcAPI.PushTransaction(packedTrx)
return e
}, app.HTTP.RetryAmount, app.HTTP.Timeout, app.HTTP.RetryDelay)
if sendError != nil {
log.Debug().Msgf("failed to send transaction to the blockchain, reason: %s", sendError.Error())
respondWithError(writer, http.StatusBadRequest, "failed to send transaction to the blockchain, reason: "+
sendError.Error())
return
}
respondWithJSON(writer, http.StatusOK, JSONResponse{"txid": result.TransactionID})
}
func (app *App) GetRouter() *mux.Router {
var router mux.Router
router.HandleFunc("/ping", app.PingQuery).Methods("GET")
router.HandleFunc("/sign_transaction", app.SignQuery).Methods("POST")
router.Handle("/metrics", metrics.GetHandler())
return &router
}