aboutsummaryrefslogtreecommitdiffstats
path: root/swarm/api/http/server_test.go
blob: a7c7e300314551e23a47dc9eb10bf236683ea5dd (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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package http

import (
    "archive/tar"
    "bytes"
    "context"
    "crypto/rand"
    "encoding/json"
    "errors"
    "flag"
    "fmt"
    "io"
    "io/ioutil"
    "math/big"
    "mime/multipart"
    "net/http"
    "net/url"
    "os"
    "path"
    "strconv"
    "strings"
    "testing"
    "time"

    "github.com/ethereum/go-ethereum/swarm/storage/mru/lookup"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/log"
    "github.com/ethereum/go-ethereum/swarm/api"
    swarm "github.com/ethereum/go-ethereum/swarm/api/client"
    "github.com/ethereum/go-ethereum/swarm/multihash"
    "github.com/ethereum/go-ethereum/swarm/storage"
    "github.com/ethereum/go-ethereum/swarm/storage/mru"
    "github.com/ethereum/go-ethereum/swarm/testutil"
)

func init() {
    loglevel := flag.Int("loglevel", 2, "loglevel")
    flag.Parse()
    log.Root().SetHandler(log.CallerFileHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(os.Stderr, log.TerminalFormat(true)))))
}

func serverFunc(api *api.API) testutil.TestServer {
    return NewServer(api, "")
}

func newTestSigner() (*mru.GenericSigner, error) {
    privKey, err := crypto.HexToECDSA("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")
    if err != nil {
        return nil, err
    }
    return mru.NewGenericSigner(privKey), nil
}

// test the transparent resolving of multihash-containing feed updates with bzz:// scheme
//
// first upload data, and store the multihash to the resulting manifest in a feed update
// retrieving the update with the multihash should return the manifest pointing directly to the data
// and raw retrieve of that hash should return the data
func TestBzzFeedMultihash(t *testing.T) {

    signer, _ := newTestSigner()

    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    // add the data our multihash aliased manifest will point to
    databytes := "bar"
    testBzzUrl := fmt.Sprintf("%s/bzz:/", srv.URL)
    resp, err := http.Post(testBzzUrl, "text/plain", bytes.NewReader([]byte(databytes)))
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        t.Fatalf("err %s", resp.Status)
    }
    b, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        t.Fatal(err)
    }
    s := common.FromHex(string(b))
    mh := multihash.ToMultihash(s)

    log.Info("added data", "manifest", string(b), "data", common.ToHex(mh))

    topic, _ := mru.NewTopic("foo.eth", nil)
    updateRequest := mru.NewFirstRequest(topic)

    updateRequest.SetData(mh)

    if err := updateRequest.Sign(signer); err != nil {
        t.Fatal(err)
    }
    log.Info("added data", "manifest", string(b), "data", common.ToHex(mh))

    testUrl, err := url.Parse(fmt.Sprintf("%s/bzz-feed:/", srv.URL))
    if err != nil {
        t.Fatal(err)
    }
    query := testUrl.Query()
    body := updateRequest.AppendValues(query) // this adds all query parameters and returns the data to be posted
    query.Set("manifest", "1")                // indicate we want a manifest back
    testUrl.RawQuery = query.Encode()

    // create the multihash update
    resp, err = http.Post(testUrl.String(), "application/octet-stream", bytes.NewReader(body))
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        t.Fatalf("err %s", resp.Status)
    }
    b, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Fatal(err)
    }
    rsrcResp := &storage.Address{}
    err = json.Unmarshal(b, rsrcResp)
    if err != nil {
        t.Fatalf("data %s could not be unmarshaled: %v", b, err)
    }

    correctManifestAddrHex := "bb056a5264c295c2b0f613c8409b9c87ce9d71576ace02458160df4cc894210b"
    if rsrcResp.Hex() != correctManifestAddrHex {
        t.Fatalf("Response feed manifest address mismatch, expected '%s', got '%s'", correctManifestAddrHex, rsrcResp.Hex())
    }

    // get bzz manifest transparent feed update resolve
    testBzzUrl = fmt.Sprintf("%s/bzz:/%s", srv.URL, rsrcResp)
    resp, err = http.Get(testBzzUrl)
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        t.Fatalf("err %s", resp.Status)
    }
    b, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(b, []byte(databytes)) {
        t.Fatalf("retrieved data mismatch, expected %x, got %x", databytes, b)
    }
}

// Test Swarm Feeds using the raw update methods
func TestBzzFeed(t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    signer, _ := newTestSigner()

    defer srv.Close()

    // data of update 1
    update1Data := make([]byte, 666)
    update1Timestamp := srv.CurrentTime
    _, err := rand.Read(update1Data)
    if err != nil {
        t.Fatal(err)
    }
    //data for update 2
    update2Data := []byte("foo")

    topic, _ := mru.NewTopic("foo.eth", nil)
    updateRequest := mru.NewFirstRequest(topic)
    if err != nil {
        t.Fatal(err)
    }
    updateRequest.SetData(update1Data)

    if err := updateRequest.Sign(signer); err != nil {
        t.Fatal(err)
    }

    // creates feed and sets update 1
    testUrl, err := url.Parse(fmt.Sprintf("%s/bzz-feed:/", srv.URL))
    if err != nil {
        t.Fatal(err)
    }
    urlQuery := testUrl.Query()
    body := updateRequest.AppendValues(urlQuery) // this adds all query parameters
    urlQuery.Set("manifest", "1")                // indicate we want a manifest back
    testUrl.RawQuery = urlQuery.Encode()

    resp, err := http.Post(testUrl.String(), "application/octet-stream", bytes.NewReader(body))
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        t.Fatalf("err %s", resp.Status)
    }
    b, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Fatal(err)
    }
    rsrcResp := &storage.Address{}
    err = json.Unmarshal(b, rsrcResp)
    if err != nil {
        t.Fatalf("data %s could not be unmarshaled: %v", b, err)
    }

    correctManifestAddrHex := "bb056a5264c295c2b0f613c8409b9c87ce9d71576ace02458160df4cc894210b"
    if rsrcResp.Hex() != correctManifestAddrHex {
        t.Fatalf("Response feed manifest mismatch, expected '%s', got '%s'", correctManifestAddrHex, rsrcResp.Hex())
    }

    // get the manifest
    testRawUrl := fmt.Sprintf("%s/bzz-raw:/%s", srv.URL, rsrcResp)
    resp, err = http.Get(testRawUrl)
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        t.Fatalf("err %s", resp.Status)
    }
    b, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Fatal(err)
    }
    manifest := &api.Manifest{}
    err = json.Unmarshal(b, manifest)
    if err != nil {
        t.Fatal(err)
    }
    if len(manifest.Entries) != 1 {
        t.Fatalf("Manifest has %d entries", len(manifest.Entries))
    }
    correctFeedHex := "0x666f6f2e65746800000000000000000000000000000000000000000000000000c96aaa54e2d44c299564da76e1cd3184a2386b8d"
    if manifest.Entries[0].Feed.Hex() != correctFeedHex {
        t.Fatalf("Expected manifest Feed '%s', got '%s'", correctFeedHex, manifest.Entries[0].Feed.Hex())
    }

    // get bzz manifest transparent feed update resolve
    testBzzUrl := fmt.Sprintf("%s/bzz:/%s", srv.URL, rsrcResp)
    resp, err = http.Get(testBzzUrl)
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode == http.StatusOK {
        t.Fatal("Expected error status since feed update does not contain multihash. Received 200 OK")
    }
    b, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Fatal(err)
    }

    // get non-existent name, should fail
    testBzzResUrl := fmt.Sprintf("%s/bzz-feed:/bar", srv.URL)
    resp, err = http.Get(testBzzResUrl)
    if err != nil {
        t.Fatal(err)
    }

    if resp.StatusCode != http.StatusNotFound {
        t.Fatalf("Expected get non-existent feed manifest to fail with StatusNotFound (404), got %d", resp.StatusCode)
    }

    resp.Body.Close()

    // get latest update through bzz-feed directly
    log.Info("get update latest = 1.1", "addr", correctManifestAddrHex)
    testBzzResUrl = fmt.Sprintf("%s/bzz-feed:/%s", srv.URL, correctManifestAddrHex)
    resp, err = http.Get(testBzzResUrl)
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        t.Fatalf("err %s", resp.Status)
    }
    b, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(update1Data, b) {
        t.Fatalf("Expected body '%x', got '%x'", update1Data, b)
    }

    // update 2
    // Move the clock ahead 1 second
    srv.CurrentTime++
    log.Info("update 2")

    // 1.- get metadata about this Feed
    testBzzResUrl = fmt.Sprintf("%s/bzz-feed:/%s/", srv.URL, correctManifestAddrHex)
    resp, err = http.Get(testBzzResUrl + "?meta=1")
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        t.Fatalf("Get feed metadata returned %s", resp.Status)
    }
    b, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Fatal(err)
    }
    updateRequest = &mru.Request{}
    if err = updateRequest.UnmarshalJSON(b); err != nil {
        t.Fatalf("Error decoding feed metadata: %s", err)
    }
    updateRequest.SetData(update2Data)
    if err = updateRequest.Sign(signer); err != nil {
        t.Fatal(err)
    }
    testUrl, err = url.Parse(fmt.Sprintf("%s/bzz-feed:/", srv.URL))
    if err != nil {
        t.Fatal(err)
    }
    urlQuery = testUrl.Query()
    body = updateRequest.AppendValues(urlQuery) // this adds all query parameters
    testUrl.RawQuery = urlQuery.Encode()

    resp, err = http.Post(testUrl.String(), "application/octet-stream", bytes.NewReader(body))
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        t.Fatalf("Update returned %s", resp.Status)
    }

    // get latest update through bzz-feed directly
    log.Info("get update 1.2")
    testBzzResUrl = fmt.Sprintf("%s/bzz-feed:/%s", srv.URL, correctManifestAddrHex)
    resp, err = http.Get(testBzzResUrl)
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        t.Fatalf("err %s", resp.Status)
    }
    b, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(update2Data, b) {
        t.Fatalf("Expected body '%x', got '%x'", update2Data, b)
    }

    // test manifest-less queries
    log.Info("get first update in update1Timestamp via direct query")
    query := mru.NewQuery(&updateRequest.Feed, update1Timestamp, lookup.NoClue)

    urlq, err := url.Parse(fmt.Sprintf("%s/bzz-feed:/", srv.URL))
    if err != nil {
        t.Fatal(err)
    }

    values := urlq.Query()
    query.AppendValues(values) // this adds feed query parameters
    urlq.RawQuery = values.Encode()
    resp, err = http.Get(urlq.String())
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        t.Fatalf("err %s", resp.Status)
    }
    b, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(update1Data, b) {
        t.Fatalf("Expected body '%x', got '%x'", update1Data, b)
    }

}

func TestBzzGetPath(t *testing.T) {
    testBzzGetPath(false, t)
    testBzzGetPath(true, t)
}

func testBzzGetPath(encrypted bool, t *testing.T) {
    var err error

    testmanifest := []string{
        `{"entries":[{"path":"b","hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","contentType":"","status":0},{"path":"c","hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","contentType":"","status":0}]}`,
        `{"entries":[{"path":"a","hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","contentType":"","status":0},{"path":"b/","hash":"<key0>","contentType":"application/bzz-manifest+json","status":0}]}`,
        `{"entries":[{"path":"a/","hash":"<key1>","contentType":"application/bzz-manifest+json","status":0}]}`,
    }

    testrequests := make(map[string]int)
    testrequests["/"] = 2
    testrequests["/a/"] = 1
    testrequests["/a/b/"] = 0
    testrequests["/x"] = 0
    testrequests[""] = 0

    expectedfailrequests := []string{"", "/x"}

    reader := [3]*bytes.Reader{}

    addr := [3]storage.Address{}

    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    for i, mf := range testmanifest {
        reader[i] = bytes.NewReader([]byte(mf))
        var wait func(context.Context) error
        ctx := context.TODO()
        addr[i], wait, err = srv.FileStore.Store(ctx, reader[i], int64(len(mf)), encrypted)
        if err != nil {
            t.Fatal(err)
        }
        for j := i + 1; j < len(testmanifest); j++ {
            testmanifest[j] = strings.Replace(testmanifest[j], fmt.Sprintf("<key%v>", i), addr[i].Hex(), -1)
        }
        err = wait(ctx)
        if err != nil {
            t.Fatal(err)
        }
    }

    rootRef := addr[2].Hex()

    _, err = http.Get(srv.URL + "/bzz-raw:/" + rootRef + "/a")
    if err != nil {
        t.Fatalf("Failed to connect to proxy: %v", err)
    }

    for k, v := range testrequests {
        var resp *http.Response
        var respbody []byte

        url := srv.URL + "/bzz-raw:/"
        if k != "" {
            url += rootRef + "/" + k[1:] + "?content_type=text/plain"
        }
        resp, err = http.Get(url)
        if err != nil {
            t.Fatalf("Request failed: %v", err)
        }
        defer resp.Body.Close()
        respbody, err = ioutil.ReadAll(resp.Body)

        if string(respbody) != testmanifest[v] {
            isexpectedfailrequest := false

            for _, r := range expectedfailrequests {
                if k == r {
                    isexpectedfailrequest = true
                }
            }
            if !isexpectedfailrequest {
                t.Fatalf("Response body does not match, expected: %v, got %v", testmanifest[v], string(respbody))
            }
        }
    }

    for k, v := range testrequests {
        var resp *http.Response
        var respbody []byte

        url := srv.URL + "/bzz-hash:/"
        if k != "" {
            url += rootRef + "/" + k[1:]
        }
        resp, err = http.Get(url)
        if err != nil {
            t.Fatalf("Request failed: %v", err)
        }
        defer resp.Body.Close()
        respbody, err = ioutil.ReadAll(resp.Body)
        if err != nil {
            t.Fatalf("Read request body: %v", err)
        }

        if string(respbody) != addr[v].Hex() {
            isexpectedfailrequest := false

            for _, r := range expectedfailrequests {
                if k == r {
                    isexpectedfailrequest = true
                }
            }
            if !isexpectedfailrequest {
                t.Fatalf("Response body does not match, expected: %v, got %v", addr[v], string(respbody))
            }
        }
    }

    ref := addr[2].Hex()

    for _, c := range []struct {
        path          string
        json          string
        pageFragments []string
    }{
        {
            path: "/",
            json: `{"common_prefixes":["a/"]}`,
            pageFragments: []string{
                fmt.Sprintf("Swarm index of bzz:/%s/", ref),
                `<a class="normal-link" href="a/">a/</a>`,
            },
        },
        {
            path: "/a/",
            json: `{"common_prefixes":["a/b/"],"entries":[{"hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","path":"a/a","mod_time":"0001-01-01T00:00:00Z"}]}`,
            pageFragments: []string{
                fmt.Sprintf("Swarm index of bzz:/%s/a/", ref),
                `<a class="normal-link" href="b/">b/</a>`,
                fmt.Sprintf(`<a class="normal-link" href="/bzz:/%s/a/a">a</a>`, ref),
            },
        },
        {
            path: "/a/b/",
            json: `{"entries":[{"hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","path":"a/b/b","mod_time":"0001-01-01T00:00:00Z"},{"hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","path":"a/b/c","mod_time":"0001-01-01T00:00:00Z"}]}`,
            pageFragments: []string{
                fmt.Sprintf("Swarm index of bzz:/%s/a/b/", ref),
                fmt.Sprintf(`<a class="normal-link" href="/bzz:/%s/a/b/b">b</a>`, ref),
                fmt.Sprintf(`<a class="normal-link" href="/bzz:/%s/a/b/c">c</a>`, ref),
            },
        },
        {
            path: "/x",
        },
        {
            path: "",
        },
    } {
        k := c.path
        url := srv.URL + "/bzz-list:/"
        if k != "" {
            url += rootRef + "/" + k[1:]
        }
        t.Run("json list "+c.path, func(t *testing.T) {
            resp, err := http.Get(url)
            if err != nil {
                t.Fatalf("HTTP request: %v", err)
            }
            defer resp.Body.Close()
            respbody, err := ioutil.ReadAll(resp.Body)
            if err != nil {
                t.Fatalf("Read response body: %v", err)
            }

            body := strings.TrimSpace(string(respbody))
            if body != c.json {
                isexpectedfailrequest := false

                for _, r := range expectedfailrequests {
                    if k == r {
                        isexpectedfailrequest = true
                    }
                }
                if !isexpectedfailrequest {
                    t.Errorf("Response list body %q does not match, expected: %v, got %v", k, c.json, body)
                }
            }
        })
        t.Run("html list "+c.path, func(t *testing.T) {
            req, err := http.NewRequest(http.MethodGet, url, nil)
            if err != nil {
                t.Fatalf("New request: %v", err)
            }
            req.Header.Set("Accept", "text/html")
            resp, err := http.DefaultClient.Do(req)
            if err != nil {
                t.Fatalf("HTTP request: %v", err)
            }
            defer resp.Body.Close()
            b, err := ioutil.ReadAll(resp.Body)
            if err != nil {
                t.Fatalf("Read response body: %v", err)
            }

            body := string(b)

            for _, f := range c.pageFragments {
                if !strings.Contains(body, f) {
                    isexpectedfailrequest := false

                    for _, r := range expectedfailrequests {
                        if k == r {
                            isexpectedfailrequest = true
                        }
                    }
                    if !isexpectedfailrequest {
                        t.Errorf("Response list body %q does not contain %q: body %q", k, f, body)
                    }
                }
            }
        })
    }

    nonhashtests := []string{
        srv.URL + "/bzz:/name",
        srv.URL + "/bzz-immutable:/nonhash",
        srv.URL + "/bzz-raw:/nonhash",
        srv.URL + "/bzz-list:/nonhash",
        srv.URL + "/bzz-hash:/nonhash",
    }

    nonhashresponses := []string{
        `cannot resolve name: no DNS to resolve name: "name"`,
        `cannot resolve nonhash: no DNS to resolve name: "nonhash"`,
        `cannot resolve nonhash: no DNS to resolve name: "nonhash"`,
        `cannot resolve nonhash: no DNS to resolve name: "nonhash"`,
        `cannot resolve nonhash: no DNS to resolve name: "nonhash"`,
    }

    for i, url := range nonhashtests {
        var resp *http.Response
        var respbody []byte

        resp, err = http.Get(url)

        if err != nil {
            t.Fatalf("Request failed: %v", err)
        }
        defer resp.Body.Close()
        respbody, err = ioutil.ReadAll(resp.Body)
        if err != nil {
            t.Fatalf("ReadAll failed: %v", err)
        }
        if !strings.Contains(string(respbody), nonhashresponses[i]) {
            t.Fatalf("Non-Hash response body does not match, expected: %v, got: %v", nonhashresponses[i], string(respbody))
        }
    }
}

func TestBzzTar(t *testing.T) {
    testBzzTar(false, t)
    testBzzTar(true, t)
}

func testBzzTar(encrypted bool, t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()
    fileNames := []string{"tmp1.txt", "tmp2.lock", "tmp3.rtf"}
    fileContents := []string{"tmp1textfilevalue", "tmp2lockfilelocked", "tmp3isjustaplaintextfile"}

    buf := &bytes.Buffer{}
    tw := tar.NewWriter(buf)
    defer tw.Close()

    for i, v := range fileNames {
        size := int64(len(fileContents[i]))
        hdr := &tar.Header{
            Name:    v,
            Mode:    0644,
            Size:    size,
            ModTime: time.Now(),
            Xattrs: map[string]string{
                "user.swarm.content-type": "text/plain",
            },
        }
        if err := tw.WriteHeader(hdr); err != nil {
            t.Fatal(err)
        }

        // copy the file into the tar stream
        n, err := io.Copy(tw, bytes.NewBufferString(fileContents[i]))
        if err != nil {
            t.Fatal(err)
        } else if n != size {
            t.Fatal("size mismatch")
        }
    }

    //post tar stream
    url := srv.URL + "/bzz:/"
    if encrypted {
        url = url + "encrypt"
    }
    req, err := http.NewRequest("POST", url, buf)
    if err != nil {
        t.Fatal(err)
    }
    req.Header.Add("Content-Type", "application/x-tar")
    client := &http.Client{}
    resp2, err := client.Do(req)
    if err != nil {
        t.Fatal(err)
    }
    if resp2.StatusCode != http.StatusOK {
        t.Fatalf("err %s", resp2.Status)
    }
    swarmHash, err := ioutil.ReadAll(resp2.Body)
    resp2.Body.Close()
    if err != nil {
        t.Fatal(err)
    }

    // now do a GET to get a tarball back
    req, err = http.NewRequest("GET", fmt.Sprintf(srv.URL+"/bzz:/%s", string(swarmHash)), nil)
    if err != nil {
        t.Fatal(err)
    }
    req.Header.Add("Accept", "application/x-tar")
    resp2, err = client.Do(req)
    if err != nil {
        t.Fatal(err)
    }
    defer resp2.Body.Close()

    if h := resp2.Header.Get("Content-Type"); h != "application/x-tar" {
        t.Fatalf("Content-Type header expected: application/x-tar, got: %s", h)
    }

    expectedFileName := string(swarmHash) + ".tar"
    expectedContentDisposition := fmt.Sprintf("inline; filename=\"%s\"", expectedFileName)
    if h := resp2.Header.Get("Content-Disposition"); h != expectedContentDisposition {
        t.Fatalf("Content-Disposition header expected: %s, got: %s", expectedContentDisposition, h)
    }

    file, err := ioutil.TempFile("", "swarm-downloaded-tarball")
    if err != nil {
        t.Fatal(err)
    }
    defer os.Remove(file.Name())
    _, err = io.Copy(file, resp2.Body)
    if err != nil {
        t.Fatalf("error getting tarball: %v", err)
    }
    file.Sync()
    file.Close()

    tarFileHandle, err := os.Open(file.Name())
    if err != nil {
        t.Fatal(err)
    }
    tr := tar.NewReader(tarFileHandle)

    for {
        hdr, err := tr.Next()
        if err == io.EOF {
            break
        } else if err != nil {
            t.Fatalf("error reading tar stream: %s", err)
        }
        bb := make([]byte, hdr.Size)
        _, err = tr.Read(bb)
        if err != nil && err != io.EOF {
            t.Fatal(err)
        }
        passed := false
        for i, v := range fileNames {
            if v == hdr.Name {
                if string(bb) == fileContents[i] {
                    passed = true
                    break
                }
            }
        }
        if !passed {
            t.Fatalf("file %s did not pass content assertion", hdr.Name)
        }
    }
}

// TestBzzRootRedirect tests that getting the root path of a manifest without
// a trailing slash gets redirected to include the trailing slash so that
// relative URLs work as expected.
func TestBzzRootRedirect(t *testing.T) {
    testBzzRootRedirect(false, t)
}
func TestBzzRootRedirectEncrypted(t *testing.T) {
    testBzzRootRedirect(true, t)
}

func testBzzRootRedirect(toEncrypt bool, t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    // create a manifest with some data at the root path
    client := swarm.NewClient(srv.URL)
    data := []byte("data")
    file := &swarm.File{
        ReadCloser: ioutil.NopCloser(bytes.NewReader(data)),
        ManifestEntry: api.ManifestEntry{
            Path:        "",
            ContentType: "text/plain",
            Size:        int64(len(data)),
        },
    }
    hash, err := client.Upload(file, "", toEncrypt)
    if err != nil {
        t.Fatal(err)
    }

    // define a CheckRedirect hook which ensures there is only a single
    // redirect to the correct URL
    redirected := false
    httpClient := http.Client{
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            if redirected {
                return errors.New("too many redirects")
            }
            redirected = true
            expectedPath := "/bzz:/" + hash + "/"
            if req.URL.Path != expectedPath {
                return fmt.Errorf("expected redirect to %q, got %q", expectedPath, req.URL.Path)
            }
            return nil
        },
    }

    // perform the GET request and assert the response
    res, err := httpClient.Get(srv.URL + "/bzz:/" + hash)
    if err != nil {
        t.Fatal(err)
    }
    defer res.Body.Close()
    if !redirected {
        t.Fatal("expected GET /bzz:/<hash> to redirect to /bzz:/<hash>/ but it didn't")
    }
    gotData, err := ioutil.ReadAll(res.Body)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(gotData, data) {
        t.Fatalf("expected response to equal %q, got %q", data, gotData)
    }
}

func TestMethodsNotAllowed(t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()
    databytes := "bar"
    for _, c := range []struct {
        url  string
        code int
    }{
        {
            url:  fmt.Sprintf("%s/bzz-list:/", srv.URL),
            code: http.StatusMethodNotAllowed,
        }, {
            url:  fmt.Sprintf("%s/bzz-hash:/", srv.URL),
            code: http.StatusMethodNotAllowed,
        },
        {
            url:  fmt.Sprintf("%s/bzz-immutable:/", srv.URL),
            code: http.StatusMethodNotAllowed,
        },
    } {
        res, _ := http.Post(c.url, "text/plain", bytes.NewReader([]byte(databytes)))
        if res.StatusCode != c.code {
            t.Fatalf("should have failed. requested url: %s, expected code %d, got %d", c.url, c.code, res.StatusCode)
        }
    }

}

func httpDo(httpMethod string, url string, reqBody io.Reader, headers map[string]string, verbose bool, t *testing.T) (*http.Response, string) {
    // Build the Request
    req, err := http.NewRequest(httpMethod, url, reqBody)
    if err != nil {
        t.Fatal(err)
    }
    for key, value := range headers {
        req.Header.Set(key, value)
    }
    if verbose {
        t.Log(req.Method, req.URL, req.Header, req.Body)
    }

    // Send Request out
    httpClient := &http.Client{}
    res, err := httpClient.Do(req)
    if err != nil {
        t.Fatal(err)
    }

    // Read the HTTP Body
    buffer, err := ioutil.ReadAll(res.Body)
    if err != nil {
        t.Fatal(err)
    }
    defer res.Body.Close()
    body := string(buffer)

    return res, body
}

func TestGet(t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    for _, testCase := range []struct {
        uri                string
        method             string
        headers            map[string]string
        expectedStatusCode int
        assertResponseBody string
        verbose            bool
    }{
        {
            uri:                fmt.Sprintf("%s/", srv.URL),
            method:             "GET",
            headers:            map[string]string{"Accept": "text/html"},
            expectedStatusCode: http.StatusOK,
            assertResponseBody: "Swarm: Serverless Hosting Incentivised Peer-To-Peer Storage And Content Distribution",
            verbose:            false,
        },
        {
            uri:                fmt.Sprintf("%s/", srv.URL),
            method:             "GET",
            headers:            map[string]string{"Accept": "application/json"},
            expectedStatusCode: http.StatusOK,
            assertResponseBody: "Swarm: Please request a valid ENS or swarm hash with the appropriate bzz scheme",
            verbose:            false,
        },
        {
            uri:                fmt.Sprintf("%s/robots.txt", srv.URL),
            method:             "GET",
            headers:            map[string]string{"Accept": "text/html"},
            expectedStatusCode: http.StatusOK,
            assertResponseBody: "User-agent: *\nDisallow: /",
            verbose:            false,
        },
        {
            uri:                fmt.Sprintf("%s/nonexistent_path", srv.URL),
            method:             "GET",
            headers:            map[string]string{},
            expectedStatusCode: http.StatusNotFound,
            verbose:            false,
        },
        {
            uri:                fmt.Sprintf("%s/bzz:asdf/", srv.URL),
            method:             "GET",
            headers:            map[string]string{},
            expectedStatusCode: http.StatusNotFound,
            verbose:            false,
        },
        {
            uri:                fmt.Sprintf("%s/tbz2/", srv.URL),
            method:             "GET",
            headers:            map[string]string{},
            expectedStatusCode: http.StatusNotFound,
            verbose:            false,
        },
        {
            uri:                fmt.Sprintf("%s/bzz-rack:/", srv.URL),
            method:             "GET",
            headers:            map[string]string{},
            expectedStatusCode: http.StatusNotFound,
            verbose:            false,
        },
        {
            uri:                fmt.Sprintf("%s/bzz-ls", srv.URL),
            method:             "GET",
            headers:            map[string]string{},
            expectedStatusCode: http.StatusNotFound,
            verbose:            false,
        }} {
        t.Run("GET "+testCase.uri, func(t *testing.T) {
            res, body := httpDo(testCase.method, testCase.uri, nil, testCase.headers, testCase.verbose, t)
            if res.StatusCode != testCase.expectedStatusCode {
                t.Fatalf("expected status code %d but got %d", testCase.expectedStatusCode, res.StatusCode)
            }
            if testCase.assertResponseBody != "" && !strings.Contains(body, testCase.assertResponseBody) {
                t.Fatalf("expected response to be: %s but got: %s", testCase.assertResponseBody, body)
            }
        })
    }
}

func TestModify(t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    swarmClient := swarm.NewClient(srv.URL)
    data := []byte("data")
    file := &swarm.File{
        ReadCloser: ioutil.NopCloser(bytes.NewReader(data)),
        ManifestEntry: api.ManifestEntry{
            Path:        "",
            ContentType: "text/plain",
            Size:        int64(len(data)),
        },
    }

    hash, err := swarmClient.Upload(file, "", false)
    if err != nil {
        t.Fatal(err)
    }

    for _, testCase := range []struct {
        uri                   string
        method                string
        headers               map[string]string
        requestBody           []byte
        expectedStatusCode    int
        assertResponseBody    string
        assertResponseHeaders map[string]string
        verbose               bool
    }{
        {
            uri:                fmt.Sprintf("%s/bzz:/%s", srv.URL, hash),
            method:             "DELETE",
            headers:            map[string]string{},
            expectedStatusCode: http.StatusOK,
            assertResponseBody: "8b634aea26eec353ac0ecbec20c94f44d6f8d11f38d4578a4c207a84c74ef731",
            verbose:            false,
        },
        {
            uri:                fmt.Sprintf("%s/bzz:/%s", srv.URL, hash),
            method:             "PUT",
            headers:            map[string]string{},
            expectedStatusCode: http.StatusMethodNotAllowed,
            verbose:            false,
        },
        {
            uri:                fmt.Sprintf("%s/bzz-raw:/%s", srv.URL, hash),
            method:             "PUT",
            headers:            map[string]string{},
            expectedStatusCode: http.StatusMethodNotAllowed,
            verbose:            false,
        },
        {
            uri:                fmt.Sprintf("%s/bzz:/%s", srv.URL, hash),
            method:             "PATCH",
            headers:            map[string]string{},
            expectedStatusCode: http.StatusMethodNotAllowed,
            verbose:            false,
        },
        {
            uri:                   fmt.Sprintf("%s/bzz-raw:/", srv.URL),
            method:                "POST",
            headers:               map[string]string{},
            requestBody:           []byte("POSTdata"),
            expectedStatusCode:    http.StatusOK,
            assertResponseHeaders: map[string]string{"Content-Length": "64"},
            verbose:               false,
        },
        {
            uri:                   fmt.Sprintf("%s/bzz-raw:/encrypt", srv.URL),
            method:                "POST",
            headers:               map[string]string{},
            requestBody:           []byte("POSTdata"),
            expectedStatusCode:    http.StatusOK,
            assertResponseHeaders: map[string]string{"Content-Length": "128"},
            verbose:               false,
        },
    } {
        t.Run(testCase.method+" "+testCase.uri, func(t *testing.T) {
            reqBody := bytes.NewReader(testCase.requestBody)
            res, body := httpDo(testCase.method, testCase.uri, reqBody, testCase.headers, testCase.verbose, t)

            if res.StatusCode != testCase.expectedStatusCode {
                t.Fatalf("expected status code %d but got %d, %s", testCase.expectedStatusCode, res.StatusCode, body)
            }
            if testCase.assertResponseBody != "" && !strings.Contains(body, testCase.assertResponseBody) {
                t.Log(body)
                t.Fatalf("expected response %s but got %s", testCase.assertResponseBody, body)
            }
            for key, value := range testCase.assertResponseHeaders {
                if res.Header.Get(key) != value {
                    t.Logf("expected %s=%s in HTTP response header but got %s", key, value, res.Header.Get(key))
                }
            }
        })
    }
}

func TestMultiPartUpload(t *testing.T) {
    // POST /bzz:/ Content-Type: multipart/form-data
    verbose := false
    // Setup Swarm
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    url := fmt.Sprintf("%s/bzz:/", srv.URL)

    buf := new(bytes.Buffer)
    form := multipart.NewWriter(buf)
    form.WriteField("name", "John Doe")
    file1, _ := form.CreateFormFile("cv", "cv.txt")
    file1.Write([]byte("John Doe's Credentials"))
    file2, _ := form.CreateFormFile("profile_picture", "profile.jpg")
    file2.Write([]byte("imaginethisisjpegdata"))
    form.Close()

    headers := map[string]string{
        "Content-Type":   form.FormDataContentType(),
        "Content-Length": strconv.Itoa(buf.Len()),
    }
    res, body := httpDo("POST", url, buf, headers, verbose, t)

    if res.StatusCode != http.StatusOK {
        t.Fatalf("expected POST multipart/form-data to return 200, but it returned %d", res.StatusCode)
    }
    if len(body) != 64 {
        t.Fatalf("expected POST multipart/form-data to return a 64 char manifest but the answer was %d chars long", len(body))
    }
}

// TestBzzGetFileWithResolver tests fetching a file using a mocked ENS resolver
func TestBzzGetFileWithResolver(t *testing.T) {
    resolver := newTestResolveValidator("")
    srv := testutil.NewTestSwarmServer(t, serverFunc, resolver)
    defer srv.Close()
    fileNames := []string{"dir1/tmp1.txt", "dir2/tmp2.lock", "dir3/tmp3.rtf"}
    fileContents := []string{"tmp1textfilevalue", "tmp2lockfilelocked", "tmp3isjustaplaintextfile"}

    buf := &bytes.Buffer{}
    tw := tar.NewWriter(buf)

    for i, v := range fileNames {
        size := len(fileContents[i])
        hdr := &tar.Header{
            Name:    v,
            Mode:    0644,
            Size:    int64(size),
            ModTime: time.Now(),
            Xattrs: map[string]string{
                "user.swarm.content-type": "text/plain",
            },
        }
        if err := tw.WriteHeader(hdr); err != nil {
            t.Fatal(err)
        }

        // copy the file into the tar stream
        n, err := io.WriteString(tw, fileContents[i])
        if err != nil {
            t.Fatal(err)
        } else if n != size {
            t.Fatal("size mismatch")
        }
    }

    if err := tw.Close(); err != nil {
        t.Fatal(err)
    }

    //post tar stream
    url := srv.URL + "/bzz:/"

    req, err := http.NewRequest("POST", url, buf)
    if err != nil {
        t.Fatal(err)
    }
    req.Header.Add("Content-Type", "application/x-tar")
    client := &http.Client{}
    serverResponse, err := client.Do(req)
    if err != nil {
        t.Fatal(err)
    }
    if serverResponse.StatusCode != http.StatusOK {
        t.Fatalf("err %s", serverResponse.Status)
    }
    swarmHash, err := ioutil.ReadAll(serverResponse.Body)
    serverResponse.Body.Close()
    if err != nil {
        t.Fatal(err)
    }
    // set the resolved hash to be the swarm hash of what we've just uploaded
    hash := common.HexToHash(string(swarmHash))
    resolver.hash = &hash
    for _, v := range []struct {
        addr                string
        path                string
        expectedStatusCode  int
        expectedContentType string
        expectedFileName    string
    }{
        {
            addr:                string(swarmHash),
            path:                fileNames[0],
            expectedStatusCode:  http.StatusOK,
            expectedContentType: "text/plain",
            expectedFileName:    path.Base(fileNames[0]),
        },
        {
            addr:                "somebogusensname",
            path:                fileNames[0],
            expectedStatusCode:  http.StatusOK,
            expectedContentType: "text/plain",
            expectedFileName:    path.Base(fileNames[0]),
        },
    } {
        req, err := http.NewRequest("GET", fmt.Sprintf(srv.URL+"/bzz:/%s/%s", v.addr, v.path), nil)
        if err != nil {
            t.Fatal(err)
        }
        serverResponse, err := client.Do(req)
        if err != nil {
            t.Fatal(err)
        }
        defer serverResponse.Body.Close()
        if serverResponse.StatusCode != v.expectedStatusCode {
            t.Fatalf("expected %d, got %d", v.expectedStatusCode, serverResponse.StatusCode)
        }

        if h := serverResponse.Header.Get("Content-Type"); h != v.expectedContentType {
            t.Fatalf("Content-Type header expected: %s, got %s", v.expectedContentType, h)
        }

        expectedContentDisposition := fmt.Sprintf("inline; filename=\"%s\"", v.expectedFileName)
        if h := serverResponse.Header.Get("Content-Disposition"); h != expectedContentDisposition {
            t.Fatalf("Content-Disposition header expected: %s, got: %s", expectedContentDisposition, h)
        }

    }
}

// testResolver implements the Resolver interface and either returns the given
// hash if it is set, or returns a "name not found" error
type testResolveValidator struct {
    hash *common.Hash
}

func newTestResolveValidator(addr string) *testResolveValidator {
    r := &testResolveValidator{}
    if addr != "" {
        hash := common.HexToHash(addr)
        r.hash = &hash
    }
    return r
}

func (t *testResolveValidator) Resolve(addr string) (common.Hash, error) {
    if t.hash == nil {
        return common.Hash{}, fmt.Errorf("DNS name not found: %q", addr)
    }
    return *t.hash, nil
}

func (t *testResolveValidator) Owner(node [32]byte) (addr common.Address, err error) {
    return
}
func (t *testResolveValidator) HeaderByNumber(context.Context, *big.Int) (header *types.Header, err error) {
    return
}