forked from web3-protocol/web3protocol-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmode-resource-request.go
301 lines (263 loc) · 8.46 KB
/
mode-resource-request.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
package web3protocol
import (
"compress/gzip"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi"
// "github.com/ethereum/go-ethereum/common"
"github.com/andybalholm/brotli"
)
// Step 1 : Process the web3:// url
func (client *Client) parseResourceRequestModeUrl(web3Url *Web3URL, urlMainParts map[string]string) (err error) {
// For this mode, we call a specific function
web3Url.ContractCallMode = ContractCallModeMethod
web3Url.MethodName = "request"
// Input types
stringArrayType, _ := abi.NewType("string[]", "", nil)
keyValueStructArrayType, _ := abi.NewType("tuple[]", "", []abi.ArgumentMarshaling{
{Name: "key", Type: "string"},
{Name: "value", Type: "string"},
})
web3Url.MethodArgs = []abi.Type{
stringArrayType,
keyValueStructArrayType,
}
// Extract the values we will feed to the contract
argValues := make([]interface{}, 0)
// Process path
pathnameParts := strings.Split(urlMainParts["pathname"], "/")
pathnamePartsToSend := pathnameParts[1:]
// Remove empty strings at the end (e.g. /boo///)
for len(pathnamePartsToSend) > 0 && pathnamePartsToSend[len(pathnamePartsToSend)-1] == "" {
pathnamePartsToSend = pathnamePartsToSend[:len(pathnamePartsToSend)-1]
}
// Now URI-percent-decode the parts
for i, _ := range pathnamePartsToSend {
decodedPart, err := url.PathUnescape(pathnamePartsToSend[i])
if err != nil {
return &ErrorWithHttpCode{http.StatusBadRequest, "Unable to URI-percent decode: " + pathnamePartsToSend[i]}
}
pathnamePartsToSend[i] = decodedPart
}
argValues = append(argValues, pathnamePartsToSend)
// Process query
params := []struct {
Key string
Value string
}{}
parsedQuery, err := ParseQuery(urlMainParts["searchParams"])
if err != nil {
return err
}
for _, queryParam := range parsedQuery {
params = append(params, struct {
Key string
Value string
}{
Key: queryParam.Name,
Value: queryParam.Value,
})
}
argValues = append(argValues, params)
web3Url.MethodArgValues = argValues
// Contract return processing will be custom
web3Url.ContractReturnProcessing = ContractReturnProcessingDecodeErc5219Request
return
}
// Step 3 : We have the contract return, process it
func (client *Client) ProcessResourceRequestContractReturn(fetchedWeb3Url *FetchedWeb3URL, web3Url *Web3URL, contractReturn []byte) (err error) {
// Preparing the ABI data structure with which we will decode the contract output
uint16Type, _ := abi.NewType("uint16", "", nil)
stringType, _ := abi.NewType("string", "", nil)
keyValueStructArrayType, _ := abi.NewType("tuple[]", "", []abi.ArgumentMarshaling{
{Name: "key", Type: "string"},
{Name: "value", Type: "string"},
})
returnDataArgTypes := abi.Arguments{
{Type: uint16Type},
{Type: stringType},
{Type: keyValueStructArrayType},
}
// Decode the ABI data
unpackedValues, err := returnDataArgTypes.UnpackValues(contractReturn)
if err != nil {
return &ErrorWithHttpCode{http.StatusBadRequest, "Unable to parse contract output"}
}
// Assign the decoded data to the right slots
// HTTP code
httpCode, ok := unpackedValues[0].(uint16)
if !ok {
err = fmt.Errorf("invalid statusCode(uint16) %v", unpackedValues[0])
return
}
fetchedWeb3Url.HttpCode = int(httpCode)
// Headers
nextChunkUrl := ""
headers, ok := unpackedValues[2].([]struct {
Key string `json:"key"`
Value string `json:"value"`
})
if !ok {
err = fmt.Errorf("invalid headers %v", unpackedValues[2])
return
}
for _, header := range headers {
// Special header, pointer to next chunk
if header.Key == "web3-next-chunk" {
nextChunkUrl = header.Value
} else {
fetchedWeb3Url.HttpHeaders[header.Key] = header.Value
}
}
// Body
body, ok := unpackedValues[1].(string)
if !ok {
err = fmt.Errorf("invalid body(string) %v", unpackedValues[1])
return
}
// Custom reader, to handle ERC-7617 chunking
fetchedWeb3Url.Output = &ResourceRequestReader{
Client: client,
FetchedWeb3URL: fetchedWeb3Url,
Chunk: []byte(body),
Cursor: 0,
NextChunkUrl: nextChunkUrl,
}
//
// ERC-7618 : Handle the decompression of data, when Content-Encoding is provided
//
// Make a mapping of the lowercase headers name pointing to the original case
headersLowercase := make(map[string]string)
for headerName, _ := range fetchedWeb3Url.HttpHeaders {
headersLowercase[strings.ToLower(headerName)] = headerName
}
// Do we have a content-encoding header?
contentEncodingHeaderName, ok := headersLowercase["content-encoding"]
if ok {
// Gzip support
if fetchedWeb3Url.HttpHeaders[contentEncodingHeaderName] == "gzip" {
// Add the decompression reader
decompressionReader, err := gzip.NewReader(fetchedWeb3Url.Output)
if err != nil {
return &ErrorWithHttpCode{http.StatusBadRequest, "Gzip decompression error: " + err.Error()}
}
fetchedWeb3Url.Output = decompressionReader
// Add the error wrapper reader
fetchedWeb3Url.Output = &PrefixDecompressionErrorReader{Reader: fetchedWeb3Url.Output}
// Remove the content-encoding header
delete(fetchedWeb3Url.HttpHeaders, contentEncodingHeaderName)
// Brotli support
} else if fetchedWeb3Url.HttpHeaders[contentEncodingHeaderName] == "br" {
// Add the decompression reader
decompressionReader := brotli.NewReader(fetchedWeb3Url.Output)
fetchedWeb3Url.Output = decompressionReader
// Add the error wrapper reader
fetchedWeb3Url.Output = &PrefixDecompressionErrorReader{Reader: fetchedWeb3Url.Output}
// Remove the content-encoding header
delete(fetchedWeb3Url.HttpHeaders, contentEncodingHeaderName)
}
}
return
}
type ResourceRequestReader struct {
Client *Client
FetchedWeb3URL *FetchedWeb3URL
// Content of the last chunk call
Chunk []byte
Cursor int
NextChunkUrl string
}
// Return the result of the method call
// Implements ERC-7617: Support for chunking
func (rrr *ResourceRequestReader) Read(p []byte) (readBytes int, err error) {
// Still bytes to return in the current body chunk? Return it.
if rrr.Cursor < len(rrr.Chunk) {
remainingSize := len(rrr.Chunk) - rrr.Cursor
if len(p) >= remainingSize {
copy(p, rrr.Chunk[rrr.Cursor:])
readBytes = remainingSize
rrr.Cursor += readBytes
} else {
copy(p, rrr.Chunk[rrr.Cursor:rrr.Cursor+len(p)])
readBytes = len(p)
rrr.Cursor += readBytes
}
return
}
// No more bytes to return in the current body chunk
// No more chunk, return
if rrr.NextChunkUrl == "" {
return 0, io.EOF
}
// If URL is relative, make it absolute
if rrr.NextChunkUrl[0:1] == "/" {
rrr.NextChunkUrl = "web3://" + rrr.FetchedWeb3URL.ParsedUrl.ContractAddress.Hex() + ":" + strconv.Itoa(rrr.FetchedWeb3URL.ParsedUrl.ChainId) + rrr.NextChunkUrl
}
// Fetch the URL
nextChunkParsedUrl, err := rrr.Client.ParseUrl(rrr.NextChunkUrl)
if err != nil {
return 0, err
}
// Fetch the contract return data
nextChunkContractReturn, err := rrr.Client.FetchContractReturn(&nextChunkParsedUrl)
if err != nil {
return 0, err
}
// Preparing the ABI data structure with which we will decode the contract output
uint16Type, _ := abi.NewType("uint16", "", nil)
stringType, _ := abi.NewType("string", "", nil)
keyValueStructArrayType, _ := abi.NewType("tuple[]", "", []abi.ArgumentMarshaling{
{Name: "key", Type: "string"},
{Name: "value", Type: "string"},
})
returnDataArgTypes := abi.Arguments{
{Type: uint16Type},
{Type: stringType},
{Type: keyValueStructArrayType},
}
// Decode the ABI data
unpackedValues, err := returnDataArgTypes.UnpackValues(nextChunkContractReturn)
if err != nil {
return 0, err
}
// Get body
body, ok := unpackedValues[1].(string)
if !ok {
return 0, err
}
rrr.Chunk = []byte(body)
rrr.Cursor = 0
// ERC-7617: Support for chunking
// Find next chunk in headers
rrr.NextChunkUrl = ""
headers, ok := unpackedValues[2].([]struct {
Key string `json:"key"`
Value string `json:"value"`
})
if !ok {
return 0, err
}
for _, header := range headers {
if header.Key == "web3-next-chunk" {
rrr.NextChunkUrl = header.Value
}
}
return rrr.Read(p)
}
type PrefixDecompressionErrorReader struct {
Reader io.Reader
}
func (r *PrefixDecompressionErrorReader) Read(p []byte) (readBytes int, err error) {
readBytes, err = r.Reader.Read(p)
if err != nil {
// The brotli libs prefix his errors with "brotli: ": Put a little more helpful error message
if strings.HasPrefix(err.Error(), "brotli: ") {
err = &ErrorWithHttpCode{http.StatusBadRequest, "Brotli decompression error: " + strings.TrimPrefix(err.Error(), "brotli: ")}
}
}
return
}