/
wyre.go
698 lines (633 loc) · 29.3 KB
/
wyre.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
package routes
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/gob"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/btcsuite/btcd/btcec"
"github.com/deso-smart/deso-core/v3/lib"
"github.com/fatih/structs"
"github.com/golang/glog"
"io"
"io/ioutil"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type WyreWalletOrderWebhookPayload struct {
// referenceId holds the public key of the user who made initiated the wallet order
ReferenceId string `json:"referenceId"`
AccountId string `json:"accountId"`
OrderId string `json:"orderId"`
OrderStatus string `json:"orderStatus"`
TransferId string `json:"transferId"`
FailedReason string `json:"failedReason"`
}
type WyreWalletOrderFullDetails struct {
Id string `json:"id"`
CreatedAt uint64 `json:"createdAt"`
Owner string `json:"owner"`
Status string `json:"status"`
OrderType string `json:"orderType"`
SourceAmount float64 `json:"sourceAmount"`
PurchaseAmount float64 `json:"purchaseAmount"`
SourceCurrency string `json:"sourceCurrency"`
DestCurrency string `json:"destCurrency"`
TransferId string `json:"transferId"`
Dest string `json:"dest"`
AuthCodesRequested bool `json:"authCodesRequested"`
ErrorCategory string `json:"errorCategory"`
ErrorCode string `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
FailureReason string `json:"failureReason"`
AccountId string `json:"accountId"`
PaymentNetworkErrorCode string `json:"paymentNetworkErrorCode"`
InternalErrorCode string `json:"internalErrorCode"`
}
type WyreTransferDetails struct {
Owner string `json:"owner"`
ReversingSubStatus interface{} `json:"reversingSubStatus"`
Source string `json:"source"`
PendingSubStatus interface{} `json:"pendingSubStatus"`
Status string `json:"status"`
ReversalReason interface{} `json:"reversalReason"`
CreatedAt int64 `json:"createdAt"`
SourceAmount float64 `json:"sourceAmount"`
DestCurrency string `json:"destCurrency"`
SourceCurrency string `json:"sourceCurrency"`
StatusHistories []struct {
Id string `json:"id"`
TransferId string `json:"transferId"`
CreatedAt int64 `json:"createdAt"`
Type string `json:"type"`
StatusOrder int `json:"statusOrder"`
StatusDetail string `json:"statusDetail"`
State string `json:"state"`
FailedState interface{} `json:"failedState"`
} `json:"statusHistories"`
BlockchainTx struct {
Id string `json:"id"`
NetworkTxId string `json:"networkTxId"`
CreatedAt int64 `json:"createdAt"`
Confirmations int `json:"confirmations"`
TimeObserved int64 `json:"timeObserved"`
BlockTime int64 `json:"blockTime"`
Blockhash string `json:"blockhash"`
Amount float64 `json:"amount"`
Direction string `json:"direction"`
NetworkFee float64 `json:"networkFee"`
Address string `json:"address"`
SourceAddress interface{} `json:"sourceAddress"`
Currency string `json:"currency"`
TwinTxId interface{} `json:"twinTxId"`
} `json:"blockchainTx"`
ExpiresAt int64 `json:"expiresAt"`
CompletedAt int64 `json:"completedAt"`
CancelledAt interface{} `json:"cancelledAt"`
FailureReason interface{} `json:"failureReason"`
UpdatedAt int64 `json:"updatedAt"`
ExchangeRate float64 `json:"exchangeRate"`
DestAmount float64 `json:"destAmount"`
Fees struct {
BTC int `json:"BTC"`
USD float64 `json:"USD"`
} `json:"fees"`
TotalFees float64 `json:"totalFees"`
CustomId string `json:"customId"`
Dest string `json:"dest"`
Message interface{} `json:"message"`
Id string `json:"id"`
}
// Make sure you only allow access to Wyre IPs for this endpoint, otherwise anybody can take all the funds from
// the public key that sends DeSo. WHITELIST WYRE IPs.
func (fes *APIServer) WyreWalletOrderSubscription(ww http.ResponseWriter, req *http.Request) {
// If this node has not integrated with Wyre, bail immediately.
if !fes.IsConfiguredForWyre() {
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: This node is not configured with Wyre"))
return
}
// Decode the request body
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
wyreWalletOrderWebhookRequest := WyreWalletOrderWebhookPayload{}
if err := decoder.Decode(&wyreWalletOrderWebhookRequest); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: Error parsing request body: %v", err))
return
}
orderId := wyreWalletOrderWebhookRequest.OrderId
orderIdBytes := []byte(orderId)
if err := fes.GlobalState.Put(GlobalStateKeyForWyreOrderID(orderIdBytes), []byte{1}); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: Error saving orderId to global state"))
return
}
referenceId := wyreWalletOrderWebhookRequest.ReferenceId
referenceIdSplit := strings.Split(referenceId, ":")
if len(referenceIdSplit) != 2 {
orderJSON, err := json.Marshal(wyreWalletOrderWebhookRequest)
if err != nil {
glog.Errorf("WyreWalletOrderSubscription: Invalid ReferenceId: %v, Error marshaling JSON request body: %v", referenceId, err)
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: Invalid ReferenceId: %v, Error marshaling JSON request body: %v", referenceId, err))
return
}
glog.Errorf("WyreWalletOrderSubscription: Invalid ReferenceId: %v, request body: %v", referenceId, string(orderJSON))
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: Invalid ReferenceId: %v, requestBody: %v", referenceId, string(orderJSON)))
return
}
publicKey := referenceIdSplit[0]
if err := fes.logAmplitudeEvent(publicKey, fmt.Sprintf("wyre : buy : subscription : %v", strings.ToLower(wyreWalletOrderWebhookRequest.OrderStatus)), structs.Map(wyreWalletOrderWebhookRequest)); err != nil {
glog.Errorf("WyreWalletOrderSubscription: Error logging payload to amplitude: %v", err)
}
timestamp, err := strconv.ParseUint(referenceIdSplit[1], 10, 64)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: Error parsing timestamp as uint64 from referenceId: %v", err))
return
}
transferId := wyreWalletOrderWebhookRequest.TransferId
publicKeyBytes, _, err := lib.Base58CheckDecode(publicKey)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: error decoding public key %v: %v", publicKey, err))
return
}
// Get the current Wyre Order Metadata from global state
currentWyreWalletOrderMetadata, err := fes.GetWyreWalletOrderMetadataFromGlobalState(publicKey, timestamp)
// Initialize the new Wyre Order Metadata object based on the current wallet order metadata (if it exists)
// and the current payload.
newMetadataObj := WyreWalletOrderMetadata{
LatestWyreWalletOrderWebhookPayload: wyreWalletOrderWebhookRequest,
}
if currentWyreWalletOrderMetadata != nil {
newMetadataObj.LatestWyreTrackWalletOrderResponse = currentWyreWalletOrderMetadata.LatestWyreTrackWalletOrderResponse
newMetadataObj.DeSoPurchasedNanos = currentWyreWalletOrderMetadata.DeSoPurchasedNanos
newMetadataObj.BasicTransferTxnBlockHash = currentWyreWalletOrderMetadata.BasicTransferTxnBlockHash
}
// Update global state before all transfer logic is completed so we have a record of the last webhook payload
// received in the event of an error when paying out DeSo.
fes.UpdateWyreGlobalState(ww, publicKeyBytes, timestamp, newMetadataObj)
// If there is a transferId, we need to get the transfer details, update the new metadata object and pay out
// deso if it has not been paid out yet.
if transferId != "" {
// Get the transfer details from Wyre
client := &http.Client{}
var wyreTrackOrderResponse *WyreTrackOrderResponse
wyreTrackOrderResponse, err = fes.TrackWalletOrder(client, transferId)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: error getting track wallet order response: %v. Webhook payload: %v", err, wyreWalletOrderWebhookRequest))
}
newMetadataObj.LatestWyreTrackWalletOrderResponse = wyreTrackOrderResponse
// If the amount of BTC purchased is greater than 0, compute how much DeSo to pay out if it has not been
// paid out yet.
btcPurchased := wyreTrackOrderResponse.DestAmount
if btcPurchased > 0 {
// BTC Purchased is in whole bitcoins, so multiply it by 10^8 to convert to Satoshis
satsPurchased := uint64(btcPurchased * lib.SatoshisPerBitcoin)
nanosPurchased := fes.GetNanosFromSats(satsPurchased, fes.BuyDESOFeeBasisPoints)
var balanceInsufficient bool
balanceInsufficient, err = fes.ExceedsDeSoBalance(nanosPurchased, fes.Config.BuyDESOSeed)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrdersubscription: Error checking if send deso balance is sufficient: %v", err))
return
}
if balanceInsufficient {
// TODO: THIS SHOULD TRIGGER ALERT
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrdersubscription: SendDeSo wallet balance is below nanos purchased"))
return
}
// Make sure this order hasn't been paid out, then mark it as paid out.
wyreOrderIdKey := GlobalStateKeyForWyreOrderIDProcessed(orderIdBytes)
// We expect badger to return a key not found error if DeSo has been paid out for this order.
// If it does not return an error, DeSo has already been paid out, so we skip ahead.
if val, _ := fes.GlobalState.Get(wyreOrderIdKey); val == nil {
// Mark this order as paid out
if err = fes.GlobalState.Put(wyreOrderIdKey, []byte{1}); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: error marking orderId %v as paid out: %v", orderId, err))
return
}
// Pay out deso to send to the public key
var txnHash *lib.BlockHash
txnHash, err = fes.SendSeedDeSo(publicKeyBytes, nanosPurchased, true)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: error paying out deso: %v", err))
// In the event that sending the deso to the public key fails for some reason, we will "unmark"
// this order as paid in global state
if err = fes.GlobalState.Delete(wyreOrderIdKey); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("WyreWalletOrderSubscription: error deleting order id key when failing to payout deso: %v", err))
}
return
}
// Set the basic transfer txn hash and deso purchased nanos of the metadata object
newMetadataObj.BasicTransferTxnBlockHash = txnHash
newMetadataObj.DeSoPurchasedNanos = nanosPurchased
}
}
}
// Update global state after all transfer logic is completed.
fes.UpdateWyreGlobalState(ww, publicKeyBytes, timestamp, newMetadataObj)
}
func (fes *APIServer) GetFullWalletOrderDetails(client *http.Client, orderId string) (_wyreWalletOrderFullDetails *WyreWalletOrderFullDetails, _err error) {
bodyBytes, err := fes.MakeWyreGetRequest(client, fmt.Sprintf("%v/v3/orders/%v/full", fes.Config.WyreUrl, orderId))
if err != nil {
return nil, fmt.Errorf("error getting full order details for orderId %v: %v", orderId, err)
}
var wyreWalletOrderFullDetails *WyreWalletOrderFullDetails
err = json.Unmarshal(bodyBytes, &wyreWalletOrderFullDetails)
if err != nil {
return nil, fmt.Errorf("error unmarshaling JSON from full order details bytes: %v", err)
}
// If the wallet order's destination does not match the configured address, that is an error.
if wyreWalletOrderFullDetails.Dest != fes.GetBTCAddress() {
return nil, fmt.Errorf("wyre wallet order's btc address (%v) does not match node's configured btc address (%v)", wyreWalletOrderFullDetails.Dest, fes.GetBTCAddress())
}
return wyreWalletOrderFullDetails, nil
}
func (fes *APIServer) GetTransferDetails(client *http.Client, transferId string) (_wyreTransferDetails *WyreTransferDetails, _err error) {
bodyBytes, err := fes.MakeWyreGetRequest(client, fmt.Sprintf("%v/v3/transfers/%v", fes.Config.WyreUrl, transferId))
if err != nil {
return nil, fmt.Errorf("error getting transfer details for transferId %v: %v", transferId, err)
}
var wyreTransferDetails *WyreTransferDetails
if err = json.Unmarshal(bodyBytes, &wyreTransferDetails); err != nil {
return nil, fmt.Errorf("error unmarshaling JSON from transfer details bytes: %v", err)
}
return wyreTransferDetails, nil
}
type WyreTrackOrderResponse struct {
TransferId string `json:"transferId"`
FeeCurrency string `json:"feeCurrency"`
Fee float64 `json:"fee"`
Fees struct {
BTC float64 `json:"BTC"`
USD float64 `json:"USD"`
} `json:"fees"`
SourceCurrency string `json:"sourceCurrency"`
DestCurrency string `json:"destCurrency"`
SourceAmount float64 `json:"sourceAmount"`
DestAmount float64 `json:"destAmount"`
DestSrn string `json:"destSrn"`
From string `json:"from"`
To interface{} `json:"to"`
Rate float64 `json:"rate"`
CustomId interface{} `json:"customId"`
Status interface{} `json:"status"`
BlockchainNetworkTx interface{} `json:"blockchainNetworkTx"`
Message interface{} `json:"message"`
TransferHistoryEntryType string `json:"transferHistoryEntryType"`
SuccessTimeline []struct {
StatusDetails string `json:"statusDetails"`
State string `json:"state"`
CreatedAt int64 `json:"createdAt"`
} `json:"successTimeline"`
FailedTimeline []interface{} `json:"failedTimeline"`
FailureReason interface{} `json:"failureReason"`
ReversalReason interface{} `json:"reversalReason"`
}
func (fes *APIServer) TrackWalletOrder(client *http.Client, transferId string) (_wyreTrackOrderResponse *WyreTrackOrderResponse, _err error) {
bodyBytes, err := fes.MakeWyreGetRequest(client, fmt.Sprintf("%v/v2/transfer/%v/track", fes.Config.WyreUrl, transferId))
if err != nil {
return nil, fmt.Errorf("error tracking transferId %v: %v", transferId, err)
}
var wyreTrackOrderResponse *WyreTrackOrderResponse
if err = json.Unmarshal(bodyBytes, &wyreTrackOrderResponse); err != nil {
return nil, fmt.Errorf("error unmarshaling JSON from transfer details bytes: %v", err)
}
// If the wallet order's destination does not match the configured address, that is an error.
if wyreTrackOrderResponse.DestSrn != fes.GetBTCAddress() {
return nil, fmt.Errorf("wyre wallet order's btc address (%v) does not match node's configured btc address (%v)", wyreTrackOrderResponse.DestSrn, fes.GetBTCAddress())
}
return wyreTrackOrderResponse, nil
}
func (fes *APIServer) UpdateWyreGlobalState(ww http.ResponseWriter, publicKeyBytes []byte, timestampNanos uint64, wyreWalletOrderMetadata WyreWalletOrderMetadata) {
// Construct the key for accessing the wyre order metadata
globalStateKey := GlobalStateKeyForUserPublicKeyTstampNanosToWyreOrderMetadata(publicKeyBytes, timestampNanos)
// Encode the WyreWalletOrderMetadata
wyreWalletOrderMetadataBuf := bytes.NewBuffer([]byte{})
if err := gob.NewEncoder(wyreWalletOrderMetadataBuf).Encode(wyreWalletOrderMetadata); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("error encoding wyre wallet order metadata: %v", err))
return
}
// Put the metadata in GlobalState
if err := fes.GlobalState.Put(globalStateKey, wyreWalletOrderMetadataBuf.Bytes()); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("Update Wyre Global state failed: %v", err))
return
}
}
type WalletOrderQuotationRequest struct {
SourceAmount float64
Country string
SourceCurrency string
}
type WyreWalletOrderQuotationPayload struct {
SourceCurrency string `json:"sourceCurrency"`
Dest string `json:"dest"`
DestCurrency string `json:"destCurrency"`
AmountIncludeFees bool `json:"amountIncludeFees"`
Country string `json:"country"`
SourceAmount string `json:"sourceAmount"`
WalletType string `json:"walletType"`
AccountId string `json:"accountId"`
}
func (fes *APIServer) GetWyreWalletOrderQuotation(ww http.ResponseWriter, req *http.Request) {
// Exit immediately if this node has not integrated with Wyre
if !fes.IsConfiguredForWyre() {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrderQuotation: This node is not configured with Wyre"))
return
}
// Decode the request body
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
wyreWalletOrderQuotationRequest := WalletOrderQuotationRequest{}
if err := decoder.Decode(&wyreWalletOrderQuotationRequest); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrderQuotation: Error parsing request body: %v", err))
return
}
// Make and marshal the payload
body := WyreWalletOrderQuotationPayload{
AccountId: fes.Config.WyreAccountId,
Dest: fmt.Sprintf("bitcoin:%v", fes.Config.BuyDESOBTCAddress),
AmountIncludeFees: true,
DestCurrency: "BTC",
SourceCurrency: wyreWalletOrderQuotationRequest.SourceCurrency,
Country: wyreWalletOrderQuotationRequest.Country,
WalletType: "DEBIT_CARD",
SourceAmount: fmt.Sprintf("%f", wyreWalletOrderQuotationRequest.SourceAmount),
}
payload, err := json.Marshal(body)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrderQuotation: Error marshaling JSON body: %v", err))
return
}
// Construct the URL
url := fmt.Sprintf("%v/v3/orders/quote/partner?timestamp=%v", fes.Config.WyreUrl, uint64(time.Now().UnixNano()))
// Make the request get an order reservation to Wyre
fes.MakeWyrePostRequest(payload, url, ww)
}
type WalletOrderReservationRequest struct {
SourceAmount float64
ReferenceId string
Country string
SourceCurrency string
RedirectUrl string
}
type WyreWalletOrderReservationPayload struct {
SourceCurrency string `json:"sourceCurrency"`
Dest string `json:"dest"`
DestCurrency string `json:"destCurrency"`
Country string `json:"country"`
Amount string `json:"amount"`
ReferrerAccountId string `json:"referrerAccountId"`
LockFields []string `json:"lockFields"`
RedirectUrl string `json:"redirectUrl"`
ReferenceId string `json:"referenceId"`
}
func (fes *APIServer) GetWyreWalletOrderReservation(ww http.ResponseWriter, req *http.Request) {
// Exit immediately if this node has not integrated with Wyre
if !fes.IsConfiguredForWyre() {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrderReservation: This node is not configured with Wyre"))
return
}
// Decode the request body
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
wyreWalletOrderReservationRequest := WalletOrderReservationRequest{}
if err := decoder.Decode(&wyreWalletOrderReservationRequest); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrderReservation: Error parsing request body: %v", err))
return
}
referenceId := wyreWalletOrderReservationRequest.ReferenceId
// Decode the referenceId as a public key.
if publicKeyBytes, _, err := lib.Base58CheckDecode(referenceId); err != nil || len(publicKeyBytes) != btcec.PubKeyBytesLenCompressed {
_AddBadRequestError(ww, fmt.Sprintf(
"GetWyreWalletOrderReservation: Problem decoding ReferenceId as public key %s: %v",
referenceId, err))
return
}
redirectUrl := fmt.Sprintf("https://%v/buy-deso", req.Host)
if wyreWalletOrderReservationRequest.RedirectUrl != "" {
if _, err := url.ParseRequestURI(wyreWalletOrderReservationRequest.RedirectUrl); err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"GetWyreWalletOrderReservation: Problem parse redirectUrl: %v", err))
return
}
redirectUrl = wyreWalletOrderReservationRequest.RedirectUrl
}
currentTime := uint64(time.Now().UnixNano())
// Make and marshal the payload
body := WyreWalletOrderReservationPayload{
ReferrerAccountId: fes.Config.WyreAccountId,
Dest: fes.GetBTCAddress(),
DestCurrency: "BTC",
SourceCurrency: wyreWalletOrderReservationRequest.SourceCurrency,
Country: wyreWalletOrderReservationRequest.Country,
Amount: fmt.Sprintf("%f", wyreWalletOrderReservationRequest.SourceAmount),
LockFields: []string{"dest", "destCurrency"},
RedirectUrl: redirectUrl,
ReferenceId: fmt.Sprintf("%v:%v", referenceId, currentTime),
}
payload, err := json.Marshal(body)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrderReservation: Error marshaling JSON body: %v", err))
return
}
// Construct the URL
url := fmt.Sprintf("%v/v3/orders/reserve?timestamp=%v", fes.Config.WyreUrl, currentTime)
// Make the request get an order reservation to Wyre.
fes.MakeWyrePostRequest(payload, url, ww)
}
func (fes *APIServer) MakeWyrePostRequest(payload []byte, url string, ww http.ResponseWriter) {
// Create a new buffer and request
payloadBytes := bytes.NewBuffer(payload)
wyreReq, err := http.NewRequest("POST", url, payloadBytes)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("Problem creating new wyre request: %v", err))
return
}
// Set the wyre headers appropriately
wyreReq = fes.SetWyreRequestHeaders(wyreReq, payloadBytes.Bytes())
// Perform the POST request
client := &http.Client{}
resp, err := client.Do(wyreReq)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("Problem executing wyre request: %v", err))
return
}
defer resp.Body.Close()
// Read the response body and write it to the response writer
wyreResponseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("Problem reading wyre response: %v", err))
return
}
if _, err = ww.Write(wyreResponseBody); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("Problem writing wyte response: %v", err))
return
}
}
func (fes *APIServer) MakeWyreGetRequest(client *http.Client, url string) (_bodyBytes []byte, _err error) {
// Make the request and set the headers
request, err := http.NewRequest("GET", fmt.Sprintf("%v?timestamp=%v", url, uint64(time.Now().UnixNano())), nil)
if err != nil {
return nil, fmt.Errorf("error creating get request: %v", err)
}
request = fes.SetWyreRequestHeaders(request, nil)
// Execute the request and handle errors
response, err := client.Do(request)
if err != nil {
return nil, fmt.Errorf("error performing wyre get request: %v", err)
}
if response == nil {
return nil, fmt.Errorf("wyre response is nil")
}
// If the response is not a 200, raise an error.
if response.StatusCode != 200 {
// what is the appropriate way to handle these errors.
return nil, fmt.Errorf("wyre responded with a non-200 status code of %v", response.StatusCode)
}
defer response.Body.Close()
// Read the response body and unmarshal it
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("error reading body from wyre response: %v", err)
}
return bodyBytes, nil
}
func (fes *APIServer) GetWyreWalletOrderMetadataFromGlobalState(publicKey string, timestamp uint64) (*WyreWalletOrderMetadata, error) {
// Decode the public get and get the key to access the Wyre Order Metadata
publicKeyBytes, _, err := lib.Base58CheckDecode(publicKey)
if err != nil {
return nil, err
}
globalStateKey := GlobalStateKeyForUserPublicKeyTstampNanosToWyreOrderMetadata(publicKeyBytes, timestamp)
// Get Wyre Order Metadata from global state and decode it
currentWyreWalletOrderMetadataBytes, err := fes.GlobalState.Get(globalStateKey)
if err != nil {
return nil, err
}
currentWyreWalletOrderMetadata := &WyreWalletOrderMetadata{}
if err = gob.NewDecoder(bytes.NewReader(currentWyreWalletOrderMetadataBytes)).Decode(currentWyreWalletOrderMetadata); err != nil {
return nil, err
}
return currentWyreWalletOrderMetadata, err
}
func (fes *APIServer) SetWyreRequestHeaders(req *http.Request, dataBytes []byte) *http.Request {
// Set the API Key and Content type headers
req.Header.Set("X-Api-Key", fes.Config.WyreApiKey)
req.Header.Set("Content-Type", "application/json")
// Wyre expects the signature to be HEX encoded HMAC with SHA-256 and the Wyre secret key
// the message will be the URL + the data (if it is a GET request, data will be nil
// For more details, see this link: https://docs.sendwyre.com/docs/authentication#secret-key-signature-auth
h := hmac.New(sha256.New, []byte(fes.Config.WyreSecretKey))
h.Write([]byte(req.URL.String()))
h.Write(dataBytes)
req.Header.Set("X-Api-Signature", hex.EncodeToString(h.Sum(nil)))
return req
}
func (fes *APIServer) GetBTCAddress() string {
return fmt.Sprintf("bitcoin:%v", fes.Config.BuyDESOBTCAddress)
}
type GetWyreWalletOrderForPublicKeyRequest struct {
PublicKeyBase58Check string
Username string
AdminPublicKey string
}
type GetWyreWalletOrderForPublicKeyResponse struct {
WyreWalletOrderMetadataResponses []*WyreWalletOrderMetadataResponse
}
func (fes *APIServer) GetWyreWalletOrdersForPublicKey(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := GetWyreWalletOrderForPublicKeyRequest{}
var err error
if err = decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrdersForPublicKey: Error parsing request body: %v", err))
return
}
var publicKeyBytes []byte
if requestData.PublicKeyBase58Check != "" {
publicKeyBytes, _, err = lib.Base58CheckDecode(requestData.PublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrdersForPublicKey: error decoding public key %v: %v", requestData.PublicKeyBase58Check, err))
return
}
} else if requestData.Username != "" {
var utxoView *lib.UtxoView
utxoView, err = fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrdersForPublicKey: error getting utxoview: %v", err))
return
}
profileEntry := utxoView.GetProfileEntryForUsername([]byte(requestData.Username))
if profileEntry == nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrdersForPublicKey: error getting profile entry for username %v", requestData.Username))
return
}
publicKeyBytes = profileEntry.PublicKey
} else {
_AddBadRequestError(ww, "GetWyreWalletOrdersForPublicKey: must provide either a public key or username")
return
}
var values [][]byte
// 1 + max length of public key + max uint64 bytes length
maxKeyLen := 1 + btcec.PubKeyBytesLenCompressed + 8
prefix := GlobalStateKeyForUserPublicKeyTstampNanosToWyreOrderMetadata(publicKeyBytes, math.MaxUint64)
validPrefix := append(_GlobalStatePrefixUserPublicKeyWyreOrderIdToWyreOrderMetadata, publicKeyBytes...)
_, values, err = fes.GlobalState.Seek(prefix, validPrefix, maxKeyLen, 100, true, true)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrdersForPublicKey: error getting wyre order metadata from global state"))
return
}
res := &GetWyreWalletOrderForPublicKeyResponse{
WyreWalletOrderMetadataResponses: []*WyreWalletOrderMetadataResponse{},
}
for _, wyreOrderMetadataBytes := range values {
var wyreOrderMetadata *WyreWalletOrderMetadata
err = gob.NewDecoder(bytes.NewReader(wyreOrderMetadataBytes)).Decode(&wyreOrderMetadata)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrdersForPublicKey: error decoding order: %v", wyreOrderMetadataBytes))
return
}
res.WyreWalletOrderMetadataResponses = append(res.WyreWalletOrderMetadataResponses, fes.WyreWalletOrderMetadataToResponse(wyreOrderMetadata))
}
if err = json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetWyreWalletOrdersForPublicKey: Problem encoding response as JSON: #{err}"))
return
}
}
func (fes *APIServer) IsConfiguredForWyre() bool {
return fes.Config.WyreUrl != ""
}
type WyreWalletOrderMetadataResponse struct {
// Last payload received from Wyre webhook
LatestWyreWalletOrderWebhookPayload WyreWalletOrderWebhookPayload
// Track Wallet Order response received based on the last payload received from Wyre Webhook
LatestWyreTrackWalletOrderResponse *WyreTrackOrderResponse
// Amount of DeSo that was sent for this WyreWalletOrder
DeSoPurchasedNanos uint64
BitCloutPurchasedNanos uint64 // Deprecated
// BlockHash of the transaction for sending the DeSo
BasicTransferTxnHash string
Timestamp *time.Time
}
func (fes *APIServer) WyreWalletOrderMetadataToResponse(metadata *WyreWalletOrderMetadata) *WyreWalletOrderMetadataResponse {
orderMetadataResponse := WyreWalletOrderMetadataResponse{
LatestWyreTrackWalletOrderResponse: metadata.LatestWyreTrackWalletOrderResponse,
LatestWyreWalletOrderWebhookPayload: metadata.LatestWyreWalletOrderWebhookPayload,
DeSoPurchasedNanos: metadata.DeSoPurchasedNanos,
BitCloutPurchasedNanos: metadata.DeSoPurchasedNanos,
Timestamp: getTimestampFromReferenceId(metadata.LatestWyreWalletOrderWebhookPayload.ReferenceId),
}
basicTransferTxnHash := metadata.BasicTransferTxnBlockHash
if basicTransferTxnHash != nil {
orderMetadataResponse.BasicTransferTxnHash = lib.PkToString(basicTransferTxnHash[:], fes.Params)
}
return &orderMetadataResponse
}
func getTimestampFromReferenceId(referenceId string) *time.Time {
splits := strings.Split(referenceId, ":")
uint64Timestamp, err := strconv.ParseUint(splits[1], 10, 64)
if err != nil {
return nil
}
timestamp := time.Unix(0, int64(uint64Timestamp))
return ×tamp
}