forked from vegaprotocol/vegawallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
891 lines (729 loc) · 23.3 KB
/
service.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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
package service
import (
"context"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"code.vegaprotocol.io/protos/commands"
typespb "code.vegaprotocol.io/protos/vega"
api "code.vegaprotocol.io/protos/vega/api/v1"
commandspb "code.vegaprotocol.io/protos/vega/commands/v1"
walletpb "code.vegaprotocol.io/protos/vega/wallet/v1"
wcommands "code.vegaprotocol.io/vegawallet/commands"
"code.vegaprotocol.io/vegawallet/network"
"code.vegaprotocol.io/vegawallet/version"
"code.vegaprotocol.io/vegawallet/wallet"
"github.com/golang/protobuf/jsonpb"
"github.com/julienschmidt/httprouter"
"github.com/rs/cors"
"go.uber.org/zap"
"google.golang.org/grpc/status"
)
type Service struct {
*httprouter.Router
network *network.Network
log *zap.Logger
server *http.Server
handler WalletHandler
auth Auth
nodeForward NodeForward
}
// CreateWalletRequest describes the request for CreateWallet.
type CreateWalletRequest struct {
Wallet string `json:"wallet"`
Passphrase string `json:"passphrase"`
}
func ParseCreateWalletRequest(r *http.Request) (*CreateWalletRequest, commands.Errors) {
errs := commands.NewErrors()
req := &CreateWalletRequest{}
if err := unmarshalBody(r, &req); err != nil {
return nil, errs.FinalAdd(err)
}
if len(req.Wallet) == 0 {
errs.AddForProperty("wallet", commands.ErrIsRequired)
}
if len(req.Passphrase) == 0 {
errs.AddForProperty("passphrase", commands.ErrIsRequired)
}
if !errs.Empty() {
return nil, errs
}
return req, errs
}
// CreateWalletResponse returns the authentication token and the auto-generated
// recovery phrase of the created wallet.
type CreateWalletResponse struct {
RecoveryPhrase string `json:"recoveryPhrase"`
Token string `json:"token"`
}
// ImportWalletRequest describes the request for ImportWallet.
type ImportWalletRequest struct {
Wallet string `json:"wallet"`
Passphrase string `json:"passphrase"`
RecoveryPhrase string `json:"recoveryPhrase"`
Version uint32 `json:"version"`
}
func ParseImportWalletRequest(r *http.Request) (*ImportWalletRequest, commands.Errors) {
errs := commands.NewErrors()
req := &ImportWalletRequest{}
if err := unmarshalBody(r, &req); err != nil {
return nil, errs.FinalAdd(err)
}
if len(req.Wallet) == 0 {
errs.AddForProperty("wallet", commands.ErrIsRequired)
}
if len(req.Passphrase) == 0 {
errs.AddForProperty("passphrase", commands.ErrIsRequired)
}
if len(req.RecoveryPhrase) == 0 {
errs.AddForProperty("recoveryPhrase", commands.ErrIsRequired)
}
if req.Version == 0 {
req.Version = wallet.LatestVersion
}
if !errs.Empty() {
return nil, errs
}
return req, errs
}
// LoginWalletRequest describes the request for CreateWallet, LoginWallet.
type LoginWalletRequest struct {
Wallet string `json:"wallet"`
Passphrase string `json:"passphrase"`
}
func ParseLoginWalletRequest(r *http.Request) (*LoginWalletRequest, commands.Errors) {
errs := commands.NewErrors()
req := &LoginWalletRequest{}
if err := unmarshalBody(r, &req); err != nil {
return nil, errs.FinalAdd(err)
}
if len(req.Wallet) == 0 {
errs.AddForProperty("wallet", commands.ErrIsRequired)
}
if len(req.Passphrase) == 0 {
errs.AddForProperty("passphrase", commands.ErrIsRequired)
}
if !errs.Empty() {
return nil, errs
}
return req, errs
}
// TaintKeyRequest describes the request for TaintKey.
type TaintKeyRequest struct {
Passphrase string `json:"passphrase"`
}
func ParseTaintKeyRequest(r *http.Request, keyID string) (*TaintKeyRequest, commands.Errors) {
errs := commands.NewErrors()
if len(keyID) == 0 {
errs.AddForProperty("keyid", commands.ErrIsRequired)
}
req := &TaintKeyRequest{}
if err := unmarshalBody(r, &req); err != nil {
return nil, errs.FinalAdd(err)
}
if len(req.Passphrase) == 0 {
errs.AddForProperty("passphrase", commands.ErrIsRequired)
}
if !errs.Empty() {
return nil, errs
}
return req, errs
}
// GenKeyPairRequest describes the request for GenerateKeyPair.
type GenKeyPairRequest struct {
Passphrase string `json:"passphrase"`
Meta []wallet.Meta `json:"meta"`
}
func ParseGenKeyPairRequest(r *http.Request) (*GenKeyPairRequest, commands.Errors) {
errs := commands.NewErrors()
req := &GenKeyPairRequest{}
if err := unmarshalBody(r, &req); err != nil {
return nil, errs.FinalAdd(err)
}
if len(req.Passphrase) == 0 {
errs.AddForProperty("passphrase", commands.ErrIsRequired)
}
if !errs.Empty() {
return nil, errs
}
return req, errs
}
// UpdateMetaRequest describes the request for UpdateMeta.
type UpdateMetaRequest struct {
Passphrase string `json:"passphrase"`
Meta []wallet.Meta `json:"meta"`
}
func ParseUpdateMetaRequest(r *http.Request, keyID string) (*UpdateMetaRequest, commands.Errors) {
errs := commands.NewErrors()
if len(keyID) == 0 {
errs.AddForProperty("keyid", commands.ErrIsRequired)
}
req := &UpdateMetaRequest{}
if err := unmarshalBody(r, &req); err != nil {
return nil, errs.FinalAdd(err)
}
if len(req.Passphrase) == 0 {
errs.AddForProperty("passphrase", commands.ErrIsRequired)
}
if !errs.Empty() {
return nil, errs
}
return req, errs
}
// SignAnyRequest describes the request for SignAny.
type SignAnyRequest struct {
// InputData is the payload to generate a signature from. I should be
// base 64 encoded.
InputData string `json:"inputData"`
// PubKey is used to retrieve the private key to sign the InputDate.
PubKey string `json:"pubKey"`
decodedInputData []byte
}
func ParseSignAnyRequest(r *http.Request) (*SignAnyRequest, commands.Errors) {
errs := commands.NewErrors()
req := &SignAnyRequest{}
if err := unmarshalBody(r, &req); err != nil {
return nil, errs.FinalAdd(err)
}
if len(req.InputData) == 0 {
errs.AddForProperty("inputData", commands.ErrIsRequired)
}
decodedInputData, err := base64.StdEncoding.DecodeString(req.InputData)
if err != nil {
errs.AddForProperty("inputData", ErrShouldBeBase64Encoded)
} else {
req.decodedInputData = decodedInputData
}
if len(req.PubKey) == 0 {
errs.AddForProperty("pubKey", commands.ErrIsRequired)
}
if !errs.Empty() {
return nil, errs
}
return req, errs
}
// VerifyAnyRequest describes the request for VerifyAny.
type VerifyAnyRequest struct {
// InputData is the payload to be verified. It should be base64 encoded.
InputData string `json:"inputData"`
// Signature is the signature to check against the InputData. It should be
// base64 encoded.
Signature string `json:"signature"`
// PubKey is the public key used along the signature to check the InputData.
PubKey string `json:"pubKey"`
decodedInputData []byte
decodedSignature []byte
}
func ParseVerifyAnyRequest(r *http.Request) (*VerifyAnyRequest, commands.Errors) {
errs := commands.NewErrors()
req := &VerifyAnyRequest{}
if err := unmarshalBody(r, &req); err != nil {
return nil, errs.FinalAdd(err)
}
if len(req.InputData) == 0 {
errs.AddForProperty("inputData", commands.ErrIsRequired)
} else {
decodedInputData, err := base64.StdEncoding.DecodeString(req.InputData)
if err != nil {
errs.AddForProperty("inputData", ErrShouldBeBase64Encoded)
} else {
req.decodedInputData = decodedInputData
}
}
if len(req.Signature) == 0 {
errs.AddForProperty("signature", commands.ErrIsRequired)
} else {
decodedSignature, err := base64.StdEncoding.DecodeString(req.Signature)
if err != nil {
errs.AddForProperty("signature", ErrShouldBeBase64Encoded)
} else {
req.decodedSignature = decodedSignature
}
}
if len(req.PubKey) == 0 {
errs.AddForProperty("pubKey", commands.ErrIsRequired)
}
if !errs.Empty() {
return nil, errs
}
return req, nil
}
func ParseSubmitTransactionRequest(r *http.Request) (*walletpb.SubmitTransactionRequest, commands.Errors) {
errs := commands.NewErrors()
req := &walletpb.SubmitTransactionRequest{}
if err := jsonpb.Unmarshal(r.Body, req); err != nil {
return nil, errs.FinalAdd(err)
}
if errs = wcommands.CheckSubmitTransactionRequest(req); !errs.Empty() {
return nil, errs
}
return req, nil
}
// KeyResponse describes the response to a request that returns a single key.
type KeyResponse struct {
Key wallet.PublicKey `json:"key"`
}
// KeysResponse describes the response to a request that returns a list of keys.
type KeysResponse struct {
Keys []wallet.PublicKey `json:"keys"`
}
// SignAnyResponse describes the response for SignAny.
type SignAnyResponse struct {
HexSignature string `json:"hexSignature"`
Base64Signature string `json:"base64Signature"`
}
// VerifyAnyResponse describes the response for VerifyAny.
type VerifyAnyResponse struct {
Valid bool `json:"success"`
}
// SuccessResponse describes the response to a request that returns a simple true/false answer.
type SuccessResponse struct {
Success bool `json:"success"`
}
// TokenResponse describes the response to a request that returns a token.
type TokenResponse struct {
Token string `json:"token"`
}
// VersionResponse describes the response to a request that returns app version info.
type VersionResponse struct {
Version string `json:"version"`
VersionHash string `json:"versionHash"`
}
// NetworkResponse describes the response to a request that returns app hosts info.
type NetworkResponse struct {
Network network.Network `json:"network"`
}
// WalletHandler ...
//go:generate go run github.com/golang/mock/mockgen -destination mocks/wallet_handler_mock.go -package mocks code.vegaprotocol.io/vegawallet/service WalletHandler
type WalletHandler interface {
CreateWallet(name, passphrase string) (string, error)
ImportWallet(name, passphrase, recoveryPhrase string, version uint32) error
LoginWallet(name, passphrase string) error
LogoutWallet(name string)
SecureGenerateKeyPair(name, passphrase string, meta []wallet.Meta) (string, error)
GetPublicKey(name, pubKey string) (wallet.PublicKey, error)
ListPublicKeys(name string) ([]wallet.PublicKey, error)
SignTx(name string, req *walletpb.SubmitTransactionRequest, height uint64) (*commandspb.Transaction, error)
SignAny(name string, inputData []byte, pubKey string) ([]byte, error)
VerifyAny(inputData, sig []byte, pubKey string) (bool, error)
TaintKey(name, pubKey, passphrase string) error
UpdateMeta(name, pubKey, passphrase string, meta []wallet.Meta) error
}
// Auth ...
//go:generate go run github.com/golang/mock/mockgen -destination mocks/auth_mock.go -package mocks code.vegaprotocol.io/vegawallet/service Auth
type Auth interface {
NewSession(name string) (string, error)
VerifyToken(token string) (string, error)
Revoke(token string) (string, error)
}
// NodeForward ...
//go:generate go run github.com/golang/mock/mockgen -destination mocks/node_forward_mock.go -package mocks code.vegaprotocol.io/vegawallet/service NodeForward
type NodeForward interface {
SendTx(context.Context, *commandspb.Transaction, api.SubmitTransactionRequest_Type) (string, error)
HealthCheck(context.Context) error
LastBlockHeight(context.Context) (uint64, error)
}
func NewService(log *zap.Logger, net *network.Network, h WalletHandler, a Auth, n NodeForward) (*Service, error) {
s := &Service{
Router: httprouter.New(),
log: log,
handler: h,
auth: a,
nodeForward: n,
network: net,
}
s.server = &http.Server{
Addr: fmt.Sprintf("%s:%v", net.Host, net.Port),
Handler: cors.AllowAll().Handler(s),
}
s.handle(http.MethodPost, "/api/v1/auth/token", s.Login)
s.handle(http.MethodDelete, "/api/v1/auth/token", extractToken(s.Revoke))
s.handle(http.MethodGet, "/api/v1/network", s.GetNetwork)
s.handle(http.MethodPost, "/api/v1/wallets", s.CreateWallet)
s.handle(http.MethodPost, "/api/v1/wallets/import", s.ImportWallet)
s.handle(http.MethodGet, "/api/v1/keys", extractToken(s.ListPublicKeys))
s.handle(http.MethodPost, "/api/v1/keys", extractToken(s.GenerateKeyPair))
s.handle(http.MethodGet, "/api/v1/keys/:keyid", extractToken(s.GetPublicKey))
s.handle(http.MethodPut, "/api/v1/keys/:keyid/taint", extractToken(s.TaintKey))
s.handle(http.MethodPut, "/api/v1/keys/:keyid/metadata", extractToken(s.UpdateMeta))
s.handle(http.MethodPost, "/api/v1/command", extractToken(s.SignTx))
s.handle(http.MethodPost, "/api/v1/command/sync", extractToken(s.SignTxSync))
s.handle(http.MethodPost, "/api/v1/command/commit", extractToken(s.SignTxCommit))
s.handle(http.MethodPost, "/api/v1/sign", extractToken(s.SignAny))
s.handle(http.MethodPost, "/api/v1/verify", s.VerifyAny)
s.handle(http.MethodGet, "/api/v1/version", s.Version)
s.handle(http.MethodGet, "/api/v1/status", s.Health)
return s, nil
}
func (s *Service) Start() error {
return s.server.ListenAndServe()
}
func (s *Service) Stop() error {
return s.server.Shutdown(context.Background())
}
func (s *Service) CreateWallet(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
req, errs := ParseCreateWalletRequest(r)
if !errs.Empty() {
s.writeBadRequest(w, errs)
return
}
recoveryPhrase, err := s.handler.CreateWallet(req.Wallet, req.Passphrase)
if err != nil {
s.writeBadRequestErr(w, err)
return
}
token, err := s.auth.NewSession(req.Wallet)
if err != nil {
s.writeInternalError(w, err)
return
}
s.writeSuccess(w, CreateWalletResponse{
RecoveryPhrase: recoveryPhrase,
Token: token,
})
}
func (s *Service) ImportWallet(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
req, errs := ParseImportWalletRequest(r)
if !errs.Empty() {
s.writeBadRequest(w, errs)
return
}
err := s.handler.ImportWallet(req.Wallet, req.Passphrase, req.RecoveryPhrase, req.Version)
if err != nil {
s.writeBadRequestErr(w, err)
return
}
token, err := s.auth.NewSession(req.Wallet)
if err != nil {
s.writeInternalError(w, err)
return
}
s.writeSuccess(w, TokenResponse{Token: token})
}
func (s *Service) Login(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
req, errs := ParseLoginWalletRequest(r)
if !errs.Empty() {
s.writeBadRequest(w, errs)
return
}
err := s.handler.LoginWallet(req.Wallet, req.Passphrase)
if err != nil {
s.writeForbiddenError(w, err)
return
}
token, err := s.auth.NewSession(req.Wallet)
if err != nil {
s.writeInternalError(w, err)
return
}
s.writeSuccess(w, TokenResponse{Token: token})
}
func (s *Service) Revoke(t string, w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
name, err := s.auth.Revoke(t)
if err != nil {
s.writeForbiddenError(w, err)
return
}
s.handler.LogoutWallet(name)
s.writeSuccess(w, nil)
}
func (s *Service) GenerateKeyPair(t string, w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
req, errs := ParseGenKeyPairRequest(r)
if !errs.Empty() {
s.writeBadRequest(w, errs)
return
}
name, err := s.auth.VerifyToken(t)
if err != nil {
s.writeForbiddenError(w, err)
return
}
pubKey, err := s.handler.SecureGenerateKeyPair(name, req.Passphrase, req.Meta)
if err != nil {
if errors.Is(err, wallet.ErrWrongPassphrase) {
s.writeForbiddenError(w, err)
} else {
s.writeInternalError(w, err)
}
return
}
key, err := s.handler.GetPublicKey(name, pubKey)
if err != nil {
s.writeInternalError(w, err)
return
}
s.writeSuccess(w, KeyResponse{Key: key})
}
func (s *Service) GetPublicKey(t string, w http.ResponseWriter, _ *http.Request, ps httprouter.Params) {
name, err := s.auth.VerifyToken(t)
if err != nil {
s.writeForbiddenError(w, err)
return
}
key, err := s.handler.GetPublicKey(name, ps.ByName("keyid"))
if err != nil {
var statusCode int
if errors.Is(err, wallet.ErrPubKeyDoesNotExist) {
statusCode = http.StatusNotFound
} else {
statusCode = http.StatusInternalServerError
}
s.writeError(w, newErrorResponse(err.Error()), statusCode)
return
}
s.writeSuccess(w, KeyResponse{Key: key})
}
func (s *Service) ListPublicKeys(t string, w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
name, err := s.auth.VerifyToken(t)
if err != nil {
s.writeForbiddenError(w, err)
return
}
keys, err := s.handler.ListPublicKeys(name)
if err != nil {
s.writeInternalError(w, err)
return
}
s.writeSuccess(w, KeysResponse{Keys: keys})
}
func (s *Service) TaintKey(t string, w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
keyID := ps.ByName("keyid")
req, errs := ParseTaintKeyRequest(r, keyID)
if !errs.Empty() {
s.writeBadRequest(w, errs)
return
}
name, err := s.auth.VerifyToken(t)
if err != nil {
s.writeForbiddenError(w, err)
return
}
if err = s.handler.TaintKey(name, keyID, req.Passphrase); err != nil {
if errors.Is(err, wallet.ErrWrongPassphrase) {
s.writeForbiddenError(w, err)
} else {
s.writeInternalError(w, err)
}
return
}
s.writeSuccess(w, nil)
}
func (s *Service) UpdateMeta(t string, w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
keyID := ps.ByName("keyid")
req, errs := ParseUpdateMetaRequest(r, keyID)
if !errs.Empty() {
s.writeBadRequest(w, errs)
return
}
name, err := s.auth.VerifyToken(t)
if err != nil {
s.writeForbiddenError(w, err)
return
}
if err = s.handler.UpdateMeta(name, keyID, req.Passphrase, req.Meta); err != nil {
if errors.Is(err, wallet.ErrWrongPassphrase) {
s.writeForbiddenError(w, err)
} else {
s.writeInternalError(w, err)
}
return
}
s.writeSuccess(w, nil)
}
func (s *Service) SignAny(t string, w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
req, errs := ParseSignAnyRequest(r)
if !errs.Empty() {
s.writeBadRequest(w, errs)
return
}
name, err := s.auth.VerifyToken(t)
if err != nil {
s.writeForbiddenError(w, err)
return
}
signature, err := s.handler.SignAny(name, req.decodedInputData, req.PubKey)
if err != nil {
s.writeInternalError(w, err)
return
}
res := SignAnyResponse{
HexSignature: hex.EncodeToString(signature),
Base64Signature: base64.StdEncoding.EncodeToString(signature),
}
s.writeSuccess(w, res)
}
func (s *Service) VerifyAny(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
req, errs := ParseVerifyAnyRequest(r)
if !errs.Empty() {
s.writeBadRequest(w, errs)
return
}
verified, err := s.handler.VerifyAny(req.decodedInputData, req.decodedSignature, req.PubKey)
if err != nil {
s.writeInternalError(w, err)
return
}
s.writeSuccess(w, VerifyAnyResponse{Valid: verified})
}
func (s *Service) SignTxSync(token string, w http.ResponseWriter, r *http.Request, p httprouter.Params) {
s.signTx(token, w, r, p, api.SubmitTransactionRequest_TYPE_SYNC)
}
func (s *Service) SignTxCommit(token string, w http.ResponseWriter, r *http.Request, p httprouter.Params) {
s.signTx(token, w, r, p, api.SubmitTransactionRequest_TYPE_COMMIT)
}
func (s *Service) SignTx(token string, w http.ResponseWriter, r *http.Request, p httprouter.Params) {
s.signTx(token, w, r, p, api.SubmitTransactionRequest_TYPE_ASYNC)
}
func (s *Service) signTx(token string, w http.ResponseWriter, r *http.Request, _ httprouter.Params, ty api.SubmitTransactionRequest_Type) {
defer r.Body.Close()
req, errs := ParseSubmitTransactionRequest(r)
if !errs.Empty() {
s.writeBadRequest(w, errs)
return
}
height, err := s.nodeForward.LastBlockHeight(r.Context())
if err != nil {
s.writeInternalError(w, ErrCouldNotGetBlockHeight)
return
}
name, err := s.auth.VerifyToken(token)
if err != nil {
s.writeForbiddenError(w, err)
return
}
tx, err := s.handler.SignTx(name, req, height)
if err != nil {
s.writeInternalError(w, err)
return
}
if !req.Propagate {
s.writeSuccess(w, nil)
return
}
txHash, err := s.nodeForward.SendTx(r.Context(), tx, ty)
if err != nil {
if st, ok := status.FromError(err); ok {
var details []string
for _, v := range st.Details() {
v, ok := v.(*typespb.ErrorDetail)
if !ok {
s.writeError(w, newErrorResponse(fmt.Sprintf("couldn't cast status details to error details: %v", v)), http.StatusInternalServerError)
}
details = append(details, v.Message)
}
s.writeError(w, newErrorWithDetails(err.Error(), details), http.StatusInternalServerError)
} else {
s.writeInternalError(w, err)
}
return
}
s.writeSuccess(w, struct {
TxHash string `json:"txHash"`
}{
TxHash: txHash,
})
}
func (s *Service) Version(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
res := VersionResponse{
Version: version.Version,
VersionHash: version.VersionHash,
}
s.writeSuccess(w, res)
}
func (s *Service) GetNetwork(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
res := NetworkResponse{
Network: *s.network,
}
s.writeSuccess(w, res)
}
func (s *Service) Health(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
if err := s.nodeForward.HealthCheck(r.Context()); err != nil {
s.writeError(w, newErrorResponse(err.Error()), http.StatusFailedDependency)
return
}
s.writeSuccess(w, nil)
}
func (s *Service) writeBadRequestErr(w http.ResponseWriter, err error) {
errs := commands.NewErrors()
s.writeErrors(w, http.StatusBadRequest, errs.FinalAdd(err))
}
func (s *Service) writeBadRequest(w http.ResponseWriter, errs commands.Errors) {
s.writeErrors(w, http.StatusBadRequest, errs)
}
func (s *Service) writeErrors(w http.ResponseWriter, statusCode int, errs commands.Errors) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
buf, _ := json.Marshal(ErrorsResponse{Errors: errs})
if _, err := w.Write(buf); err != nil {
s.log.Error("couldn't marshal error", zap.Error(errs))
w.WriteHeader(http.StatusInternalServerError)
}
s.log.Info(fmt.Sprintf("%d %s", statusCode, http.StatusText(statusCode)))
}
func unmarshalBody(r *http.Request, into interface{}) error {
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return ErrCouldNotReadRequest
}
if len(body) == 0 {
return nil
}
return json.Unmarshal(body, into)
}
func (s *Service) writeForbiddenError(w http.ResponseWriter, e error) {
s.writeError(w, newErrorResponse(e.Error()), http.StatusForbidden)
}
func (s *Service) writeInternalError(w http.ResponseWriter, e error) {
s.writeError(w, newErrorResponse(e.Error()), http.StatusInternalServerError)
}
func (s *Service) writeError(w http.ResponseWriter, e error, status int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
buf, err := json.Marshal(e)
if err != nil {
s.log.Error("couldn't marshal error", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = w.Write(buf)
if err != nil {
s.log.Error("couldn't write error to HTTP response", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
s.log.Info(fmt.Sprintf("%d %s", status, http.StatusText(status)))
}
func (s *Service) writeSuccess(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if data == nil {
s.log.Info(fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK)))
return
}
buf, err := json.Marshal(data)
if err != nil {
s.log.Error("couldn't marshal error", zap.Error(err))
s.writeInternalError(w, fmt.Errorf("couldn't marshal error: %w", err))
return
}
_, err = w.Write(buf)
if err != nil {
s.log.Error("couldn't write error to HTTP response", zap.Error(err))
s.writeInternalError(w, fmt.Errorf("couldn't write error to HTTP response: %w", err))
return
}
s.log.Info(fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK)))
}
func (s *Service) handle(method string, path string, handle httprouter.Handle) {
loggedEndpoint := func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
s.log.Info(fmt.Sprintf("--> %s %s", method, path))
handle(w, r, p)
s.log.Info(fmt.Sprintf("<-- %s %s", method, path))
}
s.Handle(method, path, loggedEndpoint)
}