-
Notifications
You must be signed in to change notification settings - Fork 244
/
ipfs.go
237 lines (187 loc) · 4.59 KB
/
ipfs.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
package ipfs
import (
"context"
"errors"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"sync"
"time"
"github.com/ipfs/go-cid"
"github.com/wealdtech/go-multicodec"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/log"
"github.com/status-im/status-go/params"
)
const maxRequestsPerSecond = 3
type taskResponse struct {
err error
response []byte
}
type taskRequest struct {
cid string
download bool
doneChan chan taskResponse
}
type Downloader struct {
ctx context.Context
cancel func()
ipfsDir string
wg sync.WaitGroup
rateLimiterChan chan taskRequest
inputTaskChan chan taskRequest
client *http.Client
quit chan struct{}
}
func NewDownloader(rootDir string) *Downloader {
ipfsDir := filepath.Clean(filepath.Join(rootDir, "./ipfs"))
if err := os.MkdirAll(ipfsDir, 0700); err != nil {
panic("could not create IPFSDir")
}
ctx, cancel := context.WithCancel(context.TODO())
d := &Downloader{
ctx: ctx,
cancel: cancel,
ipfsDir: ipfsDir,
rateLimiterChan: make(chan taskRequest, maxRequestsPerSecond),
inputTaskChan: make(chan taskRequest, 1000),
wg: sync.WaitGroup{},
client: &http.Client{
Timeout: time.Second * 5,
},
quit: make(chan struct{}, 1),
}
go d.taskDispatcher()
go d.worker()
return d
}
func (d *Downloader) Stop() {
close(d.quit)
d.cancel()
d.wg.Wait()
close(d.inputTaskChan)
close(d.rateLimiterChan)
}
func (d *Downloader) worker() {
for request := range d.rateLimiterChan {
resp, err := d.download(request.cid, request.download)
request.doneChan <- taskResponse{
err: err,
response: resp,
}
}
}
func (d *Downloader) taskDispatcher() {
ticker := time.NewTicker(time.Second / maxRequestsPerSecond)
defer ticker.Stop()
for {
<-ticker.C
request, ok := <-d.inputTaskChan
if !ok {
return
}
d.rateLimiterChan <- request
}
}
func hashToCid(hash []byte) (string, error) {
// contract response includes a contenthash, which needs to be decoded to reveal
// an IPFS identifier. Once decoded, download the content from IPFS. This content
// is in EDN format, ie https://ipfs.infura.io/ipfs/QmWVVLwVKCwkVNjYJrRzQWREVvEk917PhbHYAUhA1gECTM
// and it also needs to be decoded in to a nim type
data, codec, err := multicodec.RemoveCodec(hash)
if err != nil {
return "", err
}
codecName, err := multicodec.Name(codec)
if err != nil {
return "", err
}
if codecName != "ipfs-ns" {
return "", errors.New("codecName is not ipfs-ns")
}
thisCID, err := cid.Parse(data)
if err != nil {
return "", err
}
return thisCID.Hash().B58String(), nil
}
func decodeStringHash(input string) (string, error) {
hash, err := hexutil.Decode("0x" + input)
if err != nil {
return "", err
}
cid, err := hashToCid(hash)
if err != nil {
return "", err
}
return cid, nil
}
// Get checks if an IPFS image exists and returns it from cache
// otherwise downloads it from INFURA's ipfs gateway
func (d *Downloader) Get(hash string, download bool) ([]byte, error) {
cid, err := decodeStringHash(hash)
if err != nil {
return nil, err
}
exists, content, err := d.exists(cid)
if err != nil {
return nil, err
}
if exists {
return content, nil
}
doneChan := make(chan taskResponse, 1)
d.wg.Add(1)
d.inputTaskChan <- taskRequest{
cid: cid,
download: download,
doneChan: doneChan,
}
done := <-doneChan
close(doneChan)
d.wg.Done()
return done.response, done.err
}
func (d *Downloader) exists(cid string) (bool, []byte, error) {
path := filepath.Join(d.ipfsDir, cid)
_, err := os.Stat(path)
if err == nil {
fileContent, err := os.ReadFile(path)
return true, fileContent, err
}
return false, nil, nil
}
func (d *Downloader) download(cid string, download bool) ([]byte, error) {
path := filepath.Join(d.ipfsDir, cid)
req, err := http.NewRequest(http.MethodGet, params.IpfsGatewayURL+cid, nil)
if err != nil {
return nil, err
}
req = req.WithContext(d.ctx)
resp, err := d.client.Do(req)
if err != nil {
return nil, err
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Error("failed to close the stickerpack request body", "err", err)
}
}()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
log.Error("could not load data for", "cid", cid, "code", resp.StatusCode)
return nil, errors.New("could not load ipfs data")
}
fileContent, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if download {
// #nosec G306
err = os.WriteFile(path, fileContent, 0700)
if err != nil {
return nil, err
}
}
return fileContent, nil
}