aboutsummaryrefslogtreecommitdiffstats
path: root/cmd/swarm/swarm-smoke/feed_upload_and_sync.go
blob: c7a1475d6c9d4532bd5635230a09723b0b277a97 (plain) (blame)
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
package main

import (
    "bytes"
    "crypto/md5"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "os"
    "os/exec"
    "strings"
    "sync"
    "time"

    "github.com/pborman/uuid"

    "github.com/ethereum/go-ethereum/common/hexutil"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/log"
    "github.com/ethereum/go-ethereum/swarm/multihash"
    "github.com/ethereum/go-ethereum/swarm/storage/feed"

    colorable "github.com/mattn/go-colorable"

    cli "gopkg.in/urfave/cli.v1"
)

const (
    feedRandomDataLength = 8
)

// TODO: retrieve with manifest + extract repeating code
func cliFeedUploadAndSync(c *cli.Context) error {

    log.Root().SetHandler(log.CallerFileHandler(log.LvlFilterHandler(log.Lvl(verbosity), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true)))))

    defer func(now time.Time) { log.Info("total time", "time", time.Since(now), "size (kb)", filesize) }(time.Now())

    generateEndpoints(scheme, cluster, from, to)

    log.Info("generating and uploading MRUs to " + endpoints[0] + " and syncing")

    // create a random private key to sign updates with and derive the address
    pkFile, err := ioutil.TempFile("", "swarm-feed-smoke-test")
    if err != nil {
        return err
    }
    defer pkFile.Close()
    defer os.Remove(pkFile.Name())

    privkeyHex := "0000000000000000000000000000000000000000000000000000000000001976"
    privKey, err := crypto.HexToECDSA(privkeyHex)
    if err != nil {
        return err
    }
    user := crypto.PubkeyToAddress(privKey.PublicKey)
    userHex := hexutil.Encode(user.Bytes())

    // save the private key to a file
    _, err = io.WriteString(pkFile, privkeyHex)
    if err != nil {
        return err
    }

    // keep hex strings for topic and subtopic
    var topicHex string
    var subTopicHex string

    // and create combination hex topics for bzz-feed retrieval
    // xor'ed with topic (zero-value topic if no topic)
    var subTopicOnlyHex string
    var mergedSubTopicHex string

    // generate random topic and subtopic and put a hex on them
    topicBytes, err := generateRandomData(feed.TopicLength)
    topicHex = hexutil.Encode(topicBytes)
    subTopicBytes, err := generateRandomData(8)
    subTopicHex = hexutil.Encode(subTopicBytes)
    if err != nil {
        return err
    }
    mergedSubTopic, err := feed.NewTopic(subTopicHex, topicBytes)
    if err != nil {
        return err
    }
    mergedSubTopicHex = hexutil.Encode(mergedSubTopic[:])
    subTopicOnlyBytes, err := feed.NewTopic(subTopicHex, nil)
    if err != nil {
        return err
    }
    subTopicOnlyHex = hexutil.Encode(subTopicOnlyBytes[:])

    // create feed manifest, topic only
    var out bytes.Buffer
    cmd := exec.Command("swarm", "--bzzapi", endpoints[0], "feed", "create", "--topic", topicHex, "--user", userHex)
    cmd.Stdout = &out
    log.Debug("create feed manifest topic cmd", "cmd", cmd)
    err = cmd.Run()
    if err != nil {
        return err
    }
    manifestWithTopic := strings.TrimRight(out.String(), string([]byte{0x0a}))
    if len(manifestWithTopic) != 64 {
        return fmt.Errorf("unknown feed create manifest hash format (topic): (%d) %s", len(out.String()), manifestWithTopic)
    }
    log.Debug("create topic feed", "manifest", manifestWithTopic)
    out.Reset()

    // create feed manifest, subtopic only
    cmd = exec.Command("swarm", "--bzzapi", endpoints[0], "feed", "create", "--name", subTopicHex, "--user", userHex)
    cmd.Stdout = &out
    log.Debug("create feed manifest subtopic cmd", "cmd", cmd)
    err = cmd.Run()
    if err != nil {
        return err
    }
    manifestWithSubTopic := strings.TrimRight(out.String(), string([]byte{0x0a}))
    if len(manifestWithSubTopic) != 64 {
        return fmt.Errorf("unknown feed create manifest hash format (subtopic): (%d) %s", len(out.String()), manifestWithSubTopic)
    }
    log.Debug("create subtopic feed", "manifest", manifestWithTopic)
    out.Reset()

    // create feed manifest, merged topic
    cmd = exec.Command("swarm", "--bzzapi", endpoints[0], "feed", "create", "--topic", topicHex, "--name", subTopicHex, "--user", userHex)
    cmd.Stdout = &out
    log.Debug("create feed manifest mergetopic cmd", "cmd", cmd)
    err = cmd.Run()
    if err != nil {
        log.Error(err.Error())
        return err
    }
    manifestWithMergedTopic := strings.TrimRight(out.String(), string([]byte{0x0a}))
    if len(manifestWithMergedTopic) != 64 {
        return fmt.Errorf("unknown feed create manifest hash format (mergedtopic): (%d) %s", len(out.String()), manifestWithMergedTopic)
    }
    log.Debug("create mergedtopic feed", "manifest", manifestWithMergedTopic)
    out.Reset()

    // create test data
    data, err := generateRandomData(feedRandomDataLength)
    if err != nil {
        return err
    }
    h := md5.New()
    h.Write(data)
    dataHash := h.Sum(nil)
    dataHex := hexutil.Encode(data)

    // update with topic
    cmd = exec.Command("swarm", "--bzzaccount", pkFile.Name(), "--bzzapi", endpoints[0], "feed", "update", "--topic", topicHex, dataHex)
    cmd.Stdout = &out
    log.Debug("update feed manifest topic cmd", "cmd", cmd)
    err = cmd.Run()
    if err != nil {
        return err
    }
    log.Debug("feed update topic", "out", out)
    out.Reset()

    // update with subtopic
    cmd = exec.Command("swarm", "--bzzaccount", pkFile.Name(), "--bzzapi", endpoints[0], "feed", "update", "--name", subTopicHex, dataHex)
    cmd.Stdout = &out
    log.Debug("update feed manifest subtopic cmd", "cmd", cmd)
    err = cmd.Run()
    if err != nil {
        return err
    }
    log.Debug("feed update subtopic", "out", out)
    out.Reset()

    // update with merged topic
    cmd = exec.Command("swarm", "--bzzaccount", pkFile.Name(), "--bzzapi", endpoints[0], "feed", "update", "--topic", topicHex, "--name", subTopicHex, dataHex)
    cmd.Stdout = &out
    log.Debug("update feed manifest merged topic cmd", "cmd", cmd)
    err = cmd.Run()
    if err != nil {
        return err
    }
    log.Debug("feed update mergedtopic", "out", out)
    out.Reset()

    time.Sleep(3 * time.Second)

    // retrieve the data
    wg := sync.WaitGroup{}
    for _, endpoint := range endpoints {
        // raw retrieve, topic only
        for _, hex := range []string{topicHex, subTopicOnlyHex, mergedSubTopicHex} {
            wg.Add(1)
            ruid := uuid.New()[:8]
            go func(endpoint string, ruid string) {
                for {
                    err := fetchFeed(hex, userHex, endpoint, dataHash, ruid)
                    if err != nil {
                        continue
                    }

                    wg.Done()
                    return
                }
            }(endpoint, ruid)

        }
    }
    wg.Wait()
    log.Info("all endpoints synced random data successfully")

    // upload test file
    log.Info("uploading to " + endpoints[0] + " and syncing")

    f, cleanup := generateRandomFile(filesize * 1000)
    defer cleanup()

    hash, err := upload(f, endpoints[0])
    if err != nil {
        return err
    }
    hashBytes, err := hexutil.Decode("0x" + hash)
    if err != nil {
        return err
    }
    multihashHex := hexutil.Encode(multihash.ToMultihash(hashBytes))

    fileHash, err := digest(f)
    if err != nil {
        return err
    }

    log.Info("uploaded successfully", "hash", hash, "digest", fmt.Sprintf("%x", fileHash))

    // update file with topic
    cmd = exec.Command("swarm", "--bzzaccount", pkFile.Name(), "--bzzapi", endpoints[0], "feed", "update", "--topic", topicHex, multihashHex)
    cmd.Stdout = &out
    err = cmd.Run()
    if err != nil {
        return err
    }
    log.Debug("feed update topic", "out", out)
    out.Reset()

    // update file with subtopic
    cmd = exec.Command("swarm", "--bzzaccount", pkFile.Name(), "--bzzapi", endpoints[0], "feed", "update", "--name", subTopicHex, multihashHex)
    cmd.Stdout = &out
    err = cmd.Run()
    if err != nil {
        return err
    }
    log.Debug("feed update subtopic", "out", out)
    out.Reset()

    // update file with merged topic
    cmd = exec.Command("swarm", "--bzzaccount", pkFile.Name(), "--bzzapi", endpoints[0], "feed", "update", "--topic", topicHex, "--name", subTopicHex, multihashHex)
    cmd.Stdout = &out
    err = cmd.Run()
    if err != nil {
        return err
    }
    log.Debug("feed update mergedtopic", "out", out)
    out.Reset()

    time.Sleep(3 * time.Second)

    for _, endpoint := range endpoints {

        // manifest retrieve, topic only
        for _, url := range []string{manifestWithTopic, manifestWithSubTopic, manifestWithMergedTopic} {
            wg.Add(1)
            ruid := uuid.New()[:8]
            go func(endpoint string, ruid string) {
                for {
                    err := fetch(url, endpoint, fileHash, ruid)
                    if err != nil {
                        continue
                    }

                    wg.Done()
                    return
                }
            }(endpoint, ruid)
        }

    }
    wg.Wait()
    log.Info("all endpoints synced random file successfully")

    return nil
}

func fetchFeed(topic string, user string, endpoint string, original []byte, ruid string) error {
    log.Trace("sleeping", "ruid", ruid)
    time.Sleep(3 * time.Second)

    log.Trace("http get request (feed)", "ruid", ruid, "api", endpoint, "topic", topic, "user", user)
    res, err := http.Get(endpoint + "/bzz-feed:/?topic=" + topic + "&user=" + user)
    if err != nil {
        return err
    }
    log.Trace("http get response (feed)", "ruid", ruid, "api", endpoint, "topic", topic, "user", user, "code", res.StatusCode, "len", res.ContentLength)

    if res.StatusCode != 200 {
        return fmt.Errorf("expected status code %d, got %v (ruid %v)", 200, res.StatusCode, ruid)
    }

    defer res.Body.Close()

    rdigest, err := digest(res.Body)
    if err != nil {
        log.Warn(err.Error(), "ruid", ruid)
        return err
    }

    if !bytes.Equal(rdigest, original) {
        err := fmt.Errorf("downloaded imported file md5=%x is not the same as the generated one=%x", rdigest, original)
        log.Warn(err.Error(), "ruid", ruid)
        return err
    }

    log.Trace("downloaded file matches random file", "ruid", ruid, "len", res.ContentLength)

    return nil
}