This repository has been archived by the owner on Apr 23, 2024. It is now read-only.
/
main.go
358 lines (311 loc) · 10.3 KB
/
main.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package backend
import (
"context"
"encoding/hex"
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
"github.com/stellar/go/amount"
"github.com/stellar/go/clients/horizonclient"
"github.com/stellar/go/support/errors"
"github.com/stellar/go/support/log"
"github.com/stellar/go/support/render/problem"
"github.com/stellar/go/txnbuild"
"github.com/stellar/go/xdr"
"github.com/stellar/starbridge/ethereum"
"github.com/stellar/starbridge/stellar/signer"
"github.com/stellar/starbridge/stellar/txbuilder"
"github.com/stellar/starbridge/stellar/txobserver"
"github.com/stellar/starbridge/store"
)
type Worker struct {
Store *store.DB
StellarClient *horizonclient.Client
StellarBuilder *txbuilder.Builder
StellarSigner *signer.Signer
StellarObserver *txobserver.Observer
StellarWithdrawalValidator StellarWithdrawalValidator
StellarRefundValidator StellarRefundValidator
EthereumRefundValidator EthereumRefundValidator
EthereumWithdrawalValidator EthereumWithdrawalValidator
EthereumSigner ethereum.Signer
log *log.Entry
}
func (w *Worker) Run(ctx context.Context) {
w.log = log.WithField("service", "backend")
w.log.Info("Starting worker")
for ctx.Err() == nil {
// Process all new ledgers before processing signature requests
w.StellarObserver.ProcessNewLedgers(ctx)
signatureRequests, err := w.Store.GetSignatureRequests(ctx)
if err != nil {
w.log.WithField("err", err).Error("cannot get signature requests")
time.Sleep(time.Second)
continue
}
if len(signatureRequests) == 0 {
time.Sleep(time.Second)
continue
}
w.log.Infof("Processing %d signature requests", len(signatureRequests))
for _, sr := range signatureRequests {
var err error
switch sr.Action {
case store.Withdraw:
switch sr.DepositChain {
case store.Ethereum:
err = w.processStellarWithdrawalRequest(ctx, sr)
case store.Stellar:
err = w.processEthereumWithdrawalRequest(ctx, sr)
default:
err = fmt.Errorf("withdrawals for deposit chain %v is not supported", sr.DepositChain)
}
case store.Refund:
switch sr.DepositChain {
case store.Ethereum:
err = w.processEthereumRefundRequest(ctx, sr)
case store.Stellar:
err = w.processStellarRefundRequest(ctx, sr)
default:
err = fmt.Errorf("refunds for deposit chain %v is not supported", sr.DepositChain)
}
default:
err = fmt.Errorf("action %v is not supported", sr.Action)
}
if err != nil {
w.log.WithFields(log.F{"err": err, "request": sr}).
Error("Cannot process signature request")
if p, ok := err.(problem.P); ok && p.Status >= 400 && p.Status < 500 {
w.deleteRequest(ctx, sr)
}
} else {
w.log.WithField("request", sr).
Info("Processed signature request successfully")
w.deleteRequest(ctx, sr)
}
}
}
}
func (w *Worker) deleteRequest(ctx context.Context, sr store.SignatureRequest) {
err := w.Store.DeleteSignatureRequest(ctx, sr)
if err != nil {
w.log.WithFields(log.F{"err": err, "request": sr}).
Error("Error removing signature request")
}
}
func (w *Worker) processStellarWithdrawalRequest(ctx context.Context, sr store.SignatureRequest) error {
if sr.DepositChain != store.Ethereum {
return fmt.Errorf("deposits from %v are not supported", sr.DepositChain)
}
deposit, err := w.Store.GetEthereumDeposit(ctx, sr.DepositID)
if err != nil {
return errors.Wrap(err, "error getting ethereum deposit")
}
details, err := w.StellarWithdrawalValidator.CanWithdraw(ctx, deposit)
if err != nil {
return errors.Wrap(err, "error validating withdraw conditions")
}
// Load source account sequence
sourceAccount, err := w.StellarClient.AccountDetail(horizonclient.AccountRequest{
AccountID: details.Recipient,
})
if err != nil {
return errors.Wrap(err, "error getting account details")
}
if sourceAccount.SequenceLedger > 0 {
if details.LedgerSequence < sourceAccount.SequenceLedger {
return errors.New("skipping, account sequence ledger is higher than last ledger ingested")
}
} else {
if details.LedgerSequence < sourceAccount.LastModifiedLedger {
return errors.New("skipping, account sequence possibly bumped after last ledger ingested")
}
}
depositIDBytes, err := hex.DecodeString(deposit.ID)
if err != nil {
return errors.Wrap(err, "error decoding deposit id")
}
tx, err := w.StellarBuilder.BuildTransaction(
details.Asset,
details.Recipient,
details.Recipient,
amount.StringFromInt64(details.Amount),
sourceAccount.Sequence+1,
// TODO: ensure using WithdrawExpiration without any time buffer is safe
details.Deadline.Unix(),
depositIDBytes,
)
if err != nil {
return errors.Wrap(err, "error building outgoing stellar transaction")
}
signature, err := w.StellarSigner.Sign(tx)
if err != nil {
return errors.Wrap(err, "error signing outgoing stellar transaction")
}
// TODO, we need xdr.TransactionEnvelope.AppendSignature.
sigs := tx.Signatures()
tx.V1.Signatures = append(sigs, signature)
txBase64, err := xdr.MarshalBase64(tx)
if err != nil {
return errors.Wrap(err, "error marshaling outgoing stellar transaction")
}
outgoingTx := store.OutgoingStellarTransaction{
Envelope: txBase64,
Action: sr.Action,
DepositID: sr.DepositID,
SourceAccount: details.Recipient,
Sequence: tx.SeqNum(),
}
err = w.Store.UpsertOutgoingStellarTransaction(ctx, outgoingTx)
if err != nil {
return errors.Wrap(err, "error upserting outgoing stellar transaction")
}
return nil
}
func (w *Worker) processStellarRefundRequest(ctx context.Context, sr store.SignatureRequest) error {
if sr.DepositChain != store.Stellar {
return fmt.Errorf("deposits from %v are not supported", sr.DepositChain)
}
deposit, err := w.Store.GetStellarDeposit(ctx, sr.DepositID)
if err != nil {
return errors.Wrap(err, "error getting ethereum deposit")
}
details, err := w.StellarRefundValidator.CanRefund(ctx, deposit)
if err != nil {
return errors.Wrap(err, "error validating refund conditions")
}
// Load source account sequence
sourceAccount, err := w.StellarClient.AccountDetail(horizonclient.AccountRequest{
AccountID: deposit.Sender,
})
if err != nil {
return errors.Wrap(err, "error getting account details")
}
if sourceAccount.SequenceLedger > 0 {
if details.LedgerSequence < sourceAccount.SequenceLedger {
return errors.New("skipping, account sequence ledger is higher than last ledger ingested")
}
} else {
if details.LedgerSequence < sourceAccount.LastModifiedLedger {
return errors.New("skipping, account sequence possibly bumped after last ledger ingested")
}
}
// All good: build, sign and persist outgoing transaction
depositIDBytes, err := hex.DecodeString(deposit.ID)
if err != nil {
return errors.Wrap(err, "error decoding deposit id")
}
tx, err := w.StellarBuilder.BuildTransaction(
deposit.Asset,
deposit.Sender,
deposit.Sender,
deposit.Amount,
sourceAccount.Sequence+1,
txnbuild.TimeoutInfinite,
depositIDBytes,
)
if err != nil {
return errors.Wrap(err, "error building outgoing stellar transaction")
}
signature, err := w.StellarSigner.Sign(tx)
if err != nil {
return errors.Wrap(err, "error signing outgoing stellar transaction")
}
// TODO, we need xdr.TransactionEnvelope.AppendSignature.
sigs := tx.Signatures()
tx.V1.Signatures = append(sigs, signature)
txBase64, err := xdr.MarshalBase64(tx)
if err != nil {
return errors.Wrap(err, "error marshaling outgoing stellar transaction")
}
outgoingTx := store.OutgoingStellarTransaction{
Envelope: txBase64,
Action: sr.Action,
DepositID: sr.DepositID,
SourceAccount: deposit.Sender,
Sequence: tx.SeqNum(),
}
err = w.Store.UpsertOutgoingStellarTransaction(ctx, outgoingTx)
if err != nil {
return errors.Wrap(err, "error upserting outgoing stellar transaction")
}
return nil
}
func (w *Worker) processEthereumRefundRequest(ctx context.Context, sr store.SignatureRequest) error {
if sr.DepositChain != store.Ethereum {
return fmt.Errorf("deposits from %v are not supported", sr.DepositChain)
}
deposit, err := w.Store.GetEthereumDeposit(ctx, sr.DepositID)
if err != nil {
return errors.Wrap(err, "error getting ethereum deposit")
}
if err = w.EthereumRefundValidator.CanRefund(ctx, deposit); err != nil {
return errors.Wrap(err, "error validating refund conditions")
}
refundAmount, ok := new(big.Int).SetString(deposit.Amount, 10)
if !ok {
return errors.Errorf("cannot convert value in wei to bit.Rat: %s", deposit.Amount)
}
expiration := int64(math.MaxInt64)
sig, err := w.EthereumSigner.SignWithdrawal(
common.HexToHash(deposit.ID),
expiration,
common.HexToAddress(deposit.Sender),
common.HexToAddress(deposit.Token),
refundAmount,
)
if err != nil {
return errors.Wrap(err, "error signing refund")
}
err = w.Store.UpsertEthereumSignature(ctx, store.EthereumSignature{
Address: w.EthereumSigner.Address().String(),
Signature: hex.EncodeToString(sig),
Action: sr.Action,
DepositID: sr.DepositID,
Expiration: expiration,
Token: deposit.Token,
Amount: deposit.Amount,
})
if err != nil {
return errors.Wrap(err, "error upserting etherum signature")
}
return nil
}
func (w *Worker) processEthereumWithdrawalRequest(ctx context.Context, sr store.SignatureRequest) error {
if sr.DepositChain != store.Stellar {
return fmt.Errorf("deposits from %v are not supported", sr.DepositChain)
}
deposit, err := w.Store.GetStellarDeposit(ctx, sr.DepositID)
if err != nil {
return errors.Wrap(err, "error getting stellar deposit")
}
details, err := w.EthereumWithdrawalValidator.CanWithdraw(ctx, deposit)
if err != nil {
return errors.Wrap(err, "error validating withdrawal conditions")
}
sig, err := w.EthereumSigner.SignWithdrawal(
common.HexToHash(deposit.ID),
details.Deadline.Unix(),
details.Recipient,
details.Token,
details.Amount,
)
if err != nil {
return errors.Wrap(err, "error signing withdrawal")
}
err = w.Store.UpsertEthereumSignature(ctx, store.EthereumSignature{
Address: w.EthereumSigner.Address().String(),
Signature: hex.EncodeToString(sig),
Action: sr.Action,
DepositID: sr.DepositID,
Expiration: details.Deadline.Unix(),
Token: details.Token.String(),
Amount: details.Amount.String(),
})
if err != nil {
return errors.Wrap(err, "error upserting etherum signature")
}
return nil
}