-
Notifications
You must be signed in to change notification settings - Fork 0
/
remoteregistry.go
258 lines (236 loc) · 8.14 KB
/
remoteregistry.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
// 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 (
"encoding/hex"
"encoding/json"
"net/url"
"strings"
"github.com/freight-trust/zeroxyz/internal/maidenlanedbind"
"github.com/freight-trust/zeroxyz/internal/maidenlanederrors"
"github.com/freight-trust/zeroxyz/internal/maidenlanedkvstore"
"github.com/freight-trust/zeroxyz/internal/maidenlanedmessages"
"github.com/freight-trust/zeroxyz/internal/maidenlanedutils"
log "github.com/sirupsen/logrus"
)
const (
defaultIDProp = "id"
defaultNameProp = "name"
defaultABIProp = "abi"
defaultBytecodeProp = "bytecode"
defaultDevdocProp = "devdoc"
defaultDeployableProp = "deployable"
defaultAddressProp = "address"
)
type deployContractWithAddress struct {
maidenlanedmessages.DeployContract
Address string `json:"address"`
}
// RemoteRegistry lookup of ABI, ByteCode and DevDocs against a conformant REST API
type RemoteRegistry interface {
loadFactoryForGateway(lookupStr string, refresh bool) (*maidenlanedmessages.DeployContract, error)
loadFactoryForInstance(lookupStr string, refresh bool) (*deployContractWithAddress, error)
registerInstance(lookupStr, address string) error
init() error
close()
}
// RemoteRegistryConf configuration
type RemoteRegistryConf struct {
maidenlanedutils.HTTPRequesterConf
CacheDB string `json:"cacheDB"`
GatewayURLPrefix string `json:"gatewayURLPrefix"`
InstanceURLPrefix string `json:"instanceURLPrefix"`
PropNames RemoteRegistryPropNamesConf `json:"propNames"`
}
// RemoteRegistryPropNamesConf configures the JSON property names to extract from the GET response on the API
type RemoteRegistryPropNamesConf struct {
ID string `json:"id"`
Name string `json:"name"`
ABI string `json:"abi"`
Bytecode string `json:"bytecode"`
Devdoc string `json:"devdoc"`
Deployable string `json:"deployable"`
Address string `json:"address"`
}
// NewRemoteRegistry construtor
func NewRemoteRegistry(conf *RemoteRegistryConf) RemoteRegistry {
rr := &remoteRegistry{
conf: conf,
hr: maidenlanedutils.NewHTTPRequester("Contract registry", &conf.HTTPRequesterConf),
}
propNames := &conf.PropNames
if propNames.ID == "" {
propNames.ID = defaultIDProp
}
if propNames.Name == "" {
propNames.Name = defaultNameProp
}
if propNames.ABI == "" {
propNames.ABI = defaultABIProp
}
if propNames.Bytecode == "" {
propNames.Bytecode = defaultBytecodeProp
}
if propNames.Devdoc == "" {
propNames.Devdoc = defaultDevdocProp
}
if propNames.Deployable == "" {
propNames.Deployable = defaultDeployableProp
}
if propNames.Address == "" {
propNames.Address = defaultAddressProp
}
if rr.conf.GatewayURLPrefix != "" && !strings.HasSuffix(rr.conf.GatewayURLPrefix, "/") {
rr.conf.GatewayURLPrefix += "/"
}
if rr.conf.InstanceURLPrefix != "" && !strings.HasSuffix(rr.conf.InstanceURLPrefix, "/") {
rr.conf.InstanceURLPrefix += "/"
}
return rr
}
type remoteRegistry struct {
conf *RemoteRegistryConf
hr *maidenlanedutils.HTTPRequester
db maidenlanedkvstore.KVStore
}
func (rr *remoteRegistry) init() (err error) {
if rr.conf.CacheDB != "" {
if rr.db, err = maidenlanedkvstore.NewLDBKeyValueStore(rr.conf.CacheDB); err != nil {
return maidenlanederrors.Errorf(maidenlanederrors.RemoteRegistryCacheInit, err)
}
}
return nil
}
func (rr *remoteRegistry) loadFactoryFromURL(baseURL, ns, lookupStr string, refresh bool) (msg *deployContractWithAddress, err error) {
safeLookupStr := url.QueryEscape(lookupStr)
if !refresh {
msg = rr.loadFactoryFromCacheDB(ns + "/" + safeLookupStr)
if msg != nil {
return msg, nil
}
}
queryURL := baseURL + safeLookupStr
jsonRes, err := rr.hr.DoRequest("GET", queryURL, nil)
if err != nil || jsonRes == nil {
return nil, err
}
idString, err := rr.hr.GetResponseString(jsonRes, rr.conf.PropNames.ID, false)
if err != nil {
return nil, err
}
abiString, err := rr.hr.GetResponseString(jsonRes, rr.conf.PropNames.ABI, false)
if err != nil {
return nil, err
}
var abi maidenlanedbind.ABIMarshaling
err = json.Unmarshal([]byte(abiString), &abi)
if err != nil {
log.Errorf("GET %s <-- !Failed to decode ABI: %s\n%s", queryURL, err, abiString)
return nil, maidenlanederrors.Errorf(maidenlanederrors.RemoteRegistryLookupGenericProcessingFailed)
}
devdoc, err := rr.hr.GetResponseString(jsonRes, rr.conf.PropNames.Devdoc, true)
if err != nil {
return nil, err
}
bytecodeStr, err := rr.hr.GetResponseString(jsonRes, rr.conf.PropNames.Bytecode, false)
if err != nil {
return nil, err
}
var bytecode []byte
if bytecode, err = hex.DecodeString(strings.TrimPrefix(bytecodeStr, "0x")); err != nil {
log.Errorf("GET %s <-- !Failed to parse bytecode: %s\n%s", queryURL, err, bytecodeStr)
return nil, maidenlanederrors.Errorf(maidenlanederrors.RemoteRegistryLookupGenericProcessingFailed)
}
addr, _ := rr.hr.GetResponseString(jsonRes, rr.conf.PropNames.Address, false)
msg = &deployContractWithAddress{
DeployContract: maidenlanedmessages.DeployContract{
TransactionCommon: maidenlanedmessages.TransactionCommon{
RequestCommon: maidenlanedmessages.RequestCommon{
Headers: maidenlanedmessages.RequestHeaders{
CommonHeaders: maidenlanedmessages.CommonHeaders{
ID: idString,
Context: map[string]interface{}{
remoteRegistryContextKey: true,
},
},
},
},
},
ABI: abi,
DevDoc: devdoc,
Compiled: bytecode,
},
Address: strings.ToLower(strings.TrimPrefix(addr, "0x")),
}
rr.storeFactoryToCacheDB(ns+"/"+safeLookupStr, msg)
return msg, nil
}
func (rr *remoteRegistry) loadFactoryFromCacheDB(cacheKey string) *deployContractWithAddress {
if rr.db == nil {
return nil
}
b, err := rr.db.Get(cacheKey)
if err != nil {
return nil
}
var msg deployContractWithAddress
err = json.Unmarshal(b, &msg)
if err != nil {
log.Warnf("Failed to deserialized cached bytes for key %s: %s", cacheKey, err)
return nil
}
return &msg
}
func (rr *remoteRegistry) storeFactoryToCacheDB(cacheKey string, msg *deployContractWithAddress) {
if rr.db == nil {
return
}
b, _ := json.Marshal(msg)
if err := rr.db.Put(cacheKey, b); err != nil {
log.Warnf("Failed to write bytes to cache for key %s: %s", cacheKey, err)
return
}
}
func (rr *remoteRegistry) loadFactoryForGateway(lookupStr string, refresh bool) (*maidenlanedmessages.DeployContract, error) {
if rr.conf.GatewayURLPrefix == "" {
return nil, nil
}
msg, err := rr.loadFactoryFromURL(rr.conf.GatewayURLPrefix, "gateways", lookupStr, refresh)
if msg != nil {
// There is no address on a gateway, so we just return the DeployMsg
return &msg.DeployContract, err
}
return nil, err
}
func (rr *remoteRegistry) loadFactoryForInstance(lookupStr string, refresh bool) (*deployContractWithAddress, error) {
if rr.conf.InstanceURLPrefix == "" {
return nil, nil
}
return rr.loadFactoryFromURL(rr.conf.InstanceURLPrefix, "instances", lookupStr, refresh)
}
func (rr *remoteRegistry) registerInstance(lookupStr, address string) error {
if rr.conf.InstanceURLPrefix == "" {
return maidenlanederrors.Errorf(maidenlanederrors.RemoteRegistryNotConfigured)
}
safeLookupStr := url.QueryEscape(lookupStr)
requestURL := strings.TrimSuffix(rr.conf.InstanceURLPrefix, "/")
bodyMap := make(map[string]interface{})
bodyMap[rr.conf.PropNames.Name] = safeLookupStr
bodyMap[rr.conf.PropNames.Address] = address
log.Debugf("Registering contract: %+v", bodyMap)
_, err := rr.hr.DoRequest("POST", requestURL, bodyMap)
if err != nil {
return maidenlanederrors.Errorf(maidenlanederrors.RemoteRegistryRegistrationFailed, err)
}
return nil
}
func (rr *remoteRegistry) close() {
}