-
Notifications
You must be signed in to change notification settings - Fork 0
/
smartcontractgw.go
1382 lines (1250 loc) · 49.3 KB
/
smartcontractgw.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 2019 SEE CONTRIBUTORS
// 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 maidenlanedcontracts
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/freight-trust/zeroxyz/internal/maidenlanedbind"
"github.com/freight-trust/zeroxyz/internal/maidenlanedopenapi"
"github.com/freight-trust/zeroxyz/internal/maidenlanedtx"
"github.com/freight-trust/zeroxyz/internal/maidenlanedutils"
"github.com/go-openapi/spec"
"github.com/julienschmidt/httprouter"
"github.com/spf13/cobra"
"github.com/ethereum/go-ethereum/common/compiler"
"github.com/freight-trust/zeroxyz/internal/maidenlanedauth"
"github.com/freight-trust/zeroxyz/internal/maidenlanederrors"
"github.com/freight-trust/zeroxyz/internal/maidenlanedeth"
"github.com/freight-trust/zeroxyz/internal/maidenlanedevents"
"github.com/freight-trust/zeroxyz/internal/maidenlanedmessages"
"github.com/mholt/archiver"
log "github.com/sirupsen/logrus"
)
const (
maxFormParsingMemory = 32 << 20 // 32 MB
errEventSupportMissing = "Event support is not configured on this gateway"
remoteRegistryContextKey = "isRemoteRegistry"
)
// SmartContractGateway provides gateway functions for OpenAPI 2.0 processing of Solidity contracts
type SmartContractGateway interface {
PreDeploy(msg *maidenlanedmessages.DeployContract) error
PostDeploy(msg *maidenlanedmessages.TransactionReceipt) error
AddRoutes(router *httprouter.Router)
Shutdown()
}
type smartContractGatewayInt interface {
SmartContractGateway
resolveContractAddr(registeredName string) (string, error)
loadDeployMsgForInstance(addrHexNo0x string) (*maidenlanedmessages.DeployContract, *contractInfo, error)
loadDeployMsgByID(abi string) (*maidenlanedmessages.DeployContract, *abiInfo, error)
checkNameAvailable(name string, isRemote bool) error
}
// SmartContractGatewayConf configuration
type SmartContractGatewayConf struct {
maidenlanedevents.SubscriptionManagerConf
StoragePath string `json:"storagePath"`
BaseURL string `json:"baseURL"`
RemoteRegistry RemoteRegistryConf `json:"registry,omitempty"` // JSON only config - no commandline
}
// CobraInitContractGateway standard naming for contract gateway command params
func CobraInitContractGateway(cmd *cobra.Command, conf *SmartContractGatewayConf) {
cmd.Flags().StringVarP(&conf.StoragePath, "openapi-path", "I", "", "Path containing ABI + generated OpenAPI/Swagger 2.0 contact definitions")
cmd.Flags().StringVarP(&conf.BaseURL, "openapi-baseurl", "U", "", "Base URL for generated OpenAPI/Swagger 2.0 contact definitions")
maidenlanedevents.CobraInitSubscriptionManager(cmd, &conf.SubscriptionManagerConf)
}
func (g *smartContractGW) withEventsAuth(handler httprouter.Handle) httprouter.Handle {
return func(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
err := maidenlanedauth.AuthEventStreams(req.Context())
if err != nil {
log.Errorf("Unauthorized: %s", err)
g.gatewayErrReply(res, req, maidenlanederrors.Errorf(maidenlanederrors.Unauthorized), 401)
return
}
handler(res, req, params)
}
}
func (g *smartContractGW) AddRoutes(router *httprouter.Router) {
g.r2e.addRoutes(router)
router.GET("/contracts", g.listContractsOrABIs)
router.GET("/contracts/:address", g.getContractOrABI)
router.POST("/abis", g.addABI)
router.GET("/abis", g.listContractsOrABIs)
router.GET("/abis/:abi", g.getContractOrABI)
router.POST("/abis/:abi/:address", g.registerContract)
router.GET("/instances/:instance_lookup", g.getRemoteRegistrySwaggerOrABI)
router.GET("/i/:instance_lookup", g.getRemoteRegistrySwaggerOrABI)
router.GET("/gateways/:gateway_lookup", g.getRemoteRegistrySwaggerOrABI)
router.GET("/g/:gateway_lookup", g.getRemoteRegistrySwaggerOrABI)
router.POST(maidenlanedevents.StreamPathPrefix, g.withEventsAuth(g.createStream))
router.PATCH(maidenlanedevents.StreamPathPrefix+"/:id", g.withEventsAuth(g.updateStream))
router.GET(maidenlanedevents.StreamPathPrefix, g.withEventsAuth(g.listStreamsOrSubs))
router.GET(maidenlanedevents.SubPathPrefix, g.withEventsAuth(g.listStreamsOrSubs))
router.GET(maidenlanedevents.StreamPathPrefix+"/:id", g.withEventsAuth(g.getStreamOrSub))
router.GET(maidenlanedevents.SubPathPrefix+"/:id", g.withEventsAuth(g.getStreamOrSub))
router.DELETE(maidenlanedevents.StreamPathPrefix+"/:id", g.withEventsAuth(g.deleteStreamOrSub))
router.DELETE(maidenlanedevents.SubPathPrefix+"/:id", g.withEventsAuth(g.deleteStreamOrSub))
router.POST(maidenlanedevents.SubPathPrefix+"/:id/reset", g.withEventsAuth(g.resetSub))
router.POST(maidenlanedevents.StreamPathPrefix+"/:id/suspend", g.withEventsAuth(g.suspendOrResumeStream))
router.POST(maidenlanedevents.StreamPathPrefix+"/:id/resume", g.withEventsAuth(g.suspendOrResumeStream))
}
// NewSmartContractGateway construtor
func NewSmartContractGateway(conf *SmartContractGatewayConf, txnConf *maidenlanedtx.TxnProcessorConf, rpc maidenlanedeth.RPCClient, processor maidenlanedtx.TxnProcessor, asyncDispatcher REST2EthAsyncDispatcher) (SmartContractGateway, error) {
var baseURL *url.URL
var err error
if conf.BaseURL != "" {
if baseURL, err = url.Parse(conf.BaseURL); err != nil {
log.Warnf("Unable to parse smart contract gateway base URL '%s': %s", conf.BaseURL, err)
}
}
if baseURL == nil {
baseURL, _ = url.Parse("http://localhost:8080")
}
log.Infof("OpenAPI Smart Contract Gateway configured with base URL '%s'", baseURL.String())
gw := &smartContractGW{
conf: conf,
rr: NewRemoteRegistry(&conf.RemoteRegistry),
contractIndex: make(map[string]maidenlanedmessages.TimeSortable),
contractRegistrations: make(map[string]*contractInfo),
abiIndex: make(map[string]maidenlanedmessages.TimeSortable),
baseSwaggerConf: &maidenlanedopenapi.ABI2SwaggerConf{
ExternalHost: baseURL.Host,
ExternalRootPath: baseURL.Path,
ExternalSchemes: []string{baseURL.Scheme},
OrionPrivateAPI: txnConf.OrionPrivateAPIS,
BasicAuth: true,
},
}
if err = gw.rr.init(); err != nil {
return nil, err
}
syncDispatcher := newSyncDispatcher(processor)
if conf.EventLevelDBPath != "" {
gw.sm = maidenlanedevents.NewSubscriptionManager(&conf.SubscriptionManagerConf, rpc)
err = gw.sm.Init()
if err != nil {
return nil, maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayEventManagerInitFailed, err)
}
}
gw.r2e = newREST2eth(gw, rpc, gw.sm, gw.rr, processor, asyncDispatcher, syncDispatcher)
gw.buildIndex()
return gw, nil
}
type smartContractGW struct {
conf *SmartContractGatewayConf
sm maidenlanedevents.SubscriptionManager
rr RemoteRegistry
r2e *rest2eth
contractIndex map[string]maidenlanedmessages.TimeSortable
contractRegistrations map[string]*contractInfo
idxLock sync.Mutex
abiIndex map[string]maidenlanedmessages.TimeSortable
baseSwaggerConf *maidenlanedopenapi.ABI2SwaggerConf
}
// contractInfo is the minimal data structure we keep in memory, indexed by address
// ONLY used for local registry. Remote registry handles its own storage/caching
type contractInfo struct {
maidenlanedmessages.TimeSorted
Address string `json:"address"`
Path string `json:"path"`
ABI string `json:"abi"`
SwaggerURL string `json:"openapi"`
RegisteredAs string `json:"registeredAs"`
}
// abiInfo is the minimal data structure we keep in memory, indexed by our own UUID
type abiInfo struct {
maidenlanedmessages.TimeSorted
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Path string `json:"path"`
Deployable bool `json:"deployable"`
SwaggerURL string `json:"openapi"`
CompilerVersion string `json:"compilerVersion"`
}
// remoteContractInfo is the ABI raw data back out of the REST API gateway with bytecode
type remoteContractInfo struct {
ID string `json:"id"`
Address string `json:"address,omitempty"`
ABI maidenlanedbind.ABIMarshaling `json:"abi"`
}
func (i *contractInfo) GetID() string {
return i.Address
}
func (i *abiInfo) GetID() string {
return i.ID
}
func (g *smartContractGW) storeNewContractInfo(addrHexNo0x, abiID, pathName, registerAs string) (*contractInfo, error) {
contractInfo := &contractInfo{
Address: addrHexNo0x,
ABI: abiID,
Path: "/contracts/" + pathName,
SwaggerURL: g.conf.BaseURL + "/contracts/" + pathName + "?swagger",
RegisteredAs: registerAs,
TimeSorted: maidenlanedmessages.TimeSorted{
CreatedISO8601: time.Now().UTC().Format(time.RFC3339),
},
}
if err := g.storeContractInfo(contractInfo); err != nil {
return nil, err
}
return contractInfo, nil
}
func isRemote(msg maidenlanedmessages.CommonHeaders) bool {
ctxMap := msg.Context
if isRemoteGeneric, ok := ctxMap[remoteRegistryContextKey]; ok {
if isRemote, ok := isRemoteGeneric.(bool); ok {
return isRemote
}
}
return false
}
// PostDeploy callback processes the transaction receipt and generates the Swagger
func (g *smartContractGW) PostDeploy(msg *maidenlanedmessages.TransactionReceipt) error {
requestID := msg.Headers.ReqID
// We use the ethereum address of the contract, without the 0x prefix, and
// all in lower case, as the name of the file and the path root of the Swagger operations
if msg.ContractAddress == nil {
return maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayPostDeployMissingAddress, requestID)
}
addrHexNo0x := strings.ToLower(msg.ContractAddress.Hex()[2:])
// Generate and store the swagger
basePath := "/contracts/"
isRemote := isRemote(msg.Headers.CommonHeaders)
if isRemote {
basePath = "/instances/"
}
registeredName := msg.RegisterAs
if registeredName == "" {
registeredName = addrHexNo0x
}
if msg.Headers.MsgType == maidenlanedmessages.MsgTypeTransactionSuccess {
msg.ContractSwagger = g.conf.BaseURL + basePath + registeredName + "?openapi"
msg.ContractUI = g.conf.BaseURL + basePath + registeredName + "?ui"
var err error
if isRemote {
if msg.RegisterAs != "" {
err = g.rr.registerInstance(msg.RegisterAs, "0x"+addrHexNo0x)
}
} else {
_, err = g.storeNewContractInfo(addrHexNo0x, requestID, registeredName, msg.RegisterAs)
}
return err
}
return nil
}
func (g *smartContractGW) swaggerForRemoteRegistry(swaggerGen *maidenlanedopenapi.ABI2Swagger, apiName, addr string, factoryOnly bool, abi *maidenlanedbind.RuntimeABI, devdoc, path string) *spec.Swagger {
var swagger *spec.Swagger
if addr == "" {
swagger = swaggerGen.Gen4Factory(path, apiName, factoryOnly, true, &abi.ABI, devdoc)
} else {
swagger = swaggerGen.Gen4Instance(path, apiName, &abi.ABI, devdoc)
}
return swagger
}
func (g *smartContractGW) swaggerForABI(swaggerGen *maidenlanedopenapi.ABI2Swagger, abiID, apiName string, factoryOnly bool, abi *maidenlanedbind.RuntimeABI, devdoc string, addrHexNo0x, registerAs string) *spec.Swagger {
// Ensure we have a contract name in all cases, as the Swagger
// won't be valid without a title
if apiName == "" {
apiName = abiID
}
var swagger *spec.Swagger
if addrHexNo0x != "" {
pathSuffix := url.QueryEscape(registerAs)
if pathSuffix == "" {
pathSuffix = addrHexNo0x
}
swagger = swaggerGen.Gen4Instance("/contracts/"+pathSuffix, apiName, &abi.ABI, devdoc)
if registerAs != "" {
swagger.Info.AddExtension("x-maidenlane-registered-name", pathSuffix)
}
} else {
swagger = swaggerGen.Gen4Factory("/abis/"+abiID, apiName, factoryOnly, false, &abi.ABI, devdoc)
}
// Add in an extension to the Swagger that points back at the filename of the deployment info
if abiID != "" {
swagger.Info.AddExtension("x-maidenlane-deployment-id", abiID)
}
return swagger
}
func (g *smartContractGW) storeContractInfo(info *contractInfo) error {
if err := g.addToContractIndex(info); err != nil {
return err
}
infoFile := path.Join(g.conf.StoragePath, "contract_"+info.Address+".instance.json")
instanceBytes, _ := json.MarshalIndent(info, "", " ")
log.Infof("%s: Storing contract instance JSON to '%s'", info.ABI, infoFile)
if err := ioutil.WriteFile(infoFile, instanceBytes, 0664); err != nil {
return maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayLocalStoreContractSave, err)
}
return nil
}
func (g *smartContractGW) resolveContractAddr(registeredName string) (string, error) {
nameUnescaped, _ := url.QueryUnescape(registeredName)
info, exists := g.contractRegistrations[nameUnescaped]
if !exists {
return "", maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayLocalStoreContractLoad, registeredName)
}
log.Infof("%s -> 0x%s", registeredName, info.Address)
return info.Address, nil
}
func (g *smartContractGW) loadDeployMsgForInstance(addrHex string) (*maidenlanedmessages.DeployContract, *contractInfo, error) {
addrHexNo0x := strings.TrimPrefix(strings.ToLower(addrHex), "0x")
info, exists := g.contractIndex[addrHexNo0x]
if !exists {
return nil, nil, maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayLocalStoreContractNotFound, addrHexNo0x)
}
deployMsg, _, err := g.loadDeployMsgByID(info.(*contractInfo).ABI)
return deployMsg, info.(*contractInfo), err
}
func (g *smartContractGW) loadDeployMsgByID(id string) (*maidenlanedmessages.DeployContract, *abiInfo, error) {
var info *abiInfo
var msg *maidenlanedmessages.DeployContract
ts, exists := g.abiIndex[id]
if !exists {
log.Infof("ABI with ID %s not found locally", id)
return nil, nil, maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayLocalStoreABINotFound, id)
}
deployFile := path.Join(g.conf.StoragePath, "abi_"+id+".deploy.json")
deployBytes, err := ioutil.ReadFile(deployFile)
if err != nil {
return nil, nil, maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayLocalStoreABILoad, id, err)
}
msg = &maidenlanedmessages.DeployContract{}
if err = json.Unmarshal(deployBytes, msg); err != nil {
return nil, nil, maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayLocalStoreABIParse, id, err)
}
info = ts.(*abiInfo)
return msg, info, nil
}
// PreDeploy
// - compiles the Solidity (if not precomplied),
// - puts the code into the message to avoid a recompile later
// - stores the ABI under the MsgID (can later be bound to an address)
// *** caller is responsible for ensuring unique Header.ID ***
func (g *smartContractGW) PreDeploy(msg *maidenlanedmessages.DeployContract) (err error) {
solidity := msg.Solidity
var compiled *maidenlanedeth.CompiledSolidity
if solidity != "" {
if compiled, err = maidenlanedeth.CompileContract(solidity, msg.ContractName, msg.CompilerVersion, msg.EVMVersion); err != nil {
return err
}
}
if !isRemote(msg.Headers.CommonHeaders) {
_, err = g.storeDeployableABI(msg, compiled)
}
return err
}
func (g *smartContractGW) storeDeployableABI(msg *maidenlanedmessages.DeployContract, compiled *maidenlanedeth.CompiledSolidity) (*abiInfo, error) {
if compiled != nil {
msg.Compiled = compiled.Compiled
msg.ABI = compiled.ABI
msg.DevDoc = compiled.DevDoc
msg.ContractName = compiled.ContractName
msg.CompilerVersion = compiled.ContractInfo.CompilerVersion
} else if msg.ABI == nil {
return nil, maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayLocalStoreMissingABI)
}
runtimeABI, err := maidenlanedbind.ABIMarshalingToABIRuntime(msg.ABI)
if err != nil {
return nil, maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayInvalidABI, err)
}
requestID := msg.Headers.ID
// We store the swagger in a generic format that can be used to deploy
// additional instances, or generically call other instances
// Generate and store the swagger
swagger := g.swaggerForABI(maidenlanedopenapi.NewABI2Swagger(g.baseSwaggerConf), requestID, msg.ContractName, false, runtimeABI, msg.DevDoc, "", "")
msg.Description = swagger.Info.Description // Swagger generation parses the devdoc
info := g.addToABIIndex(requestID, msg, time.Now().UTC())
g.writeAbiInfo(requestID, msg)
// We remove the solidity payload from the message, as we've consumed
// it by compiling and there is no need to serialize it again.
// The messages should contain compiled bytes at this
msg.Solidity = ""
return info, nil
}
func (g *smartContractGW) gatewayErrReply(res http.ResponseWriter, req *http.Request, err error, status int) {
log.Errorf("<-- %s %s [%d]: %s", req.Method, req.URL, status, err)
reply, _ := json.Marshal(&restErrMsg{Message: err.Error()})
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(status)
res.Write(reply)
return
}
func (g *smartContractGW) writeAbiInfo(requestID string, msg *maidenlanedmessages.DeployContract) error {
// We store all the details from our compile, or the user-supplied
// details, in a file under the message ID.
infoFile := path.Join(g.conf.StoragePath, "abi_"+requestID+".deploy.json")
infoBytes, _ := json.MarshalIndent(msg, "", " ")
log.Infof("%s: Stashing deployment details to '%s'", requestID, infoFile)
if err := ioutil.WriteFile(infoFile, infoBytes, 0664); err != nil {
return maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayLocalStoreContractSavePostDeploy, requestID, err)
}
return nil
}
func (g *smartContractGW) buildIndex() {
log.Infof("Building installed smart contract index")
legacyContractMatcher, _ := regexp.Compile("^contract_([0-9a-z]{40})\\.swagger\\.json$")
instanceMatcher, _ := regexp.Compile("^contract_([0-9a-z]{40})\\.instance\\.json$")
abiMatcher, _ := regexp.Compile("^abi_([0-9a-z-]+)\\.deploy.json$")
files, err := ioutil.ReadDir(g.conf.StoragePath)
if err != nil {
log.Errorf("Failed to read directory %s: %s", g.conf.StoragePath, err)
return
}
for _, file := range files {
fileName := file.Name()
legacyContractGroups := legacyContractMatcher.FindStringSubmatch(fileName)
abiGroups := abiMatcher.FindStringSubmatch(fileName)
instanceGroups := instanceMatcher.FindStringSubmatch(fileName)
if legacyContractGroups != nil {
g.migrateLegacyContract(legacyContractGroups[1], path.Join(g.conf.StoragePath, fileName), file.ModTime())
} else if instanceGroups != nil {
g.addFileToContractIndex(instanceGroups[1], path.Join(g.conf.StoragePath, fileName))
} else if abiGroups != nil {
g.addFileToABIIndex(abiGroups[1], path.Join(g.conf.StoragePath, fileName), file.ModTime())
}
}
log.Infof("Smart contract index built. %d entries", len(g.contractIndex))
}
func (g *smartContractGW) migrateLegacyContract(address, fileName string, createdTime time.Time) {
swaggerFile, err := os.OpenFile(fileName, os.O_RDONLY, 0)
if err != nil {
log.Errorf("Failed to load Swagger file %s: %s", fileName, err)
return
}
defer swaggerFile.Close()
var swagger spec.Swagger
err = json.NewDecoder(bufio.NewReader(swaggerFile)).Decode(&swagger)
if err != nil {
log.Errorf("Failed to parse Swagger file %s: %s", fileName, err)
return
}
if swagger.Info == nil {
log.Errorf("Failed to migrate invalid Swagger file %s", fileName)
return
}
var registeredAs string
if ext, exists := swagger.Info.Extensions["x-maidenlane-registered-name"]; exists {
registeredAs = ext.(string)
}
if ext, exists := swagger.Info.Extensions["x-maidenlane-deployment-id"]; exists {
_, err := g.storeNewContractInfo(address, ext.(string), address, registeredAs)
if err != nil {
log.Errorf("Failed to write migrated instance file: %s", err)
return
}
if err := os.Remove(fileName); err != nil {
log.Errorf("Failed to clean-up migrated file %s: %s", fileName, err)
}
} else {
log.Warnf("Swagger cannot be migrated due to missing 'x-maidenlane-deployment-id' extension: %s", fileName)
}
}
func (g *smartContractGW) addFileToContractIndex(address, fileName string) {
contractFile, err := os.OpenFile(fileName, os.O_RDONLY, 0)
if err != nil {
log.Errorf("Failed to load contract instance file %s: %s", fileName, err)
return
}
defer contractFile.Close()
var contractInfo contractInfo
err = json.NewDecoder(bufio.NewReader(contractFile)).Decode(&contractInfo)
if err != nil {
log.Errorf("Failed to parse contract instnace deployment file %s: %s", fileName, err)
return
}
g.addToContractIndex(&contractInfo)
}
func (g *smartContractGW) addFileToABIIndex(id, fileName string, createdTime time.Time) {
deployFile, err := os.OpenFile(fileName, os.O_RDONLY, 0)
if err != nil {
log.Errorf("Failed to load ABI deployment file %s: %s", fileName, err)
return
}
defer deployFile.Close()
var deployMsg maidenlanedmessages.DeployContract
err = json.NewDecoder(bufio.NewReader(deployFile)).Decode(&deployMsg)
if err != nil {
log.Errorf("Failed to parse ABI deployment file %s: %s", fileName, err)
return
}
g.addToABIIndex(id, &deployMsg, createdTime)
}
func (g *smartContractGW) checkNameAvailable(registerAs string, isRemote bool) error {
if isRemote {
msg, err := g.rr.loadFactoryForInstance(registerAs, false)
if err != nil {
return err
} else if msg != nil {
return maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayFriendlyNameClash, msg.Address, registerAs)
}
return nil
}
if existing, exists := g.contractRegistrations[registerAs]; exists {
return maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayFriendlyNameClash, existing.Address, registerAs)
}
return nil
}
func (g *smartContractGW) addToContractIndex(info *contractInfo) error {
g.idxLock.Lock()
defer g.idxLock.Unlock()
if info.RegisteredAs != "" {
// Protect against overwrite
if err := g.checkNameAvailable(info.RegisteredAs, false); err != nil {
return err
}
log.Infof("Registering %s as '%s'", info.Address, info.RegisteredAs)
g.contractRegistrations[info.RegisteredAs] = info
}
g.contractIndex[info.Address] = info
return nil
}
func (g *smartContractGW) addToABIIndex(id string, deployMsg *maidenlanedmessages.DeployContract, createdTime time.Time) *abiInfo {
g.idxLock.Lock()
info := &abiInfo{
ID: id,
Name: deployMsg.ContractName,
Description: deployMsg.Description,
Deployable: len(deployMsg.Compiled) > 0,
CompilerVersion: deployMsg.CompilerVersion,
Path: "/abis/" + id,
SwaggerURL: g.conf.BaseURL + "/abis/" + id + "?swagger",
TimeSorted: maidenlanedmessages.TimeSorted{
CreatedISO8601: createdTime.UTC().Format(time.RFC3339),
},
}
g.abiIndex[id] = info
g.idxLock.Unlock()
return info
}
// listContracts sorts by Title then Address and returns an array
func (g *smartContractGW) listContractsOrABIs(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
log.Infof("--> %s %s", req.Method, req.URL)
var index map[string]maidenlanedmessages.TimeSortable
if strings.HasSuffix(req.URL.Path, "contracts") {
index = g.contractIndex
} else {
index = g.abiIndex
}
// Get an array copy of the current list
g.idxLock.Lock()
retval := make([]maidenlanedmessages.TimeSortable, 0, len(index))
for _, info := range index {
retval = append(retval, info)
}
g.idxLock.Unlock()
// Do the sort by Title then Address
sort.Slice(retval, func(i, j int) bool {
return retval[i].IsLessThan(retval[i], retval[j])
})
status := 200
log.Infof("<-- %s %s [%d]", req.Method, req.URL, status)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(status)
enc := json.NewEncoder(res)
enc.SetIndent("", " ")
enc.Encode(&retval)
}
// createStream creates a stream
func (g *smartContractGW) createStream(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
log.Infof("--> %s %s", req.Method, req.URL)
if g.sm == nil {
g.gatewayErrReply(res, req, errors.New(errEventSupportMissing), 405)
return
}
var spec maidenlanedevents.StreamInfo
if err := json.NewDecoder(req.Body).Decode(&spec); err != nil {
g.gatewayErrReply(res, req, maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayEventStreamInvalid, err), 400)
return
}
newSpec, err := g.sm.AddStream(req.Context(), &spec)
if err != nil {
g.gatewayErrReply(res, req, err, 400)
return
}
status := 200
log.Infof("<-- %s %s [%d]", req.Method, req.URL, status)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(status)
enc := json.NewEncoder(res)
enc.SetIndent("", " ")
enc.Encode(&newSpec)
}
// updateStream updates a stream
func (g *smartContractGW) updateStream(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
log.Infof("--> %s %s", req.Method, req.URL)
if g.sm == nil {
g.gatewayErrReply(res, req, errors.New(errEventSupportMissing), 405)
return
}
streamID := params.ByName("id")
_, err := g.sm.StreamByID(req.Context(), streamID)
if err != nil {
g.gatewayErrReply(res, req, err, 404)
return
}
var spec maidenlanedevents.StreamInfo
if err := json.NewDecoder(req.Body).Decode(&spec); err != nil {
g.gatewayErrReply(res, req, maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayEventStreamInvalid, err), 400)
return
}
newSpec, err := g.sm.UpdateStream(req.Context(), streamID, &spec)
if err != nil {
g.gatewayErrReply(res, req, err, 500)
return
}
status := 200
log.Infof("<-- %s %s [%d]", req.Method, req.URL, status)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(status)
enc := json.NewEncoder(res)
enc.SetIndent("", " ")
enc.Encode(&newSpec)
}
// listStreamsOrSubs sorts by Title then Address and returns an array
func (g *smartContractGW) listStreamsOrSubs(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
log.Infof("--> %s %s", req.Method, req.URL)
if g.sm == nil {
g.gatewayErrReply(res, req, errors.New(errEventSupportMissing), 405)
return
}
var results []maidenlanedmessages.TimeSortable
if strings.HasPrefix(req.URL.Path, maidenlanedevents.SubPathPrefix) {
subs := g.sm.Subscriptions(req.Context())
results = make([]maidenlanedmessages.TimeSortable, len(subs))
for i := range subs {
results[i] = subs[i]
}
} else {
streams := g.sm.Streams(req.Context())
results = make([]maidenlanedmessages.TimeSortable, len(streams))
for i := range streams {
results[i] = streams[i]
}
}
// Do the sort
sort.Slice(results, func(i, j int) bool {
return results[i].IsLessThan(results[i], results[j])
})
status := 200
log.Infof("<-- %s %s [%d]", req.Method, req.URL, status)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(status)
enc := json.NewEncoder(res)
enc.SetIndent("", " ")
enc.Encode(&results)
}
// getStreamOrSub returns stream over REST
func (g *smartContractGW) getStreamOrSub(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
log.Infof("--> %s %s", req.Method, req.URL)
if g.sm == nil {
g.gatewayErrReply(res, req, errors.New(errEventSupportMissing), 405)
return
}
var retval interface{}
var err error
if strings.HasPrefix(req.URL.Path, maidenlanedevents.SubPathPrefix) {
retval, err = g.sm.SubscriptionByID(req.Context(), params.ByName("id"))
} else {
retval, err = g.sm.StreamByID(req.Context(), params.ByName("id"))
}
if err != nil {
g.gatewayErrReply(res, req, err, 404)
return
}
status := 200
log.Infof("<-- %s %s [%d]", req.Method, req.URL, status)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(status)
enc := json.NewEncoder(res)
enc.SetIndent("", " ")
enc.Encode(retval)
}
// deleteStreamOrSub deletes stream over REST
func (g *smartContractGW) deleteStreamOrSub(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
log.Infof("--> %s %s", req.Method, req.URL)
if g.sm == nil {
g.gatewayErrReply(res, req, errors.New(errEventSupportMissing), 405)
return
}
var err error
if strings.HasPrefix(req.URL.Path, maidenlanedevents.SubPathPrefix) {
err = g.sm.DeleteSubscription(req.Context(), params.ByName("id"))
} else {
err = g.sm.DeleteStream(req.Context(), params.ByName("id"))
}
if err != nil {
g.gatewayErrReply(res, req, err, 500)
return
}
status := 204
log.Infof("<-- %s %s [%d]", req.Method, req.URL, status)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(status)
}
// resetSub resets subscription over REST
func (g *smartContractGW) resetSub(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
log.Infof("--> %s %s", req.Method, req.URL)
if g.sm == nil {
g.gatewayErrReply(res, req, errors.New(errEventSupportMissing), 405)
return
}
var body struct {
FromBlock string `json:"fromBlock"`
}
err := json.NewDecoder(req.Body).Decode(&body)
if err == nil {
err = g.sm.ResetSubscription(req.Context(), params.ByName("id"), body.FromBlock)
}
if err != nil {
g.gatewayErrReply(res, req, err, 500)
return
}
status := 204
log.Infof("<-- %s %s [%d]", req.Method, req.URL, status)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(status)
}
// suspendOrResumeStream suspends or resumes a stream
func (g *smartContractGW) suspendOrResumeStream(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
log.Infof("--> %s %s", req.Method, req.URL)
if g.sm == nil {
g.gatewayErrReply(res, req, errors.New(errEventSupportMissing), 405)
return
}
var err error
if strings.HasSuffix(req.URL.Path, "resume") {
err = g.sm.ResumeStream(req.Context(), params.ByName("id"))
} else {
err = g.sm.SuspendStream(req.Context(), params.ByName("id"))
}
if err != nil {
g.gatewayErrReply(res, req, err, 500)
return
}
status := 204
log.Infof("<-- %s %s [%d]", req.Method, req.URL, status)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(status)
}
func (g *smartContractGW) resolveAddressOrName(id string) (deployMsg *maidenlanedmessages.DeployContract, registeredName string, info *contractInfo, err error) {
deployMsg, info, err = g.loadDeployMsgForInstance(id)
if err != nil {
var origErr = err
registeredName = id
if id, err = g.resolveContractAddr(registeredName); err != nil {
log.Infof("%s is not a friendly name: %s", registeredName, err)
return nil, "", nil, origErr
}
if deployMsg, info, err = g.loadDeployMsgForInstance(id); err != nil {
return nil, "", nil, err
}
}
return deployMsg, registeredName, info, err
}
func (g *smartContractGW) isSwaggerRequest(req *http.Request) (swaggerGen *maidenlanedopenapi.ABI2Swagger, uiRequest, factoryOnly, abiRequest, refreshABI bool, from string) {
req.ParseForm()
var swaggerRequest bool
if vs := req.Form["swagger"]; len(vs) > 0 {
swaggerRequest = strings.ToLower(vs[0]) != "false"
}
if vs := req.Form["openapi"]; len(vs) > 0 {
swaggerRequest = strings.ToLower(vs[0]) != "false"
}
if vs := req.Form["ui"]; len(vs) > 0 {
uiRequest = strings.ToLower(vs[0]) != "false"
}
if vs := req.Form["factory"]; len(vs) > 0 {
factoryOnly = strings.ToLower(vs[0]) != "false"
}
if vs := req.Form["abi"]; len(vs) > 0 {
abiRequest = strings.ToLower(vs[0]) != "false"
}
if vs := req.Form["refresh"]; len(vs) > 0 {
refreshABI = strings.ToLower(vs[0]) != "false"
}
from = req.FormValue("from")
if swaggerRequest {
var conf = *g.baseSwaggerConf
if vs := req.Form["noauth"]; len(vs) > 0 {
conf.BasicAuth = strings.ToLower(vs[0]) == "false"
}
if vs := req.Form["schemes"]; len(vs) > 0 {
requested := strings.Split(vs[0], ",")
conf.ExternalSchemes = []string{}
for _, scheme := range requested {
// Only allow http and https
if scheme == "http" || scheme == "https" {
conf.ExternalSchemes = append(conf.ExternalSchemes, scheme)
} else {
log.Warnf("Excluded unknown scheme: %s", scheme)
}
}
}
swaggerGen = maidenlanedopenapi.NewABI2Swagger(&conf)
}
return
}
func (g *smartContractGW) replyWithSwagger(res http.ResponseWriter, req *http.Request, swagger *spec.Swagger, id, from string) {
if from != "" {
if swagger.Parameters != nil {
if param, exists := swagger.Parameters["fromParam"]; exists {
param.SimpleSchema.Default = from
swagger.Parameters["fromParam"] = param
}
}
}
swaggerBytes, _ := json.MarshalIndent(&swagger, "", " ")
log.Infof("<-- %s %s [%d]", req.Method, req.URL, 200)
res.Header().Set("Content-Type", "application/json")
if vs := req.Form["download"]; len(vs) > 0 {
res.Header().Set("Content-Disposition", "attachment; filename=\""+id+".swagger.json\"")
}
res.WriteHeader(200)
res.Write(swaggerBytes)
}
func (g *smartContractGW) getContractOrABI(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
log.Infof("--> %s %s", req.Method, req.URL)
swaggerGen, uiRequest, factoryOnly, abiRequest, _, from := g.isSwaggerRequest(req)
id := strings.TrimPrefix(strings.ToLower(params.ByName("address")), "0x")
prefix := "contract"
if id == "" {
id = strings.ToLower(params.ByName("abi"))
prefix = "abi"
}
// For safety we always check our sanitized address index in memory, before checking the filesystem
var registeredName string
var err error
var deployMsg *maidenlanedmessages.DeployContract
var info maidenlanedmessages.TimeSortable
var abiID string
if prefix == "contract" {
if deployMsg, registeredName, info, err = g.resolveAddressOrName(params.ByName("address")); err != nil {
g.gatewayErrReply(res, req, err, 404)
return
}
} else {
abiID = id
deployMsg, info, err = g.loadDeployMsgByID(abiID)
if err != nil {
g.gatewayErrReply(res, req, err, 404)
return
}
}
if uiRequest {
g.writeHTMLForUI(prefix, id, from, (prefix == "abi"), factoryOnly, res)
} else if swaggerGen != nil {
addr := params.ByName("address")
runtimeABI, err := maidenlanedbind.ABIMarshalingToABIRuntime(deployMsg.ABI)
if err != nil {
g.gatewayErrReply(res, req, maidenlanederrors.Errorf(maidenlanederrors.RESTGatewayInvalidABI, err), 404)
return
}
swagger := g.swaggerForABI(swaggerGen, abiID, deployMsg.ContractName, factoryOnly, runtimeABI, deployMsg.DevDoc, addr, registeredName)
g.replyWithSwagger(res, req, swagger, id, from)
} else if abiRequest {
log.Infof("<-- %s %s [%d]", req.Method, req.URL, 200)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(200)
enc := json.NewEncoder(res)
enc.SetIndent("", " ")
enc.Encode(deployMsg.ABI)
} else {
log.Infof("<-- %s %s [%d]", req.Method, req.URL, 200)
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(200)
enc := json.NewEncoder(res)
enc.SetIndent("", " ")
enc.Encode(info)
}
}
func (g *smartContractGW) getRemoteRegistrySwaggerOrABI(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
log.Infof("--> %s %s", req.Method, req.URL)
swaggerGen, uiRequest, factoryOnly, abiRequest, refreshABI, from := g.isSwaggerRequest(req)
var deployMsg *maidenlanedmessages.DeployContract
var err error
var isGateway = false
var prefix, id, addr string
if strings.HasPrefix(req.URL.Path, "/gateways/") || strings.HasPrefix(req.URL.Path, "/g/") {
isGateway = true
prefix = "gateway"
id = params.ByName("gateway_lookup")
deployMsg, err = g.rr.loadFactoryForGateway(id, refreshABI)
if err != nil {
g.gatewayErrReply(res, req, err, 500)