github.com/alexdevranger/node-1.8.27@v0.0.0-20221128213301-aa5841e41d2d/swarm/api/http/server_test.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-dubxcoin library.
     3  //
     4  // The go-dubxcoin library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-dubxcoin library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-dubxcoin library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package http
    18  
    19  import (
    20  	"archive/tar"
    21  	"bytes"
    22  	"context"
    23  	"encoding/json"
    24  	"errors"
    25  	"flag"
    26  	"fmt"
    27  	"io"
    28  	"io/ioutil"
    29  	"math/big"
    30  	"mime/multipart"
    31  	"net/http"
    32  	"net/url"
    33  	"os"
    34  	"path"
    35  	"strconv"
    36  	"strings"
    37  	"testing"
    38  	"time"
    39  
    40  	"github.com/alexdevranger/node-1.8.27/swarm/storage/feed/lookup"
    41  
    42  	"github.com/alexdevranger/node-1.8.27/common"
    43  	"github.com/alexdevranger/node-1.8.27/core/types"
    44  	"github.com/alexdevranger/node-1.8.27/crypto"
    45  	"github.com/alexdevranger/node-1.8.27/log"
    46  	"github.com/alexdevranger/node-1.8.27/swarm/api"
    47  	swarm "github.com/alexdevranger/node-1.8.27/swarm/api/client"
    48  	"github.com/alexdevranger/node-1.8.27/swarm/storage"
    49  	"github.com/alexdevranger/node-1.8.27/swarm/storage/feed"
    50  	"github.com/alexdevranger/node-1.8.27/swarm/testutil"
    51  )
    52  
    53  func init() {
    54  	loglevel := flag.Int("loglevel", 2, "loglevel")
    55  	flag.Parse()
    56  	log.Root().SetHandler(log.CallerFileHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(os.Stderr, log.TerminalFormat(true)))))
    57  }
    58  
    59  func serverFunc(api *api.API) TestServer {
    60  	return NewServer(api, "")
    61  }
    62  
    63  func newTestSigner() (*feed.GenericSigner, error) {
    64  	privKey, err := crypto.HexToECDSA("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")
    65  	if err != nil {
    66  		return nil, err
    67  	}
    68  	return feed.NewGenericSigner(privKey), nil
    69  }
    70  
    71  // Test the transparent resolving of feed updates with bzz:// scheme
    72  //
    73  // First upload data to bzz:, and store the Swarm hash to the resulting manifest in a feed update.
    74  // This effectively uses a feed to store a pointer to content rather than the content itself
    75  // Retrieving the update with the Swarm hash should return the manifest pointing directly to the data
    76  // and raw retrieve of that hash should return the data
    77  func TestBzzWithFeed(t *testing.T) {
    78  
    79  	signer, _ := newTestSigner()
    80  
    81  	// Initialize Swarm test server
    82  	srv := NewTestSwarmServer(t, serverFunc, nil)
    83  	defer srv.Close()
    84  
    85  	// put together some data for our test:
    86  	dataBytes := []byte(`
    87  	//
    88  	// Create some data our manifest will point to. Data that could be very big and wouldn't fit in a feed update.
    89  	// So what we are going to do is upload it to Swarm bzz:// and obtain a **manifest hash** pointing to it:
    90  	//
    91  	// MANIFEST HASH --> DATA
    92  	//
    93  	// Then, we store that **manifest hash** into a Swarm Feed update. Once we have done this,
    94  	// we can use the **feed manifest hash** in bzz:// instead, this way: bzz://feed-manifest-hash.
    95  	//
    96  	// FEED MANIFEST HASH --> MANIFEST HASH --> DATA
    97  	//
    98  	// Given that we can update the feed at any time with a new **manifest hash** but the **feed manifest hash**
    99  	// stays constant, we have effectively created a fixed address to changing content. (Applause)
   100  	//
   101  	// FEED MANIFEST HASH (the same) --> MANIFEST HASH(2) --> DATA(2) ...
   102  	//
   103  	`)
   104  
   105  	// POST data to bzz and get back a content-addressed **manifest hash** pointing to it.
   106  	resp, err := http.Post(fmt.Sprintf("%s/bzz:/", srv.URL), "text/plain", bytes.NewReader([]byte(dataBytes)))
   107  	if err != nil {
   108  		t.Fatal(err)
   109  	}
   110  
   111  	defer resp.Body.Close()
   112  	if resp.StatusCode != http.StatusOK {
   113  		t.Fatalf("err %s", resp.Status)
   114  	}
   115  	manifestAddressHex, err := ioutil.ReadAll(resp.Body)
   116  
   117  	if err != nil {
   118  		t.Fatal(err)
   119  	}
   120  
   121  	manifestAddress := common.FromHex(string(manifestAddressHex))
   122  
   123  	log.Info("added data", "manifest", string(manifestAddressHex))
   124  
   125  	// At this point we have uploaded the data and have a manifest pointing to it
   126  	// Now store that manifest address in a feed update.
   127  	// We also want a feed manifest, so we can use it to refer to the feed.
   128  
   129  	// First, create a topic for our feed:
   130  	topic, _ := feed.NewTopic("interesting topic indeed", nil)
   131  
   132  	// Create a feed update request:
   133  	updateRequest := feed.NewFirstRequest(topic)
   134  
   135  	// Store the **manifest address** as data into the feed update.
   136  	updateRequest.SetData(manifestAddress)
   137  
   138  	// Sign the update
   139  	if err := updateRequest.Sign(signer); err != nil {
   140  		t.Fatal(err)
   141  	}
   142  	log.Info("added data", "data", common.ToHex(manifestAddress))
   143  
   144  	// Build the feed update http request:
   145  	feedUpdateURL, err := url.Parse(fmt.Sprintf("%s/bzz-feed:/", srv.URL))
   146  	if err != nil {
   147  		t.Fatal(err)
   148  	}
   149  	query := feedUpdateURL.Query()
   150  	body := updateRequest.AppendValues(query) // this adds all query parameters and returns the data to be posted
   151  	query.Set("manifest", "1")                // indicate we want a feed manifest back
   152  	feedUpdateURL.RawQuery = query.Encode()
   153  
   154  	// submit the feed update request to Swarm
   155  	resp, err = http.Post(feedUpdateURL.String(), "application/octet-stream", bytes.NewReader(body))
   156  	if err != nil {
   157  		t.Fatal(err)
   158  	}
   159  	defer resp.Body.Close()
   160  	if resp.StatusCode != http.StatusOK {
   161  		t.Fatalf("err %s", resp.Status)
   162  	}
   163  
   164  	feedManifestAddressHex, err := ioutil.ReadAll(resp.Body)
   165  	if err != nil {
   166  		t.Fatal(err)
   167  	}
   168  	feedManifestAddress := &storage.Address{}
   169  	err = json.Unmarshal(feedManifestAddressHex, feedManifestAddress)
   170  	if err != nil {
   171  		t.Fatalf("data %s could not be unmarshaled: %v", feedManifestAddressHex, err)
   172  	}
   173  
   174  	correctManifestAddrHex := "747c402e5b9dc715a25a4393147512167bab018a007fad7cdcd9adc7fce1ced2"
   175  	if feedManifestAddress.Hex() != correctManifestAddrHex {
   176  		t.Fatalf("Response feed manifest address mismatch, expected '%s', got '%s'", correctManifestAddrHex, feedManifestAddress.Hex())
   177  	}
   178  
   179  	// get bzz manifest transparent feed update resolve
   180  	getBzzURL := fmt.Sprintf("%s/bzz:/%s", srv.URL, feedManifestAddress)
   181  	resp, err = http.Get(getBzzURL)
   182  	if err != nil {
   183  		t.Fatal(err)
   184  	}
   185  	defer resp.Body.Close()
   186  	if resp.StatusCode != http.StatusOK {
   187  		t.Fatalf("err %s", resp.Status)
   188  	}
   189  	retrievedData, err := ioutil.ReadAll(resp.Body)
   190  	if err != nil {
   191  		t.Fatal(err)
   192  	}
   193  	if !bytes.Equal(retrievedData, []byte(dataBytes)) {
   194  		t.Fatalf("retrieved data mismatch, expected %x, got %x", dataBytes, retrievedData)
   195  	}
   196  }
   197  
   198  // Test Swarm feeds using the raw update methods
   199  func TestBzzFeed(t *testing.T) {
   200  	srv := NewTestSwarmServer(t, serverFunc, nil)
   201  	signer, _ := newTestSigner()
   202  
   203  	defer srv.Close()
   204  
   205  	// data of update 1
   206  	update1Data := testutil.RandomBytes(1, 666)
   207  	update1Timestamp := srv.CurrentTime
   208  	//data for update 2
   209  	update2Data := []byte("foo")
   210  
   211  	topic, _ := feed.NewTopic("foo.eth", nil)
   212  	updateRequest := feed.NewFirstRequest(topic)
   213  	updateRequest.SetData(update1Data)
   214  
   215  	if err := updateRequest.Sign(signer); err != nil {
   216  		t.Fatal(err)
   217  	}
   218  
   219  	// creates feed and sets update 1
   220  	testUrl, err := url.Parse(fmt.Sprintf("%s/bzz-feed:/", srv.URL))
   221  	if err != nil {
   222  		t.Fatal(err)
   223  	}
   224  	urlQuery := testUrl.Query()
   225  	body := updateRequest.AppendValues(urlQuery) // this adds all query parameters
   226  	urlQuery.Set("manifest", "1")                // indicate we want a manifest back
   227  	testUrl.RawQuery = urlQuery.Encode()
   228  
   229  	resp, err := http.Post(testUrl.String(), "application/octet-stream", bytes.NewReader(body))
   230  	if err != nil {
   231  		t.Fatal(err)
   232  	}
   233  	defer resp.Body.Close()
   234  	if resp.StatusCode != http.StatusOK {
   235  		t.Fatalf("err %s", resp.Status)
   236  	}
   237  	b, err := ioutil.ReadAll(resp.Body)
   238  	if err != nil {
   239  		t.Fatal(err)
   240  	}
   241  	rsrcResp := &storage.Address{}
   242  	err = json.Unmarshal(b, rsrcResp)
   243  	if err != nil {
   244  		t.Fatalf("data %s could not be unmarshaled: %v", b, err)
   245  	}
   246  
   247  	correctManifestAddrHex := "bb056a5264c295c2b0f613c8409b9c87ce9d71576ace02458160df4cc894210b"
   248  	if rsrcResp.Hex() != correctManifestAddrHex {
   249  		t.Fatalf("Response feed manifest mismatch, expected '%s', got '%s'", correctManifestAddrHex, rsrcResp.Hex())
   250  	}
   251  
   252  	// get the manifest
   253  	testRawUrl := fmt.Sprintf("%s/bzz-raw:/%s", srv.URL, rsrcResp)
   254  	resp, err = http.Get(testRawUrl)
   255  	if err != nil {
   256  		t.Fatal(err)
   257  	}
   258  	defer resp.Body.Close()
   259  	if resp.StatusCode != http.StatusOK {
   260  		t.Fatalf("err %s", resp.Status)
   261  	}
   262  	b, err = ioutil.ReadAll(resp.Body)
   263  	if err != nil {
   264  		t.Fatal(err)
   265  	}
   266  	manifest := &api.Manifest{}
   267  	err = json.Unmarshal(b, manifest)
   268  	if err != nil {
   269  		t.Fatal(err)
   270  	}
   271  	if len(manifest.Entries) != 1 {
   272  		t.Fatalf("Manifest has %d entries", len(manifest.Entries))
   273  	}
   274  	correctFeedHex := "0x666f6f2e65746800000000000000000000000000000000000000000000000000c96aaa54e2d44c299564da76e1cd3184a2386b8d"
   275  	if manifest.Entries[0].Feed.Hex() != correctFeedHex {
   276  		t.Fatalf("Expected manifest Feed '%s', got '%s'", correctFeedHex, manifest.Entries[0].Feed.Hex())
   277  	}
   278  
   279  	// take the chance to have bzz: crash on resolving a feed update that does not contain
   280  	// a swarm hash:
   281  	testBzzUrl := fmt.Sprintf("%s/bzz:/%s", srv.URL, rsrcResp)
   282  	resp, err = http.Get(testBzzUrl)
   283  	if err != nil {
   284  		t.Fatal(err)
   285  	}
   286  	defer resp.Body.Close()
   287  	if resp.StatusCode == http.StatusOK {
   288  		t.Fatal("Expected error status since feed update does not contain a Swarm hash. Received 200 OK")
   289  	}
   290  	_, err = ioutil.ReadAll(resp.Body)
   291  	if err != nil {
   292  		t.Fatal(err)
   293  	}
   294  
   295  	// get non-existent name, should fail
   296  	testBzzResUrl := fmt.Sprintf("%s/bzz-feed:/bar", srv.URL)
   297  	resp, err = http.Get(testBzzResUrl)
   298  	if err != nil {
   299  		t.Fatal(err)
   300  	}
   301  
   302  	if resp.StatusCode != http.StatusNotFound {
   303  		t.Fatalf("Expected get non-existent feed manifest to fail with StatusNotFound (404), got %d", resp.StatusCode)
   304  	}
   305  
   306  	resp.Body.Close()
   307  
   308  	// get latest update through bzz-feed directly
   309  	log.Info("get update latest = 1.1", "addr", correctManifestAddrHex)
   310  	testBzzResUrl = fmt.Sprintf("%s/bzz-feed:/%s", srv.URL, correctManifestAddrHex)
   311  	resp, err = http.Get(testBzzResUrl)
   312  	if err != nil {
   313  		t.Fatal(err)
   314  	}
   315  	defer resp.Body.Close()
   316  	if resp.StatusCode != http.StatusOK {
   317  		t.Fatalf("err %s", resp.Status)
   318  	}
   319  	b, err = ioutil.ReadAll(resp.Body)
   320  	if err != nil {
   321  		t.Fatal(err)
   322  	}
   323  	if !bytes.Equal(update1Data, b) {
   324  		t.Fatalf("Expected body '%x', got '%x'", update1Data, b)
   325  	}
   326  
   327  	// update 2
   328  	// Move the clock ahead 1 second
   329  	srv.CurrentTime++
   330  	log.Info("update 2")
   331  
   332  	// 1.- get metadata about this feed
   333  	testBzzResUrl = fmt.Sprintf("%s/bzz-feed:/%s/", srv.URL, correctManifestAddrHex)
   334  	resp, err = http.Get(testBzzResUrl + "?meta=1")
   335  	if err != nil {
   336  		t.Fatal(err)
   337  	}
   338  	defer resp.Body.Close()
   339  	if resp.StatusCode != http.StatusOK {
   340  		t.Fatalf("Get feed metadata returned %s", resp.Status)
   341  	}
   342  	b, err = ioutil.ReadAll(resp.Body)
   343  	if err != nil {
   344  		t.Fatal(err)
   345  	}
   346  	updateRequest = &feed.Request{}
   347  	if err = updateRequest.UnmarshalJSON(b); err != nil {
   348  		t.Fatalf("Error decoding feed metadata: %s", err)
   349  	}
   350  	updateRequest.SetData(update2Data)
   351  	if err = updateRequest.Sign(signer); err != nil {
   352  		t.Fatal(err)
   353  	}
   354  	testUrl, err = url.Parse(fmt.Sprintf("%s/bzz-feed:/", srv.URL))
   355  	if err != nil {
   356  		t.Fatal(err)
   357  	}
   358  	urlQuery = testUrl.Query()
   359  	body = updateRequest.AppendValues(urlQuery) // this adds all query parameters
   360  	goodQueryParameters := urlQuery.Encode()    // save the query parameters for a second attempt
   361  
   362  	// create bad query parameters in which the signature is missing
   363  	urlQuery.Del("signature")
   364  	testUrl.RawQuery = urlQuery.Encode()
   365  
   366  	// 1st attempt with bad query parameters in which the signature is missing
   367  	resp, err = http.Post(testUrl.String(), "application/octet-stream", bytes.NewReader(body))
   368  	if err != nil {
   369  		t.Fatal(err)
   370  	}
   371  	defer resp.Body.Close()
   372  	expectedCode := http.StatusBadRequest
   373  	if resp.StatusCode != expectedCode {
   374  		t.Fatalf("Update returned %s. Expected %d", resp.Status, expectedCode)
   375  	}
   376  
   377  	// 2nd attempt with bad query parameters in which the signature is of incorrect length
   378  	urlQuery.Set("signature", "0xabcd") // should be 130 hex chars
   379  	resp, err = http.Post(testUrl.String(), "application/octet-stream", bytes.NewReader(body))
   380  	if err != nil {
   381  		t.Fatal(err)
   382  	}
   383  	defer resp.Body.Close()
   384  	expectedCode = http.StatusBadRequest
   385  	if resp.StatusCode != expectedCode {
   386  		t.Fatalf("Update returned %s. Expected %d", resp.Status, expectedCode)
   387  	}
   388  
   389  	// 3rd attempt, with good query parameters:
   390  	testUrl.RawQuery = goodQueryParameters
   391  	resp, err = http.Post(testUrl.String(), "application/octet-stream", bytes.NewReader(body))
   392  	if err != nil {
   393  		t.Fatal(err)
   394  	}
   395  	defer resp.Body.Close()
   396  	expectedCode = http.StatusOK
   397  	if resp.StatusCode != expectedCode {
   398  		t.Fatalf("Update returned %s. Expected %d", resp.Status, expectedCode)
   399  	}
   400  
   401  	// get latest update through bzz-feed directly
   402  	log.Info("get update 1.2")
   403  	testBzzResUrl = fmt.Sprintf("%s/bzz-feed:/%s", srv.URL, correctManifestAddrHex)
   404  	resp, err = http.Get(testBzzResUrl)
   405  	if err != nil {
   406  		t.Fatal(err)
   407  	}
   408  	defer resp.Body.Close()
   409  	if resp.StatusCode != http.StatusOK {
   410  		t.Fatalf("err %s", resp.Status)
   411  	}
   412  	b, err = ioutil.ReadAll(resp.Body)
   413  	if err != nil {
   414  		t.Fatal(err)
   415  	}
   416  	if !bytes.Equal(update2Data, b) {
   417  		t.Fatalf("Expected body '%x', got '%x'", update2Data, b)
   418  	}
   419  
   420  	// test manifest-less queries
   421  	log.Info("get first update in update1Timestamp via direct query")
   422  	query := feed.NewQuery(&updateRequest.Feed, update1Timestamp, lookup.NoClue)
   423  
   424  	urlq, err := url.Parse(fmt.Sprintf("%s/bzz-feed:/", srv.URL))
   425  	if err != nil {
   426  		t.Fatal(err)
   427  	}
   428  
   429  	values := urlq.Query()
   430  	query.AppendValues(values) // this adds feed query parameters
   431  	urlq.RawQuery = values.Encode()
   432  	resp, err = http.Get(urlq.String())
   433  	if err != nil {
   434  		t.Fatal(err)
   435  	}
   436  	defer resp.Body.Close()
   437  	if resp.StatusCode != http.StatusOK {
   438  		t.Fatalf("err %s", resp.Status)
   439  	}
   440  	b, err = ioutil.ReadAll(resp.Body)
   441  	if err != nil {
   442  		t.Fatal(err)
   443  	}
   444  	if !bytes.Equal(update1Data, b) {
   445  		t.Fatalf("Expected body '%x', got '%x'", update1Data, b)
   446  	}
   447  
   448  }
   449  
   450  func TestBzzGetPath(t *testing.T) {
   451  	testBzzGetPath(false, t)
   452  	testBzzGetPath(true, t)
   453  }
   454  
   455  func testBzzGetPath(encrypted bool, t *testing.T) {
   456  	var err error
   457  
   458  	testmanifest := []string{
   459  		`{"entries":[{"path":"b","hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","contentType":"","status":0},{"path":"c","hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","contentType":"","status":0}]}`,
   460  		`{"entries":[{"path":"a","hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","contentType":"","status":0},{"path":"b/","hash":"<key0>","contentType":"application/bzz-manifest+json","status":0}]}`,
   461  		`{"entries":[{"path":"a/","hash":"<key1>","contentType":"application/bzz-manifest+json","status":0}]}`,
   462  	}
   463  
   464  	testrequests := make(map[string]int)
   465  	testrequests["/"] = 2
   466  	testrequests["/a/"] = 1
   467  	testrequests["/a/b/"] = 0
   468  	testrequests["/x"] = 0
   469  	testrequests[""] = 0
   470  
   471  	expectedfailrequests := []string{"", "/x"}
   472  
   473  	reader := [3]*bytes.Reader{}
   474  
   475  	addr := [3]storage.Address{}
   476  
   477  	srv := NewTestSwarmServer(t, serverFunc, nil)
   478  	defer srv.Close()
   479  
   480  	for i, mf := range testmanifest {
   481  		reader[i] = bytes.NewReader([]byte(mf))
   482  		var wait func(context.Context) error
   483  		ctx := context.TODO()
   484  		addr[i], wait, err = srv.FileStore.Store(ctx, reader[i], int64(len(mf)), encrypted)
   485  		if err != nil {
   486  			t.Fatal(err)
   487  		}
   488  		for j := i + 1; j < len(testmanifest); j++ {
   489  			testmanifest[j] = strings.Replace(testmanifest[j], fmt.Sprintf("<key%v>", i), addr[i].Hex(), -1)
   490  		}
   491  		err = wait(ctx)
   492  		if err != nil {
   493  			t.Fatal(err)
   494  		}
   495  	}
   496  
   497  	rootRef := addr[2].Hex()
   498  
   499  	_, err = http.Get(srv.URL + "/bzz-raw:/" + rootRef + "/a")
   500  	if err != nil {
   501  		t.Fatalf("Failed to connect to proxy: %v", err)
   502  	}
   503  
   504  	for k, v := range testrequests {
   505  		var resp *http.Response
   506  		var respbody []byte
   507  
   508  		url := srv.URL + "/bzz-raw:/"
   509  		if k != "" {
   510  			url += rootRef + "/" + k[1:] + "?content_type=text/plain"
   511  		}
   512  		resp, err = http.Get(url)
   513  		if err != nil {
   514  			t.Fatalf("Request failed: %v", err)
   515  		}
   516  		defer resp.Body.Close()
   517  		respbody, err = ioutil.ReadAll(resp.Body)
   518  		if err != nil {
   519  			t.Fatalf("Error while reading response body: %v", err)
   520  		}
   521  
   522  		if string(respbody) != testmanifest[v] {
   523  			isexpectedfailrequest := false
   524  
   525  			for _, r := range expectedfailrequests {
   526  				if k == r {
   527  					isexpectedfailrequest = true
   528  				}
   529  			}
   530  			if !isexpectedfailrequest {
   531  				t.Fatalf("Response body does not match, expected: %v, got %v", testmanifest[v], string(respbody))
   532  			}
   533  		}
   534  	}
   535  
   536  	for k, v := range testrequests {
   537  		var resp *http.Response
   538  		var respbody []byte
   539  
   540  		url := srv.URL + "/bzz-hash:/"
   541  		if k != "" {
   542  			url += rootRef + "/" + k[1:]
   543  		}
   544  		resp, err = http.Get(url)
   545  		if err != nil {
   546  			t.Fatalf("Request failed: %v", err)
   547  		}
   548  		defer resp.Body.Close()
   549  		respbody, err = ioutil.ReadAll(resp.Body)
   550  		if err != nil {
   551  			t.Fatalf("Read request body: %v", err)
   552  		}
   553  
   554  		if string(respbody) != addr[v].Hex() {
   555  			isexpectedfailrequest := false
   556  
   557  			for _, r := range expectedfailrequests {
   558  				if k == r {
   559  					isexpectedfailrequest = true
   560  				}
   561  			}
   562  			if !isexpectedfailrequest {
   563  				t.Fatalf("Response body does not match, expected: %v, got %v", addr[v], string(respbody))
   564  			}
   565  		}
   566  	}
   567  
   568  	ref := addr[2].Hex()
   569  
   570  	for _, c := range []struct {
   571  		path          string
   572  		json          string
   573  		pageFragments []string
   574  	}{
   575  		{
   576  			path: "/",
   577  			json: `{"common_prefixes":["a/"]}`,
   578  			pageFragments: []string{
   579  				fmt.Sprintf("Swarm index of bzz:/%s/", ref),
   580  				`<a class="normal-link" href="a/">a/</a>`,
   581  			},
   582  		},
   583  		{
   584  			path: "/a/",
   585  			json: `{"common_prefixes":["a/b/"],"entries":[{"hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","path":"a/a","mod_time":"0001-01-01T00:00:00Z"}]}`,
   586  			pageFragments: []string{
   587  				fmt.Sprintf("Swarm index of bzz:/%s/a/", ref),
   588  				`<a class="normal-link" href="b/">b/</a>`,
   589  				fmt.Sprintf(`<a class="normal-link" href="/bzz:/%s/a/a">a</a>`, ref),
   590  			},
   591  		},
   592  		{
   593  			path: "/a/b/",
   594  			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"}]}`,
   595  			pageFragments: []string{
   596  				fmt.Sprintf("Swarm index of bzz:/%s/a/b/", ref),
   597  				fmt.Sprintf(`<a class="normal-link" href="/bzz:/%s/a/b/b">b</a>`, ref),
   598  				fmt.Sprintf(`<a class="normal-link" href="/bzz:/%s/a/b/c">c</a>`, ref),
   599  			},
   600  		},
   601  		{
   602  			path: "/x",
   603  		},
   604  		{
   605  			path: "",
   606  		},
   607  	} {
   608  		k := c.path
   609  		url := srv.URL + "/bzz-list:/"
   610  		if k != "" {
   611  			url += rootRef + "/" + k[1:]
   612  		}
   613  		t.Run("json list "+c.path, func(t *testing.T) {
   614  			resp, err := http.Get(url)
   615  			if err != nil {
   616  				t.Fatalf("HTTP request: %v", err)
   617  			}
   618  			defer resp.Body.Close()
   619  			respbody, err := ioutil.ReadAll(resp.Body)
   620  			if err != nil {
   621  				t.Fatalf("Read response body: %v", err)
   622  			}
   623  
   624  			body := strings.TrimSpace(string(respbody))
   625  			if body != c.json {
   626  				isexpectedfailrequest := false
   627  
   628  				for _, r := range expectedfailrequests {
   629  					if k == r {
   630  						isexpectedfailrequest = true
   631  					}
   632  				}
   633  				if !isexpectedfailrequest {
   634  					t.Errorf("Response list body %q does not match, expected: %v, got %v", k, c.json, body)
   635  				}
   636  			}
   637  		})
   638  		t.Run("html list "+c.path, func(t *testing.T) {
   639  			req, err := http.NewRequest(http.MethodGet, url, nil)
   640  			if err != nil {
   641  				t.Fatalf("New request: %v", err)
   642  			}
   643  			req.Header.Set("Accept", "text/html")
   644  			resp, err := http.DefaultClient.Do(req)
   645  			if err != nil {
   646  				t.Fatalf("HTTP request: %v", err)
   647  			}
   648  			defer resp.Body.Close()
   649  			b, err := ioutil.ReadAll(resp.Body)
   650  			if err != nil {
   651  				t.Fatalf("Read response body: %v", err)
   652  			}
   653  
   654  			body := string(b)
   655  
   656  			for _, f := range c.pageFragments {
   657  				if !strings.Contains(body, f) {
   658  					isexpectedfailrequest := false
   659  
   660  					for _, r := range expectedfailrequests {
   661  						if k == r {
   662  							isexpectedfailrequest = true
   663  						}
   664  					}
   665  					if !isexpectedfailrequest {
   666  						t.Errorf("Response list body %q does not contain %q: body %q", k, f, body)
   667  					}
   668  				}
   669  			}
   670  		})
   671  	}
   672  
   673  	nonhashtests := []string{
   674  		srv.URL + "/bzz:/name",
   675  		srv.URL + "/bzz-immutable:/nonhash",
   676  		srv.URL + "/bzz-raw:/nonhash",
   677  		srv.URL + "/bzz-list:/nonhash",
   678  		srv.URL + "/bzz-hash:/nonhash",
   679  	}
   680  
   681  	nonhashresponses := []string{
   682  		`cannot resolve name: no DNS to resolve name: "name"`,
   683  		`cannot resolve nonhash: no DNS to resolve name: "nonhash"`,
   684  		`cannot resolve nonhash: no DNS to resolve name: "nonhash"`,
   685  		`cannot resolve nonhash: no DNS to resolve name: "nonhash"`,
   686  		`cannot resolve nonhash: no DNS to resolve name: "nonhash"`,
   687  	}
   688  
   689  	for i, url := range nonhashtests {
   690  		var resp *http.Response
   691  		var respbody []byte
   692  
   693  		resp, err = http.Get(url)
   694  
   695  		if err != nil {
   696  			t.Fatalf("Request failed: %v", err)
   697  		}
   698  		defer resp.Body.Close()
   699  		respbody, err = ioutil.ReadAll(resp.Body)
   700  		if err != nil {
   701  			t.Fatalf("ReadAll failed: %v", err)
   702  		}
   703  		if !strings.Contains(string(respbody), nonhashresponses[i]) {
   704  			t.Fatalf("Non-Hash response body does not match, expected: %v, got: %v", nonhashresponses[i], string(respbody))
   705  		}
   706  	}
   707  }
   708  
   709  func TestBzzTar(t *testing.T) {
   710  	testBzzTar(false, t)
   711  	testBzzTar(true, t)
   712  }
   713  
   714  func testBzzTar(encrypted bool, t *testing.T) {
   715  	srv := NewTestSwarmServer(t, serverFunc, nil)
   716  	defer srv.Close()
   717  	fileNames := []string{"tmp1.txt", "tmp2.lock", "tmp3.rtf"}
   718  	fileContents := []string{"tmp1textfilevalue", "tmp2lockfilelocked", "tmp3isjustaplaintextfile"}
   719  
   720  	buf := &bytes.Buffer{}
   721  	tw := tar.NewWriter(buf)
   722  	defer tw.Close()
   723  
   724  	for i, v := range fileNames {
   725  		size := int64(len(fileContents[i]))
   726  		hdr := &tar.Header{
   727  			Name:    v,
   728  			Mode:    0644,
   729  			Size:    size,
   730  			ModTime: time.Now(),
   731  			Xattrs: map[string]string{
   732  				"user.swarm.content-type": "text/plain",
   733  			},
   734  		}
   735  		if err := tw.WriteHeader(hdr); err != nil {
   736  			t.Fatal(err)
   737  		}
   738  
   739  		// copy the file into the tar stream
   740  		n, err := io.Copy(tw, bytes.NewBufferString(fileContents[i]))
   741  		if err != nil {
   742  			t.Fatal(err)
   743  		} else if n != size {
   744  			t.Fatal("size mismatch")
   745  		}
   746  	}
   747  
   748  	//post tar stream
   749  	url := srv.URL + "/bzz:/"
   750  	if encrypted {
   751  		url = url + "encrypt"
   752  	}
   753  	req, err := http.NewRequest("POST", url, buf)
   754  	if err != nil {
   755  		t.Fatal(err)
   756  	}
   757  	req.Header.Add("Content-Type", "application/x-tar")
   758  	client := &http.Client{}
   759  	resp2, err := client.Do(req)
   760  	if err != nil {
   761  		t.Fatal(err)
   762  	}
   763  	if resp2.StatusCode != http.StatusOK {
   764  		t.Fatalf("err %s", resp2.Status)
   765  	}
   766  	swarmHash, err := ioutil.ReadAll(resp2.Body)
   767  	resp2.Body.Close()
   768  	if err != nil {
   769  		t.Fatal(err)
   770  	}
   771  
   772  	// now do a GET to get a tarball back
   773  	req, err = http.NewRequest("GET", fmt.Sprintf(srv.URL+"/bzz:/%s", string(swarmHash)), nil)
   774  	if err != nil {
   775  		t.Fatal(err)
   776  	}
   777  	req.Header.Add("Accept", "application/x-tar")
   778  	resp2, err = client.Do(req)
   779  	if err != nil {
   780  		t.Fatal(err)
   781  	}
   782  	defer resp2.Body.Close()
   783  
   784  	if h := resp2.Header.Get("Content-Type"); h != "application/x-tar" {
   785  		t.Fatalf("Content-Type header expected: application/x-tar, got: %s", h)
   786  	}
   787  
   788  	expectedFileName := string(swarmHash) + ".tar"
   789  	expectedContentDisposition := fmt.Sprintf("inline; filename=\"%s\"", expectedFileName)
   790  	if h := resp2.Header.Get("Content-Disposition"); h != expectedContentDisposition {
   791  		t.Fatalf("Content-Disposition header expected: %s, got: %s", expectedContentDisposition, h)
   792  	}
   793  
   794  	file, err := ioutil.TempFile("", "swarm-downloaded-tarball")
   795  	if err != nil {
   796  		t.Fatal(err)
   797  	}
   798  	defer os.Remove(file.Name())
   799  	_, err = io.Copy(file, resp2.Body)
   800  	if err != nil {
   801  		t.Fatalf("error getting tarball: %v", err)
   802  	}
   803  	file.Sync()
   804  	file.Close()
   805  
   806  	tarFileHandle, err := os.Open(file.Name())
   807  	if err != nil {
   808  		t.Fatal(err)
   809  	}
   810  	tr := tar.NewReader(tarFileHandle)
   811  
   812  	for {
   813  		hdr, err := tr.Next()
   814  		if err == io.EOF {
   815  			break
   816  		} else if err != nil {
   817  			t.Fatalf("error reading tar stream: %s", err)
   818  		}
   819  		bb := make([]byte, hdr.Size)
   820  		_, err = tr.Read(bb)
   821  		if err != nil && err != io.EOF {
   822  			t.Fatal(err)
   823  		}
   824  		passed := false
   825  		for i, v := range fileNames {
   826  			if v == hdr.Name {
   827  				if string(bb) == fileContents[i] {
   828  					passed = true
   829  					break
   830  				}
   831  			}
   832  		}
   833  		if !passed {
   834  			t.Fatalf("file %s did not pass content assertion", hdr.Name)
   835  		}
   836  	}
   837  }
   838  
   839  // TestBzzRootRedirect tests that getting the root path of a manifest without
   840  // a trailing slash gets redirected to include the trailing slash so that
   841  // relative URLs work as expected.
   842  func TestBzzRootRedirect(t *testing.T) {
   843  	testBzzRootRedirect(false, t)
   844  }
   845  func TestBzzRootRedirectEncrypted(t *testing.T) {
   846  	testBzzRootRedirect(true, t)
   847  }
   848  
   849  func testBzzRootRedirect(toEncrypt bool, t *testing.T) {
   850  	srv := NewTestSwarmServer(t, serverFunc, nil)
   851  	defer srv.Close()
   852  
   853  	// create a manifest with some data at the root path
   854  	client := swarm.NewClient(srv.URL)
   855  	data := []byte("data")
   856  	file := &swarm.File{
   857  		ReadCloser: ioutil.NopCloser(bytes.NewReader(data)),
   858  		ManifestEntry: api.ManifestEntry{
   859  			Path:        "",
   860  			ContentType: "text/plain",
   861  			Size:        int64(len(data)),
   862  		},
   863  	}
   864  	hash, err := client.Upload(file, "", toEncrypt)
   865  	if err != nil {
   866  		t.Fatal(err)
   867  	}
   868  
   869  	// define a CheckRedirect hook which ensures there is only a single
   870  	// redirect to the correct URL
   871  	redirected := false
   872  	httpClient := http.Client{
   873  		CheckRedirect: func(req *http.Request, via []*http.Request) error {
   874  			if redirected {
   875  				return errors.New("too many redirects")
   876  			}
   877  			redirected = true
   878  			expectedPath := "/bzz:/" + hash + "/"
   879  			if req.URL.Path != expectedPath {
   880  				return fmt.Errorf("expected redirect to %q, got %q", expectedPath, req.URL.Path)
   881  			}
   882  			return nil
   883  		},
   884  	}
   885  
   886  	// perform the GET request and assert the response
   887  	res, err := httpClient.Get(srv.URL + "/bzz:/" + hash)
   888  	if err != nil {
   889  		t.Fatal(err)
   890  	}
   891  	defer res.Body.Close()
   892  	if !redirected {
   893  		t.Fatal("expected GET /bzz:/<hash> to redirect to /bzz:/<hash>/ but it didn't")
   894  	}
   895  	gotData, err := ioutil.ReadAll(res.Body)
   896  	if err != nil {
   897  		t.Fatal(err)
   898  	}
   899  	if !bytes.Equal(gotData, data) {
   900  		t.Fatalf("expected response to equal %q, got %q", data, gotData)
   901  	}
   902  }
   903  
   904  func TestMethodsNotAllowed(t *testing.T) {
   905  	srv := NewTestSwarmServer(t, serverFunc, nil)
   906  	defer srv.Close()
   907  	databytes := "bar"
   908  	for _, c := range []struct {
   909  		url  string
   910  		code int
   911  	}{
   912  		{
   913  			url:  fmt.Sprintf("%s/bzz-list:/", srv.URL),
   914  			code: http.StatusMethodNotAllowed,
   915  		}, {
   916  			url:  fmt.Sprintf("%s/bzz-hash:/", srv.URL),
   917  			code: http.StatusMethodNotAllowed,
   918  		},
   919  		{
   920  			url:  fmt.Sprintf("%s/bzz-immutable:/", srv.URL),
   921  			code: http.StatusMethodNotAllowed,
   922  		},
   923  	} {
   924  		res, _ := http.Post(c.url, "text/plain", bytes.NewReader([]byte(databytes)))
   925  		if res.StatusCode != c.code {
   926  			t.Fatalf("should have failed. requested url: %s, expected code %d, got %d", c.url, c.code, res.StatusCode)
   927  		}
   928  	}
   929  
   930  }
   931  
   932  func httpDo(httpMethod string, url string, reqBody io.Reader, headers map[string]string, verbose bool, t *testing.T) (*http.Response, string) {
   933  	// Build the Request
   934  	req, err := http.NewRequest(httpMethod, url, reqBody)
   935  	if err != nil {
   936  		t.Fatal(err)
   937  	}
   938  	for key, value := range headers {
   939  		req.Header.Set(key, value)
   940  	}
   941  	if verbose {
   942  		t.Log(req.Method, req.URL, req.Header, req.Body)
   943  	}
   944  
   945  	// Send Request out
   946  	httpClient := &http.Client{}
   947  	res, err := httpClient.Do(req)
   948  	if err != nil {
   949  		t.Fatal(err)
   950  	}
   951  
   952  	// Read the HTTP Body
   953  	buffer, err := ioutil.ReadAll(res.Body)
   954  	if err != nil {
   955  		t.Fatal(err)
   956  	}
   957  	defer res.Body.Close()
   958  	body := string(buffer)
   959  
   960  	return res, body
   961  }
   962  
   963  func TestGet(t *testing.T) {
   964  	srv := NewTestSwarmServer(t, serverFunc, nil)
   965  	defer srv.Close()
   966  
   967  	for _, testCase := range []struct {
   968  		uri                string
   969  		method             string
   970  		headers            map[string]string
   971  		expectedStatusCode int
   972  		assertResponseBody string
   973  		verbose            bool
   974  	}{
   975  		{
   976  			uri:                fmt.Sprintf("%s/", srv.URL),
   977  			method:             "GET",
   978  			headers:            map[string]string{"Accept": "text/html"},
   979  			expectedStatusCode: http.StatusOK,
   980  			assertResponseBody: "Swarm: Serverless Hosting Incentivised Peer-To-Peer Storage And Content Distribution",
   981  			verbose:            false,
   982  		},
   983  		{
   984  			uri:                fmt.Sprintf("%s/", srv.URL),
   985  			method:             "GET",
   986  			headers:            map[string]string{"Accept": "application/json"},
   987  			expectedStatusCode: http.StatusOK,
   988  			assertResponseBody: "Swarm: Please request a valid ENS or swarm hash with the appropriate bzz scheme",
   989  			verbose:            false,
   990  		},
   991  		{
   992  			uri:                fmt.Sprintf("%s/robots.txt", srv.URL),
   993  			method:             "GET",
   994  			headers:            map[string]string{"Accept": "text/html"},
   995  			expectedStatusCode: http.StatusOK,
   996  			assertResponseBody: "User-agent: *\nDisallow: /",
   997  			verbose:            false,
   998  		},
   999  		{
  1000  			uri:                fmt.Sprintf("%s/nonexistent_path", srv.URL),
  1001  			method:             "GET",
  1002  			headers:            map[string]string{},
  1003  			expectedStatusCode: http.StatusNotFound,
  1004  			verbose:            false,
  1005  		},
  1006  		{
  1007  			uri:                fmt.Sprintf("%s/bzz:asdf/", srv.URL),
  1008  			method:             "GET",
  1009  			headers:            map[string]string{},
  1010  			expectedStatusCode: http.StatusNotFound,
  1011  			verbose:            false,
  1012  		},
  1013  		{
  1014  			uri:                fmt.Sprintf("%s/tbz2/", srv.URL),
  1015  			method:             "GET",
  1016  			headers:            map[string]string{},
  1017  			expectedStatusCode: http.StatusNotFound,
  1018  			verbose:            false,
  1019  		},
  1020  		{
  1021  			uri:                fmt.Sprintf("%s/bzz-rack:/", srv.URL),
  1022  			method:             "GET",
  1023  			headers:            map[string]string{},
  1024  			expectedStatusCode: http.StatusNotFound,
  1025  			verbose:            false,
  1026  		},
  1027  		{
  1028  			uri:                fmt.Sprintf("%s/bzz-ls", srv.URL),
  1029  			method:             "GET",
  1030  			headers:            map[string]string{},
  1031  			expectedStatusCode: http.StatusNotFound,
  1032  			verbose:            false,
  1033  		}} {
  1034  		t.Run("GET "+testCase.uri, func(t *testing.T) {
  1035  			res, body := httpDo(testCase.method, testCase.uri, nil, testCase.headers, testCase.verbose, t)
  1036  			if res.StatusCode != testCase.expectedStatusCode {
  1037  				t.Fatalf("expected status code %d but got %d", testCase.expectedStatusCode, res.StatusCode)
  1038  			}
  1039  			if testCase.assertResponseBody != "" && !strings.Contains(body, testCase.assertResponseBody) {
  1040  				t.Fatalf("expected response to be: %s but got: %s", testCase.assertResponseBody, body)
  1041  			}
  1042  		})
  1043  	}
  1044  }
  1045  
  1046  func TestModify(t *testing.T) {
  1047  	srv := NewTestSwarmServer(t, serverFunc, nil)
  1048  	defer srv.Close()
  1049  
  1050  	swarmClient := swarm.NewClient(srv.URL)
  1051  	data := []byte("data")
  1052  	file := &swarm.File{
  1053  		ReadCloser: ioutil.NopCloser(bytes.NewReader(data)),
  1054  		ManifestEntry: api.ManifestEntry{
  1055  			Path:        "",
  1056  			ContentType: "text/plain",
  1057  			Size:        int64(len(data)),
  1058  		},
  1059  	}
  1060  
  1061  	hash, err := swarmClient.Upload(file, "", false)
  1062  	if err != nil {
  1063  		t.Fatal(err)
  1064  	}
  1065  
  1066  	for _, testCase := range []struct {
  1067  		uri                   string
  1068  		method                string
  1069  		headers               map[string]string
  1070  		requestBody           []byte
  1071  		expectedStatusCode    int
  1072  		assertResponseBody    string
  1073  		assertResponseHeaders map[string]string
  1074  		verbose               bool
  1075  	}{
  1076  		{
  1077  			uri:                fmt.Sprintf("%s/bzz:/%s", srv.URL, hash),
  1078  			method:             "DELETE",
  1079  			headers:            map[string]string{},
  1080  			expectedStatusCode: http.StatusOK,
  1081  			assertResponseBody: "8b634aea26eec353ac0ecbec20c94f44d6f8d11f38d4578a4c207a84c74ef731",
  1082  			verbose:            false,
  1083  		},
  1084  		{
  1085  			uri:                fmt.Sprintf("%s/bzz:/%s", srv.URL, hash),
  1086  			method:             "PUT",
  1087  			headers:            map[string]string{},
  1088  			expectedStatusCode: http.StatusMethodNotAllowed,
  1089  			verbose:            false,
  1090  		},
  1091  		{
  1092  			uri:                fmt.Sprintf("%s/bzz-raw:/%s", srv.URL, hash),
  1093  			method:             "PUT",
  1094  			headers:            map[string]string{},
  1095  			expectedStatusCode: http.StatusMethodNotAllowed,
  1096  			verbose:            false,
  1097  		},
  1098  		{
  1099  			uri:                fmt.Sprintf("%s/bzz:/%s", srv.URL, hash),
  1100  			method:             "PATCH",
  1101  			headers:            map[string]string{},
  1102  			expectedStatusCode: http.StatusMethodNotAllowed,
  1103  			verbose:            false,
  1104  		},
  1105  		{
  1106  			uri:                   fmt.Sprintf("%s/bzz-raw:/", srv.URL),
  1107  			method:                "POST",
  1108  			headers:               map[string]string{},
  1109  			requestBody:           []byte("POSTdata"),
  1110  			expectedStatusCode:    http.StatusOK,
  1111  			assertResponseHeaders: map[string]string{"Content-Length": "64"},
  1112  			verbose:               false,
  1113  		},
  1114  		{
  1115  			uri:                   fmt.Sprintf("%s/bzz-raw:/encrypt", srv.URL),
  1116  			method:                "POST",
  1117  			headers:               map[string]string{},
  1118  			requestBody:           []byte("POSTdata"),
  1119  			expectedStatusCode:    http.StatusOK,
  1120  			assertResponseHeaders: map[string]string{"Content-Length": "128"},
  1121  			verbose:               false,
  1122  		},
  1123  	} {
  1124  		t.Run(testCase.method+" "+testCase.uri, func(t *testing.T) {
  1125  			reqBody := bytes.NewReader(testCase.requestBody)
  1126  			res, body := httpDo(testCase.method, testCase.uri, reqBody, testCase.headers, testCase.verbose, t)
  1127  
  1128  			if res.StatusCode != testCase.expectedStatusCode {
  1129  				t.Fatalf("expected status code %d but got %d, %s", testCase.expectedStatusCode, res.StatusCode, body)
  1130  			}
  1131  			if testCase.assertResponseBody != "" && !strings.Contains(body, testCase.assertResponseBody) {
  1132  				t.Log(body)
  1133  				t.Fatalf("expected response %s but got %s", testCase.assertResponseBody, body)
  1134  			}
  1135  			for key, value := range testCase.assertResponseHeaders {
  1136  				if res.Header.Get(key) != value {
  1137  					t.Logf("expected %s=%s in HTTP response header but got %s", key, value, res.Header.Get(key))
  1138  				}
  1139  			}
  1140  		})
  1141  	}
  1142  }
  1143  
  1144  func TestMultiPartUpload(t *testing.T) {
  1145  	// POST /bzz:/ Content-Type: multipart/form-data
  1146  	verbose := false
  1147  	// Setup Swarm
  1148  	srv := NewTestSwarmServer(t, serverFunc, nil)
  1149  	defer srv.Close()
  1150  
  1151  	url := fmt.Sprintf("%s/bzz:/", srv.URL)
  1152  
  1153  	buf := new(bytes.Buffer)
  1154  	form := multipart.NewWriter(buf)
  1155  	form.WriteField("name", "John Doe")
  1156  	file1, _ := form.CreateFormFile("cv", "cv.txt")
  1157  	file1.Write([]byte("John Doe's Credentials"))
  1158  	file2, _ := form.CreateFormFile("profile_picture", "profile.jpg")
  1159  	file2.Write([]byte("imaginethisisjpegdata"))
  1160  	form.Close()
  1161  
  1162  	headers := map[string]string{
  1163  		"Content-Type":   form.FormDataContentType(),
  1164  		"Content-Length": strconv.Itoa(buf.Len()),
  1165  	}
  1166  	res, body := httpDo("POST", url, buf, headers, verbose, t)
  1167  
  1168  	if res.StatusCode != http.StatusOK {
  1169  		t.Fatalf("expected POST multipart/form-data to return 200, but it returned %d", res.StatusCode)
  1170  	}
  1171  	if len(body) != 64 {
  1172  		t.Fatalf("expected POST multipart/form-data to return a 64 char manifest but the answer was %d chars long", len(body))
  1173  	}
  1174  }
  1175  
  1176  // TestBzzGetFileWithResolver tests fetching a file using a mocked ENS resolver
  1177  func TestBzzGetFileWithResolver(t *testing.T) {
  1178  	resolver := newTestResolveValidator("")
  1179  	srv := NewTestSwarmServer(t, serverFunc, resolver)
  1180  	defer srv.Close()
  1181  	fileNames := []string{"dir1/tmp1.txt", "dir2/tmp2.lock", "dir3/tmp3.rtf"}
  1182  	fileContents := []string{"tmp1textfilevalue", "tmp2lockfilelocked", "tmp3isjustaplaintextfile"}
  1183  
  1184  	buf := &bytes.Buffer{}
  1185  	tw := tar.NewWriter(buf)
  1186  
  1187  	for i, v := range fileNames {
  1188  		size := len(fileContents[i])
  1189  		hdr := &tar.Header{
  1190  			Name:    v,
  1191  			Mode:    0644,
  1192  			Size:    int64(size),
  1193  			ModTime: time.Now(),
  1194  			Xattrs: map[string]string{
  1195  				"user.swarm.content-type": "text/plain",
  1196  			},
  1197  		}
  1198  		if err := tw.WriteHeader(hdr); err != nil {
  1199  			t.Fatal(err)
  1200  		}
  1201  
  1202  		// copy the file into the tar stream
  1203  		n, err := io.WriteString(tw, fileContents[i])
  1204  		if err != nil {
  1205  			t.Fatal(err)
  1206  		} else if n != size {
  1207  			t.Fatal("size mismatch")
  1208  		}
  1209  	}
  1210  
  1211  	if err := tw.Close(); err != nil {
  1212  		t.Fatal(err)
  1213  	}
  1214  
  1215  	//post tar stream
  1216  	url := srv.URL + "/bzz:/"
  1217  
  1218  	req, err := http.NewRequest("POST", url, buf)
  1219  	if err != nil {
  1220  		t.Fatal(err)
  1221  	}
  1222  	req.Header.Add("Content-Type", "application/x-tar")
  1223  	client := &http.Client{}
  1224  	serverResponse, err := client.Do(req)
  1225  	if err != nil {
  1226  		t.Fatal(err)
  1227  	}
  1228  	if serverResponse.StatusCode != http.StatusOK {
  1229  		t.Fatalf("err %s", serverResponse.Status)
  1230  	}
  1231  	swarmHash, err := ioutil.ReadAll(serverResponse.Body)
  1232  	serverResponse.Body.Close()
  1233  	if err != nil {
  1234  		t.Fatal(err)
  1235  	}
  1236  	// set the resolved hash to be the swarm hash of what we've just uploaded
  1237  	hash := common.HexToHash(string(swarmHash))
  1238  	resolver.hash = &hash
  1239  	for _, v := range []struct {
  1240  		addr                string
  1241  		path                string
  1242  		expectedStatusCode  int
  1243  		expectedContentType string
  1244  		expectedFileName    string
  1245  	}{
  1246  		{
  1247  			addr:                string(swarmHash),
  1248  			path:                fileNames[0],
  1249  			expectedStatusCode:  http.StatusOK,
  1250  			expectedContentType: "text/plain",
  1251  			expectedFileName:    path.Base(fileNames[0]),
  1252  		},
  1253  		{
  1254  			addr:                "somebogusensname",
  1255  			path:                fileNames[0],
  1256  			expectedStatusCode:  http.StatusOK,
  1257  			expectedContentType: "text/plain",
  1258  			expectedFileName:    path.Base(fileNames[0]),
  1259  		},
  1260  	} {
  1261  		req, err := http.NewRequest("GET", fmt.Sprintf(srv.URL+"/bzz:/%s/%s", v.addr, v.path), nil)
  1262  		if err != nil {
  1263  			t.Fatal(err)
  1264  		}
  1265  		serverResponse, err := client.Do(req)
  1266  		if err != nil {
  1267  			t.Fatal(err)
  1268  		}
  1269  		defer serverResponse.Body.Close()
  1270  		if serverResponse.StatusCode != v.expectedStatusCode {
  1271  			t.Fatalf("expected %d, got %d", v.expectedStatusCode, serverResponse.StatusCode)
  1272  		}
  1273  
  1274  		if h := serverResponse.Header.Get("Content-Type"); h != v.expectedContentType {
  1275  			t.Fatalf("Content-Type header expected: %s, got %s", v.expectedContentType, h)
  1276  		}
  1277  
  1278  		expectedContentDisposition := fmt.Sprintf("inline; filename=\"%s\"", v.expectedFileName)
  1279  		if h := serverResponse.Header.Get("Content-Disposition"); h != expectedContentDisposition {
  1280  			t.Fatalf("Content-Disposition header expected: %s, got: %s", expectedContentDisposition, h)
  1281  		}
  1282  
  1283  	}
  1284  }
  1285  
  1286  // testResolver implements the Resolver interface and either returns the given
  1287  // hash if it is set, or returns a "name not found" error
  1288  type testResolveValidator struct {
  1289  	hash *common.Hash
  1290  }
  1291  
  1292  func newTestResolveValidator(addr string) *testResolveValidator {
  1293  	r := &testResolveValidator{}
  1294  	if addr != "" {
  1295  		hash := common.HexToHash(addr)
  1296  		r.hash = &hash
  1297  	}
  1298  	return r
  1299  }
  1300  
  1301  func (t *testResolveValidator) Resolve(addr string) (common.Hash, error) {
  1302  	if t.hash == nil {
  1303  		return common.Hash{}, fmt.Errorf("DNS name not found: %q", addr)
  1304  	}
  1305  	return *t.hash, nil
  1306  }
  1307  
  1308  func (t *testResolveValidator) Owner(node [32]byte) (addr common.Address, err error) {
  1309  	return
  1310  }
  1311  func (t *testResolveValidator) HeaderByNumber(context.Context, *big.Int) (header *types.Header, err error) {
  1312  	return
  1313  }