-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest_api.go
1774 lines (1443 loc) · 62.9 KB
/
rest_api.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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package rest
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"golang.org/x/net/context"
"github.com/gocraft/web"
"github.com/golang/protobuf/jsonpb"
"github.com/op/go-logging"
"github.com/spf13/viper"
"github.com/golang/protobuf/ptypes/empty"
core "github.com/hyperledger/fabric/core"
"github.com/hyperledger/fabric/core/chaincode"
"github.com/hyperledger/fabric/core/comm"
"github.com/hyperledger/fabric/core/crypto"
"github.com/hyperledger/fabric/core/crypto/primitives"
pb "github.com/hyperledger/fabric/protos"
)
var restLogger = logging.MustGetLogger("rest")
// serverOpenchain is a variable that holds the pointer to the
// underlying ServerOpenchain object. serverDevops is a variable that holds
// the pointer to the underlying Devops object. This is necessary due to
// how the gocraft/web package implements context initialization.
var serverOpenchain *ServerOpenchain
var serverDevops pb.DevopsServer
// ServerOpenchainREST defines the Openchain REST service object. It exposes
// the methods available on the ServerOpenchain service and the Devops service
// through a REST API.
type ServerOpenchainREST struct {
server *ServerOpenchain
devops pb.DevopsServer
}
// restResult defines the response payload for a general REST interface request.
type restResult struct {
OK string `json:",omitempty"`
Error string `json:",omitempty"`
}
// tcertsResult defines the response payload for the GetTransactionCert REST
// interface request.
type tcertsResult struct {
OK []string
}
// rpcRequest defines the JSON RPC 2.0 request payload for the /chaincode endpoint.
type rpcRequest struct {
Jsonrpc *string `json:"jsonrpc,omitempty"`
Method *string `json:"method,omitempty"`
Params *pb.ChaincodeSpec `json:"params,omitempty"`
ID *rpcID `json:"id,omitempty"`
}
type rpcID struct {
StringValue *string
IntValue *int64
}
func (id *rpcID) UnmarshalJSON(b []byte) error {
var err error
s, n := "", int64(0)
if err = json.Unmarshal(b, &s); err == nil {
id.StringValue = &s
return nil
}
if err = json.Unmarshal(b, &n); err == nil {
id.IntValue = &n
return nil
}
return fmt.Errorf("cannot unmarshal %s into Go value of type int64 or string", string(b))
}
func (id *rpcID) MarshalJSON() ([]byte, error) {
if id.StringValue != nil {
return json.Marshal(id.StringValue)
}
if id.IntValue != nil {
return json.Marshal(id.IntValue)
}
return nil, errors.New("cannot marshal rpcID")
}
// rpcResponse defines the JSON RPC 2.0 response payload for the /chaincode endpoint.
type rpcResponse struct {
Jsonrpc string `json:"jsonrpc,omitempty"`
Result *rpcResult `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
ID *rpcID `json:"id"`
}
// rpcResult defines the structure for an rpc sucess/error result message.
type rpcResult struct {
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
// rpcError defines the structure for an rpc error.
type rpcError struct {
// A Number that indicates the error type that occurred. This MUST be an integer.
Code int64 `json:"code,omitempty"`
// A String providing a short description of the error. The message SHOULD be
// limited to a concise single sentence.
Message string `json:"message,omitempty"`
// A Primitive or Structured value that contains additional information about
// the error. This may be omitted. The value of this member is defined by the
// Server (e.g. detailed error information, nested errors etc.).
Data string `json:"data,omitempty"`
}
// JSON RPC 2.0 errors and messages.
var (
// Pre-defined errors and messages.
ParseError = &rpcError{Code: -32700, Message: "Parse error", Data: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."}
InvalidRequest = &rpcError{Code: -32600, Message: "Invalid request", Data: "The JSON sent is not a valid Request object."}
MethodNotFound = &rpcError{Code: -32601, Message: "Method not found", Data: "The method does not exist / is not available."}
InvalidParams = &rpcError{Code: -32602, Message: "Invalid params", Data: "Invalid method parameter(s)."}
InternalError = &rpcError{Code: -32603, Message: "Internal error", Data: "Internal JSON-RPC error."}
// -32000 to -32099 - Server error. Reserved for implementation-defined server-errors.
MissingRegistrationError = &rpcError{Code: -32000, Message: "Registration missing", Data: "User not logged in. Use the '/registrar' endpoint to obtain a security token."}
ChaincodeDeployError = &rpcError{Code: -32001, Message: "Deployment failure", Data: "Chaincode deployment has failed."}
ChaincodeInvokeError = &rpcError{Code: -32002, Message: "Invocation failure", Data: "Chaincode invocation has failed."}
ChaincodeQueryError = &rpcError{Code: -32003, Message: "Query failure", Data: "Chaincode query has failed."}
)
// SetOpenchainServer is a middleware function that sets the pointer to the
// underlying ServerOpenchain object and the undeflying Devops object.
func (s *ServerOpenchainREST) SetOpenchainServer(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
s.server = serverOpenchain
s.devops = serverDevops
next(rw, req)
}
// SetResponseType is a middleware function that sets the appropriate response
// headers. Currently, it is setting the "Content-Type" to "application/json" as
// well as the necessary headers in order to enable CORS for Swagger usage.
func (s *ServerOpenchainREST) SetResponseType(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
rw.Header().Set("Content-Type", "application/json")
// Enable CORS
rw.Header().Set("Access-Control-Allow-Origin", "*")
rw.Header().Set("Access-Control-Allow-Headers", "accept, content-type")
next(rw, req)
}
// getRESTFilePath is a helper function to retrieve the local storage directory
// of client login tokens.
func getRESTFilePath() string {
localStore := viper.GetString("peer.fileSystemPath")
if !strings.HasSuffix(localStore, "/") {
localStore = localStore + "/"
}
localStore = localStore + "client/"
return localStore
}
// isEnrollmentIDValid returns true if the given enrollmentID matches the valid
// pattern defined in the configuration.
func isEnrollmentIDValid(enrollmentID string) (bool, error) {
pattern := viper.GetString("rest.validPatterns.enrollmentID")
if pattern == "" {
return false, errors.New("Missing configuration key rest.validPatterns.enrollmentID")
}
return regexp.MatchString(pattern, enrollmentID)
}
// validateEnrollmentIDParameter checks whether the given enrollmentID is
// valid: if valid, returns true and does nothing; if not, writes the HTTP
// error response and returns false.
func validateEnrollmentIDParameter(rw web.ResponseWriter, enrollmentID string) bool {
validID, err := isEnrollmentIDValid(enrollmentID)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(rw).Encode(restResult{Error: err.Error()})
restLogger.Errorf("Error when validating enrollment ID: %s", err)
return false
}
if !validID {
rw.WriteHeader(http.StatusBadRequest)
json.NewEncoder(rw).Encode(restResult{Error: "Invalid enrollment ID parameter"})
restLogger.Errorf("Invalid enrollment ID parameter '%s'.\n", enrollmentID)
return false
}
return true
}
// Register confirms the enrollmentID and secret password of the client with the
// CA and stores the enrollment certificate and key in the Devops server.
func (s *ServerOpenchainREST) Register(rw web.ResponseWriter, req *web.Request) {
restLogger.Info("REST client login...")
encoder := json.NewEncoder(rw)
// Decode the incoming JSON payload
var loginSpec pb.Secret
err := jsonpb.Unmarshal(req.Body, &loginSpec)
// Check for proper JSON syntax
if err != nil {
// Client must supply payload
if err == io.EOF {
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: "Payload must contain object Secret with enrollId and enrollSecret fields."})
restLogger.Error("Error: Payload must contain object Secret with enrollId and enrollSecret fields.")
} else {
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: err.Error()})
restLogger.Errorf("Error: %s", err)
}
return
}
// Check that the enrollId and enrollSecret are not left blank.
if (loginSpec.EnrollId == "") || (loginSpec.EnrollSecret == "") {
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: "enrollId and enrollSecret may not be blank."})
restLogger.Error("Error: enrollId and enrollSecret may not be blank.")
return
}
if !validateEnrollmentIDParameter(rw, loginSpec.EnrollId) {
return
}
// Retrieve the REST data storage path
// Returns /var/hyperledger/production/client/
localStore := getRESTFilePath()
restLogger.Infof("Local data store for client loginToken: %s", localStore)
// If the user is already logged in, return
if _, err := os.Stat(localStore + "loginToken_" + loginSpec.EnrollId); err == nil {
rw.WriteHeader(http.StatusOK)
encoder.Encode(restResult{OK: fmt.Sprintf("User %s is already logged in.", loginSpec.EnrollId)})
restLogger.Infof("User '%s' is already logged in.\n", loginSpec.EnrollId)
return
}
// User is not logged in, proceed with login
restLogger.Infof("Logging in user '%s' on REST interface...\n", loginSpec.EnrollId)
loginResult, err := s.devops.Login(context.Background(), &loginSpec)
// Check if login is successful
if loginResult.Status == pb.Response_SUCCESS {
// If /var/hyperledger/production/client/ directory does not exist, create it
if _, err := os.Stat(localStore); err != nil {
if os.IsNotExist(err) {
// Directory does not exist, create it
if err := os.Mkdir(localStore, 0755); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: fmt.Sprintf("Fatal error -- %s", err)})
panic(fmt.Errorf("Fatal error when creating %s directory: %s\n", localStore, err))
}
} else {
// Unexpected error
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: fmt.Sprintf("Fatal error -- %s", err)})
panic(fmt.Errorf("Fatal error on os.Stat of %s directory: %s\n", localStore, err))
}
}
// Store client security context into a file
restLogger.Infof("Storing login token for user '%s'.\n", loginSpec.EnrollId)
err = ioutil.WriteFile(localStore+"loginToken_"+loginSpec.EnrollId, []byte(loginSpec.EnrollId), 0755)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: fmt.Sprintf("Fatal error -- %s", err)})
panic(fmt.Errorf("Fatal error when storing client login token: %s\n", err))
}
rw.WriteHeader(http.StatusOK)
encoder.Encode(restResult{OK: fmt.Sprintf("Login successful for user '%s'.", loginSpec.EnrollId)})
restLogger.Infof("Login successful for user '%s'.\n", loginSpec.EnrollId)
} else {
rw.WriteHeader(http.StatusUnauthorized)
encoder.Encode(restResult{Error: string(loginResult.Msg)})
restLogger.Errorf("Error on client login: %s", string(loginResult.Msg))
}
return
}
// GetEnrollmentID checks whether a given user has already registered with the
// Devops server.
func (s *ServerOpenchainREST) GetEnrollmentID(rw web.ResponseWriter, req *web.Request) {
// Parse out the user enrollment ID
enrollmentID := req.PathParams["id"]
if !validateEnrollmentIDParameter(rw, enrollmentID) {
return
}
// Retrieve the REST data storage path
// Returns /var/hyperledger/production/client/
localStore := getRESTFilePath()
encoder := json.NewEncoder(rw)
// If the user is already logged in, return OK. Otherwise return error.
if _, err := os.Stat(localStore + "loginToken_" + enrollmentID); err == nil {
rw.WriteHeader(http.StatusOK)
encoder.Encode(restResult{OK: fmt.Sprintf("User %s is already logged in.", enrollmentID)})
restLogger.Infof("User '%s' is already logged in.\n", enrollmentID)
} else {
rw.WriteHeader(http.StatusUnauthorized)
encoder.Encode(restResult{Error: fmt.Sprintf("User %s must log in.", enrollmentID)})
restLogger.Infof("User '%s' must log in.\n", enrollmentID)
}
}
// DeleteEnrollmentID removes the login token of the specified user from the
// Devops server. Once the login token is removed, the specified user will no
// longer be able to transact without logging in again. On the REST interface,
// this method may be used as a means of logging out an active client.
func (s *ServerOpenchainREST) DeleteEnrollmentID(rw web.ResponseWriter, req *web.Request) {
// Parse out the user enrollment ID
enrollmentID := req.PathParams["id"]
if !validateEnrollmentIDParameter(rw, enrollmentID) {
return
}
// Retrieve the REST data storage path
// Returns /var/hyperledger/production/client/
localStore := getRESTFilePath()
// Construct the path to the login token and to the directory containing the
// cert and key.
// /var/hyperledger/production/client/loginToken_username
loginTok := localStore + "loginToken_" + enrollmentID
// /var/hyperledger/production/crypto/client/username
cryptoDir := viper.GetString("peer.fileSystemPath") + "/crypto/client/" + enrollmentID
// Stat both paths to determine if the user is currently logged in
_, err1 := os.Stat(loginTok)
_, err2 := os.Stat(cryptoDir)
encoder := json.NewEncoder(rw)
// If the user is not logged in, nothing to delete. Return OK.
if os.IsNotExist(err1) && os.IsNotExist(err2) {
rw.WriteHeader(http.StatusOK)
encoder.Encode(restResult{OK: fmt.Sprintf("User %s is not logged in.", enrollmentID)})
restLogger.Infof("User '%s' is not logged in.\n", enrollmentID)
return
}
// The user is logged in, delete the user's login token
if err := os.RemoveAll(loginTok); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: fmt.Sprintf("Error trying to delete login token for user %s: %s", enrollmentID, err)})
restLogger.Errorf("Error: Error trying to delete login token for user %s: %s", enrollmentID, err)
return
}
// The user is logged in, delete the user's cert and key directory
if err := os.RemoveAll(cryptoDir); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: fmt.Sprintf("Error trying to delete login directory for user %s: %s", enrollmentID, err)})
restLogger.Errorf("Error: Error trying to delete login directory for user %s: %s", enrollmentID, err)
return
}
rw.WriteHeader(http.StatusOK)
encoder.Encode(restResult{OK: fmt.Sprintf("Deleted login token and directory for user %s.", enrollmentID)})
restLogger.Infof("Deleted login token and directory for user %s.\n", enrollmentID)
return
}
// GetEnrollmentCert retrieves the enrollment certificate for a given user.
func (s *ServerOpenchainREST) GetEnrollmentCert(rw web.ResponseWriter, req *web.Request) {
// Parse out the user enrollment ID
enrollmentID := req.PathParams["id"]
if !validateEnrollmentIDParameter(rw, enrollmentID) {
return
}
restLogger.Debugf("REST received enrollment certificate retrieval request for registrationID '%s'", enrollmentID)
encoder := json.NewEncoder(rw)
// If security is enabled, initialize the crypto client
if core.SecurityEnabled() {
if restLogger.IsEnabledFor(logging.DEBUG) {
restLogger.Debugf("Initializing secure client using context '%s'", enrollmentID)
}
// Initialize the security client
sec, err := crypto.InitClient(enrollmentID, nil)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: err.Error()})
restLogger.Errorf("Error: %s", err)
return
}
// Obtain the client CertificateHandler
handler, err := sec.GetEnrollmentCertificateHandler()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: err.Error()})
restLogger.Errorf("Error: %s", err)
return
}
// Certificate handler can not be hil
if handler == nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: "Error retrieving certificate handler."})
restLogger.Errorf("Error: Error retrieving certificate handler.")
return
}
// Obtain the DER encoded certificate
certDER := handler.GetCertificate()
// Confirm the retrieved enrollment certificate is not nil
if certDER == nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: "Enrollment certificate is nil."})
restLogger.Errorf("Error: Enrollment certificate is nil.")
return
}
// Confirm the retrieved enrollment certificate has non-zero length
if len(certDER) == 0 {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: "Enrollment certificate length is 0."})
restLogger.Errorf("Error: Enrollment certificate length is 0.")
return
}
// Transforms the DER encoded certificate to a PEM encoded certificate
certPEM := primitives.DERCertToPEM(certDER)
// As the enrollment certificate contains \n characters, url encode it before outputting
urlEncodedCert := url.QueryEscape(string(certPEM))
// Close the security client
crypto.CloseClient(sec)
rw.WriteHeader(http.StatusOK)
encoder.Encode(restResult{OK: urlEncodedCert})
restLogger.Debugf("Successfully retrieved enrollment certificate for secure context '%s'", enrollmentID)
} else {
// Security must be enabled to request enrollment certificates
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: "Security functionality must be enabled before requesting client certificates."})
restLogger.Errorf("Error: Security functionality must be enabled before requesting client certificates.")
return
}
}
// GetTransactionCert retrieves the transaction certificate(s) for a given user.
func (s *ServerOpenchainREST) GetTransactionCert(rw web.ResponseWriter, req *web.Request) {
// Parse out the user enrollment ID
enrollmentID := req.PathParams["id"]
if !validateEnrollmentIDParameter(rw, enrollmentID) {
return
}
restLogger.Debugf("REST received transaction certificate retrieval request for registrationID '%s'", enrollmentID)
encoder := json.NewEncoder(rw)
// Parse out the count query parameter
req.ParseForm()
queryParams := req.Form
// The default number of TCerts to retrieve is 1
var count uint32 = 1
// If the query parameter is present, examine the supplied value
if queryParams["count"] != nil {
// Convert string to uint. The parse function return the widest type (uint64)
// Setting base to 32 allows you to subsequently cast the value to uint32
qParam, err := strconv.ParseUint(queryParams["count"][0], 10, 32)
// Check for count parameter being a non-negative integer
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: "Count query parameter must be a non-negative integer."})
restLogger.Errorf("Error: Count query parameter must be a non-negative integer.")
return
}
// If the query parameter is within the allowed range, record it
if qParam > 0 && qParam <= 500 {
count = uint32(qParam)
}
// Limit the number of TCerts retrieved to 500
if qParam > 500 {
count = 500
}
}
// If security is enabled, initialize the crypto client
if core.SecurityEnabled() {
if restLogger.IsEnabledFor(logging.DEBUG) {
restLogger.Debugf("Initializing secure client using context '%s'", enrollmentID)
}
// Initialize the security client
sec, err := crypto.InitClient(enrollmentID, nil)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: err.Error()})
restLogger.Errorf("Error: %s", err)
return
}
// Obtain the client CertificateHandler
// TODO - Replace empty attributes map
attributes := []string{}
handler, err := sec.GetTCertificateHandlerNext(attributes...)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: err.Error()})
restLogger.Errorf("Error: %s", err)
return
}
// Certificate handler can not be hil
if handler == nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: "Error retrieving certificate handler."})
restLogger.Errorf("Error: Error retrieving certificate handler.")
return
}
// Retrieve the required number of TCerts
tcertArray := make([]string, count)
var i uint32
for i = 0; i < count; i++ {
// Obtain the DER encoded certificate
certDER := handler.GetCertificate()
// Confirm the retrieved enrollment certificate is not nil
if certDER == nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: "Transaction certificate is nil."})
restLogger.Errorf("Error: Transaction certificate is nil.")
return
}
// Confirm the retrieved enrollment certificate has non-zero length
if len(certDER) == 0 {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: "Transaction certificate length is 0."})
restLogger.Errorf("Error: Transaction certificate length is 0.")
return
}
// Transforms the DER encoded certificate to a PEM encoded certificate
certPEM := primitives.DERCertToPEM(certDER)
// As the transaction certificate contains \n characters, url encode it before outputting
urlEncodedCert := url.QueryEscape(string(certPEM))
// Add the urlEncodedCert transaction certificate to the certificate array
tcertArray[i] = urlEncodedCert
}
// Close the security client
crypto.CloseClient(sec)
rw.WriteHeader(http.StatusOK)
encoder.Encode(tcertsResult{OK: tcertArray})
restLogger.Debugf("Successfully retrieved transaction certificates for secure context '%s'", enrollmentID)
} else {
// Security must be enabled to request transaction certificates
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: "Security functionality must be enabled before requesting client certificates."})
restLogger.Errorf("Error: Security functionality must be enabled before requesting client certificates.")
return
}
}
// GetBlockchainInfo returns information about the blockchain ledger such as
// height, current block hash, and previous block hash.
func (s *ServerOpenchainREST) GetBlockchainInfo(rw web.ResponseWriter, req *web.Request) {
info, err := s.server.GetBlockchainInfo(context.Background(), &empty.Empty{})
encoder := json.NewEncoder(rw)
// Check for error
if err != nil {
// Failure
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: err.Error()})
} else {
// Success
rw.WriteHeader(http.StatusOK)
encoder.Encode(info)
}
}
// GetBlockByNumber returns the data contained within a specific block in the
// blockchain. The genesis block is block zero.
func (s *ServerOpenchainREST) GetBlockByNumber(rw web.ResponseWriter, req *web.Request) {
// Parse out the Block id
blockNumber, err := strconv.ParseUint(req.PathParams["id"], 10, 64)
encoder := json.NewEncoder(rw)
// Check for proper Block id syntax
if err != nil {
// Failure
rw.WriteHeader(http.StatusBadRequest)
encoder.Encode(restResult{Error: "Block id must be an integer (uint64)."})
return
}
// Retrieve Block from blockchain
block, err := s.server.GetBlockByNumber(context.Background(), &pb.BlockNumber{Number: blockNumber})
if (err == ErrNotFound) || (err == nil && block == nil) {
rw.WriteHeader(http.StatusNotFound)
encoder.Encode(restResult{Error: ErrNotFound.Error()})
return
}
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: err.Error()})
return
}
// Success
rw.WriteHeader(http.StatusOK)
encoder.Encode(block)
}
// GetTransactionByID returns a transaction matching the specified ID
func (s *ServerOpenchainREST) GetTransactionByID(rw web.ResponseWriter, req *web.Request) {
// Parse out the transaction ID
txID := req.PathParams["id"]
// Retrieve the transaction matching the ID
tx, err := s.server.GetTransactionByID(context.Background(), txID)
encoder := json.NewEncoder(rw)
// Check for Error
if err != nil {
switch err {
case ErrNotFound:
rw.WriteHeader(http.StatusNotFound)
encoder.Encode(restResult{Error: fmt.Sprintf("Transaction %s is not found.", txID)})
default:
rw.WriteHeader(http.StatusInternalServerError)
encoder.Encode(restResult{Error: fmt.Sprintf("Error retrieving transaction %s: %s.", txID, err)})
restLogger.Errorf("Error retrieving transaction %s: %s", txID, err)
}
} else {
// Return existing transaction
rw.WriteHeader(http.StatusOK)
encoder.Encode(tx)
restLogger.Infof("Successfully retrieved transaction: %s", txID)
}
}
// Deploy first builds the chaincode package and subsequently deploys it to the
// blockchain.
//
// Deprecated: use the /chaincode endpoint instead (routes to ProcessChaincode)
func (s *ServerOpenchainREST) Deploy(rw web.ResponseWriter, req *web.Request) {
restLogger.Info("REST deploying chaincode...")
// This endpoint has been deprecated. Add a warning header to all responses.
rw.Header().Set("Warning", "299 - /devops/deploy endpoint has been deprecated. Use /chaincode endpoint instead.")
// Decode the incoming JSON payload
var spec pb.ChaincodeSpec
err := jsonpb.Unmarshal(req.Body, &spec)
// Check for proper JSON syntax
if err != nil {
// Unmarshall returns a " character around unrecognized fields in the case
// of a schema validation failure. These must be replaced with a ' character.
// Otherwise, the returned JSON is invalid.
errVal := strings.Replace(err.Error(), "\"", "'", -1)
// Client must supply payload
if err == io.EOF {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Payload must contain a ChaincodeSpec.\"}")
restLogger.Error("{\"Error\": \"Payload must contain a ChaincodeSpec.\"}")
} else {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"%s\"}", errVal)
restLogger.Errorf("{\"Error\": \"%s\"}", errVal)
}
return
}
// Check that the ChaincodeID is not nil.
if spec.ChaincodeID == nil {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Payload must contain a ChaincodeID.\"}")
restLogger.Error("{\"Error\": \"Payload must contain a ChaincodeID.\"}")
return
}
// If the peer is running in development mode, confirm that the Chaincode name
// is not left blank. If the peer is running in production mode, confirm that
// the Chaincode path is not left blank. This is necessary as in development
// mode, the chaincode is identified by name not by path during the deploy
// process.
if viper.GetString("chaincode.mode") == chaincode.DevModeUserRunsChaincode {
// Check that the Chaincode name is not blank.
if spec.ChaincodeID.Name == "" {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Chaincode name may not be blank in development mode.\"}")
restLogger.Error("{\"Error\": \"Chaincode name may not be blank in development mode.\"}")
return
}
} else {
// Check that the Chaincode path is not left blank.
if spec.ChaincodeID.Path == "" {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Chaincode path may not be blank.\"}")
restLogger.Error("{\"Error\": \"Chaincode path may not be blank.\"}")
return
}
}
// Check that the CtorMsg is not left blank.
if (spec.CtorMsg == nil) || (len(spec.CtorMsg.Args) == 0) {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Payload must contain a CtorMsg with a Chaincode function name.\"}")
restLogger.Error("{\"Error\": \"Payload must contain a CtorMsg with a Chaincode function name.\"}")
return
}
// If security is enabled, add client login token
if core.SecurityEnabled() {
chaincodeUsr := spec.SecureContext
if chaincodeUsr == "" {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Must supply username for chaincode when security is enabled.\"}")
restLogger.Error("{\"Error\": \"Must supply username for chaincode when security is enabled.\"}")
return
}
// Retrieve the REST data storage path
// Returns /var/hyperledger/production/client/
localStore := getRESTFilePath()
// Check if the user is logged in before sending transaction
if _, err := os.Stat(localStore + "loginToken_" + chaincodeUsr); err == nil {
restLogger.Infof("Local user '%s' is already logged in. Retrieving login token.\n", chaincodeUsr)
// Read in the login token
token, err := ioutil.ReadFile(localStore + "loginToken_" + chaincodeUsr)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(rw, "{\"Error\": \"Fatal error -- %s\"}", err)
panic(fmt.Errorf("Fatal error when reading client login token: %s\n", err))
}
// Add the login token to the chaincodeSpec
spec.SecureContext = string(token)
// If privacy is enabled, mark chaincode as confidential
if viper.GetBool("security.privacy") {
spec.ConfidentialityLevel = pb.ConfidentialityLevel_CONFIDENTIAL
}
} else {
// Check if the token is not there and fail
if os.IsNotExist(err) {
rw.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(rw, "{\"Error\": \"User not logged in. Use the '/registrar' endpoint to obtain a security token.\"}")
restLogger.Error("{\"Error\": \"User not logged in. Use the '/registrar' endpoint to obtain a security token.\"}")
return
}
// Unexpected error
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(rw, "{\"Error\": \"Fatal error -- %s\"}", err)
panic(fmt.Errorf("Fatal error when checking for client login token: %s\n", err))
}
}
// Deploy the ChaincodeSpec
chaincodeDeploymentSpec, err := s.devops.Deploy(context.Background(), &spec)
if err != nil {
// Replace " characters with '
errVal := strings.Replace(err.Error(), "\"", "'", -1)
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"%s\"}", errVal)
restLogger.Errorf("{\"Error\": \"Deploying Chaincode -- %s\"}", errVal)
return
}
// Clients will need the chaincode name in order to invoke or query it
chainID := chaincodeDeploymentSpec.ChaincodeSpec.ChaincodeID.Name
rw.WriteHeader(http.StatusOK)
fmt.Fprintf(rw, "{\"OK\": \"Successfully deployed chainCode.\",\"message\":\""+chainID+"\"}")
restLogger.Infof("Successfully deployed chainCode: %s \n", chainID)
}
// Invoke executes a specified function within a target Chaincode.
//
// Deprecated: use the /chaincode endpoint instead (routes to ProcessChaincode)
func (s *ServerOpenchainREST) Invoke(rw web.ResponseWriter, req *web.Request) {
restLogger.Info("REST invoking chaincode...")
// This endpoint has been deprecated. Add a warning header to all responses.
rw.Header().Set("Warning", "299 - /devops/invoke endpoint has been deprecated. Use /chaincode endpoint instead.")
// Decode the incoming JSON payload
var spec pb.ChaincodeInvocationSpec
err := jsonpb.Unmarshal(req.Body, &spec)
// Check for proper JSON syntax
if err != nil {
// Unmarshall returns a " character around unrecognized fields in the case
// of a schema validation failure. These must be replaced with a ' character.
// Otherwise, the returned JSON is invalid.
errVal := strings.Replace(err.Error(), "\"", "'", -1)
// Client must supply payload
if err == io.EOF {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Payload must contain a ChaincodeInvocationSpec.\"}")
restLogger.Error("{\"Error\": \"Payload must contain a ChaincodeInvocationSpec.\"}")
} else {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"%s\"}", errVal)
restLogger.Errorf("{\"Error\": \"%s\"}", errVal)
}
return
}
// Check that the ChaincodeSpec is not left blank.
if spec.ChaincodeSpec == nil {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Payload must contain a ChaincodeSpec.\"}")
restLogger.Error("{\"Error\": \"Payload must contain a ChaincodeSpec.\"}")
return
}
// Check that the ChaincodeID is not left blank.
if spec.ChaincodeSpec.ChaincodeID == nil {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Payload must contain a ChaincodeID.\"}")
restLogger.Error("{\"Error\": \"Payload must contain a ChaincodeID.\"}")
return
}
// Check that the Chaincode name is not blank.
if spec.ChaincodeSpec.ChaincodeID.Name == "" {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Chaincode name may not be blank.\"}")
restLogger.Error("{\"Error\": \"Chaincode name may not be blank.\"}")
return
}
// Check that the CtorMsg is not left blank.
if (spec.ChaincodeSpec.CtorMsg == nil) || (len(spec.ChaincodeSpec.CtorMsg.Args) == 0) {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Payload must contain a CtorMsg with a Chaincode function name.\"}")
restLogger.Error("{\"Error\": \"Payload must contain a CtorMsg with a Chaincode function name.\"}")
return
}
// If security is enabled, add client login token
if core.SecurityEnabled() {
chaincodeUsr := spec.ChaincodeSpec.SecureContext
if chaincodeUsr == "" {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"Must supply username for chaincode when security is enabled.\"}")
restLogger.Error("{\"Error\": \"Must supply username for chaincode when security is enabled.\"}")
return
}
// Retrieve the REST data storage path
// Returns /var/hyperledger/production/client/
localStore := getRESTFilePath()
// Check if the user is logged in before sending transaction
if _, err := os.Stat(localStore + "loginToken_" + chaincodeUsr); err == nil {
restLogger.Infof("Local user '%s' is already logged in. Retrieving login token.\n", chaincodeUsr)
// Read in the login token
token, err := ioutil.ReadFile(localStore + "loginToken_" + chaincodeUsr)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(rw, "{\"Error\": \"Fatal error -- %s\"}", err)
panic(fmt.Errorf("Fatal error when reading client login token: %s\n", err))
}
// Add the login token to the chaincodeSpec
spec.ChaincodeSpec.SecureContext = string(token)
// If privacy is enabled, mark chaincode as confidential
if viper.GetBool("security.privacy") {
spec.ChaincodeSpec.ConfidentialityLevel = pb.ConfidentialityLevel_CONFIDENTIAL
}
} else {
// Check if the token is not there and fail
if os.IsNotExist(err) {
rw.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(rw, "{\"Error\": \"User not logged in. Use the '/registrar' endpoint to obtain a security token.\"}")
restLogger.Error("{\"Error\": \"User not logged in. Use the '/registrar' endpoint to obtain a security token.\"}")
return
}
// Unexpected error
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(rw, "{\"Error\": \"Fatal error -- %s\"}", err)
panic(fmt.Errorf("Fatal error when checking for client login token: %s\n", err))
}
}
// Invoke the chainCode
resp, err := s.devops.Invoke(context.Background(), &spec)
if err != nil {
// Replace " characters with '
errVal := strings.Replace(err.Error(), "\"", "'", -1)
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"%s\"}", errVal)
restLogger.Errorf("{\"Error\": \"Invoking Chaincode -- %s\"}", errVal)
return