forked from thirdweb-dev/go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipfs_storage.go
384 lines (329 loc) · 9.36 KB
/
ipfs_storage.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
package thirdweb
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math/big"
"mime/multipart"
"net/http"
"reflect"
"strings"
)
type baseUriWithUris struct {
baseUri string
uris []string
}
type storage interface {
Get(ctx context.Context, uri string) ([]byte, error)
Upload(ctx context.Context, data map[string]interface{}, contractAddress string, signerAddress string) (string, error)
UploadBatch(ctx context.Context, data []map[string]interface{}, fileStartNumber int, contractAddress string, signerAddress string) (*baseUriWithUris, error)
}
type uploadResponse struct {
IpfsHash string `json:"ipfsHash"`
PinSize *big.Int `json:"PinSize"`
Timestamp string `json:"Timestamp"`
IsDuplicate bool `json:"isDuplicate"`
IpfsUri string `json:"IpfsUri"`
}
type IpfsStorage struct {
secretKey string
gatewayUrl string
httpClient *http.Client
}
func newIpfsStorage(secretKey string, gatewayUrl string, httpClient *http.Client) *IpfsStorage {
return &IpfsStorage{
secretKey: secretKey,
gatewayUrl: gatewayUrl,
httpClient: httpClient,
}
}
// Get
//
// # Get IPFS data at a given hash and return it as byte data
//
// uri: the IPFS URI to fetch data from
//
// returns: byte data of the IPFS data at the URI
func (ipfs *IpfsStorage) Get(ctx context.Context, uri string) ([]byte, error) {
gatewayUrl := replaceHashWithGatewayUrl(uri, ipfs.gatewayUrl)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, gatewayUrl, nil)
if err != nil {
return nil, err
}
if strings.Contains(ipfs.gatewayUrl, ".ipfscdn.io") {
req.Header.Set("x-secret-key", ipfs.secretKey)
}
resp, err := ipfs.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, errors.New(fmt.Sprintf("Bad status code, %d", resp.StatusCode))
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
// Upload
//
// Upload method can be used to upload a generic payload to IPFS.
//
// data: the individual data to upload to IPFS
//
// contractAddress: the optional contractAddress upload is being called from
//
// signerAddress: the optional signerAddress upload is being called from
//
// returns: the URI of the IPFS upload
func (ipfs *IpfsStorage) Upload(ctx context.Context, data map[string]interface{}, contractAddress string, signerAddress string) (string, error) {
baseUriWithUris, err := ipfs.UploadBatch(ctx, []map[string]interface{}{data}, 0, contractAddress, signerAddress)
if err != nil {
return "", err
}
baseUri := baseUriWithUris.baseUri + "0"
return baseUri, nil
}
// UploadBatch
//
// UploadBatch method can be used to upload a batch of generic payloads to IPFS.
//
// data: the array of data to upload to IPFS
//
// contractAddress: the optional contractAddress upload is being called from
//
// signerAddress: the optional signerAddress upload is being called from
//
// returns: the base URI of the IPFS upload folder with the URIs of each subfile
func (ipfs *IpfsStorage) UploadBatch(ctx context.Context, data []map[string]interface{}, fileStartNumber int, contractAddress string, signerAddress string) (*baseUriWithUris, error) {
preparedData, err := ipfs.batchUploadProperties(ctx, data)
if err != nil {
return nil, err
}
dataToUpload := []interface{}{}
dataValue := reflect.ValueOf(preparedData)
switch dataValue.Kind() {
case reflect.Array, reflect.Slice:
for i := 0; i < dataValue.Len(); i++ {
jsonData, err := json.Marshal(dataValue.Index(i).Interface())
if err != nil {
return nil, err
}
dataToUpload = append(dataToUpload, jsonData)
}
break
default:
return nil, errors.New("data must be an array or slice")
}
baseUriWithUris, err := ipfs.uploadBatchWithCid(ctx, dataToUpload, fileStartNumber)
if err != nil {
return nil, err
}
return baseUriWithUris, nil
}
func (ipfs *IpfsStorage) uploadBatchWithCid(
ctx context.Context,
// data (string | io.Reader)[] - file or JSON string
data []interface{},
fileStartNumber int,
) (*baseUriWithUris, error) {
fileNames := []string{}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
for i, obj := range data {
if jsonData, ok := obj.([]byte); ok {
fileName := fmt.Sprintf("%v", i+fileStartNumber)
fileNames = append(fileNames, fileName)
part, err := writer.CreateFormFile("file", fmt.Sprintf("files/%v", fileName))
if err != nil {
return nil, err
}
if _, err := part.Write(jsonData); err != nil {
return nil, err
}
} else if fileData, ok := obj.(io.Reader); ok {
fileName := fmt.Sprintf("%v", i+fileStartNumber)
fileNames = append(fileNames, fileName)
part, err := writer.CreateFormFile("file", fmt.Sprintf("files/%v", fileName))
if err != nil {
return nil, err
}
_, err = io.Copy(part, fileData)
if err != nil {
return nil, err
}
} else {
return nil, errors.New("Data to upload must be either JSON ([]byte) or a file (io.Reader)")
}
}
_ = writer.Close()
req, err := http.NewRequestWithContext(ctx, "POST", twStorageUploadUrl, body)
if err != nil {
return nil, err
}
req.Header.Set("x-secret-key", ipfs.secretKey)
req.Header.Set("Content-Type", writer.FormDataContentType())
if result, err := ipfs.httpClient.Do(req); err != nil {
return nil, err
} else {
if result.StatusCode != http.StatusOK {
return nil, &failedToUploadError{
statusCode: result.StatusCode,
Payload: data,
}
}
var uploadMeta uploadResponse
bodyBytes, err := ioutil.ReadAll(result.Body)
if err != nil {
return nil, &failedToUploadError{
statusCode: result.StatusCode,
Payload: data,
UnderlyingError: err,
}
}
if err := json.Unmarshal(bodyBytes, &uploadMeta); err != nil {
return nil, &unmarshalError{
body: string(bodyBytes),
typeName: "UploadResponse",
UnderlyingError: err,
}
}
baseUri := "ipfs://" + uploadMeta.IpfsHash + "/"
uris := []string{}
for _, fileName := range fileNames {
uri := baseUri + fileName
uris = append(uris, uri)
}
return &baseUriWithUris{
baseUri: baseUri,
uris: uris,
}, nil
}
}
// returns - map[string]interface{}
func (ipfs *IpfsStorage) batchUploadProperties(ctx context.Context, data []map[string]interface{}) (interface{}, error) {
sanitizedMetadatas, err := replaceGatewayUrlWithHash(data, "ipfs://", ipfs.gatewayUrl)
if err != nil {
return nil, err
}
filesToUpload, err := buildFilePropertiesMap(sanitizedMetadatas, []interface{}{})
if err != nil {
return nil, err
}
if len(filesToUpload) == 0 {
return sanitizedMetadatas, nil
}
baseUriWithUris, err := ipfs.uploadBatchWithCid(ctx, filesToUpload, 0)
if err != nil {
return nil, err
}
replacedMetadatas, err := replaceFilePropertiesWithHashes(sanitizedMetadatas, baseUriWithUris.uris)
if err != nil {
return nil, err
}
return replacedMetadatas, nil
}
// data - array or map or strings
// Returns []io.Reader files to upload
func buildFilePropertiesMap(data interface{}, files []interface{}) ([]interface{}, error) {
v := reflect.ValueOf(data)
switch v.Kind() {
case reflect.Array, reflect.Slice:
for i := 0; i < v.Len(); i++ {
builtFiles, err := buildFilePropertiesMap(v.Index(i).Interface(), files)
if err != nil {
return nil, err
}
files = builtFiles
}
break
case reflect.Map:
for _, k := range v.MapKeys() {
builtFiles, err := buildFilePropertiesMap(v.MapIndex(k).Interface(), files)
if err != nil {
return nil, err
}
files = builtFiles
}
break
default:
file, ok := data.(io.Reader)
if ok {
files = append(files, file)
}
}
return files, nil
}
func replaceFilePropertiesWithHashes(data interface{}, cids []string) (interface{}, error) {
v := reflect.ValueOf(data)
switch v.Kind() {
case reflect.Array, reflect.Slice:
updated := []interface{}{}
for i := 0; i < v.Len(); i++ {
val, err := replaceFilePropertiesWithHashes(v.Index(i).Interface(), cids)
if err != nil {
return nil, err
}
updated = append(updated, val)
}
return updated, nil
case reflect.Map:
updated := map[string]interface{}{}
for _, k := range v.MapKeys() {
val, err := replaceFilePropertiesWithHashes(v.MapIndex(k).Interface(), cids)
if err != nil {
return nil, err
}
updated[k.String()] = val
}
return updated, nil
default:
_, ok := data.(io.Reader)
if ok {
data, cids = cids[0], cids[1:]
}
return data, nil
}
}
func replaceGatewayUrlWithHash(data interface{}, scheme string, gatewayUrl string) (interface{}, error) {
v := reflect.ValueOf(data)
switch v.Kind() {
case reflect.Array, reflect.Slice:
for i := 0; i < v.Len(); i++ {
if _, err := replaceGatewayUrlWithHash(v.Index(i), scheme, gatewayUrl); err != nil {
return nil, err
}
}
break
case reflect.Map:
for _, k := range v.MapKeys() {
if _, err := replaceGatewayUrlWithHash(v.MapIndex(k), scheme, gatewayUrl); err != nil {
return nil, err
}
}
break
case reflect.String:
if strings.Contains(v.String(), gatewayUrl) {
data = strings.Replace(v.String(), gatewayUrl, scheme, 1)
}
}
return data, nil
}
func resolveGatewayUrl(data interface{}, scheme string, gatewayUrl string) interface{} {
return data
}
func replaceHashWithGatewayUrl(ipfsUrl string, gatewayUrl string) string {
if ipfsUrl == "" {
return ""
}
gateway := gatewayUrl
if !strings.HasSuffix(gatewayUrl, "/") {
gateway = gatewayUrl + "/"
}
return strings.Replace(ipfsUrl, "ipfs://", gateway, 1)
}