github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/swarm/api/client/client_test.go (about) 1 // Copyright 2017 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum 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-ethereum 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-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package client 18 19 import ( 20 "bytes" 21 "io/ioutil" 22 "os" 23 "path/filepath" 24 "reflect" 25 "sort" 26 "testing" 27 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/crypto" 30 "github.com/ethereum/go-ethereum/swarm/api" 31 swarmhttp "github.com/ethereum/go-ethereum/swarm/api/http" 32 "github.com/ethereum/go-ethereum/swarm/storage" 33 "github.com/ethereum/go-ethereum/swarm/storage/feed" 34 "github.com/ethereum/go-ethereum/swarm/storage/feed/lookup" 35 ) 36 37 func serverFunc(api *api.API) swarmhttp.TestServer { 38 return swarmhttp.NewServer(api, "") 39 } 40 41 // TestClientUploadDownloadRaw test uploading and downloading raw data to swarm 42 func TestClientUploadDownloadRaw(t *testing.T) { 43 testClientUploadDownloadRaw(false, t) 44 } 45 func TestClientUploadDownloadRawEncrypted(t *testing.T) { 46 testClientUploadDownloadRaw(true, t) 47 } 48 49 func testClientUploadDownloadRaw(toEncrypt bool, t *testing.T) { 50 srv := swarmhttp.NewTestSwarmServer(t, serverFunc, nil) 51 defer srv.Close() 52 53 client := NewClient(srv.URL) 54 55 // upload some raw data 56 data := []byte("foo123") 57 hash, err := client.UploadRaw(bytes.NewReader(data), int64(len(data)), toEncrypt) 58 if err != nil { 59 t.Fatal(err) 60 } 61 62 // check we can download the same data 63 res, isEncrypted, err := client.DownloadRaw(hash) 64 if err != nil { 65 t.Fatal(err) 66 } 67 if isEncrypted != toEncrypt { 68 t.Fatalf("Expected encyption status %v got %v", toEncrypt, isEncrypted) 69 } 70 defer res.Close() 71 gotData, err := ioutil.ReadAll(res) 72 if err != nil { 73 t.Fatal(err) 74 } 75 if !bytes.Equal(gotData, data) { 76 t.Fatalf("expected downloaded data to be %q, got %q", data, gotData) 77 } 78 } 79 80 // TestClientUploadDownloadFiles test uploading and downloading files to swarm 81 // manifests 82 func TestClientUploadDownloadFiles(t *testing.T) { 83 testClientUploadDownloadFiles(false, t) 84 } 85 86 func TestClientUploadDownloadFilesEncrypted(t *testing.T) { 87 testClientUploadDownloadFiles(true, t) 88 } 89 90 func testClientUploadDownloadFiles(toEncrypt bool, t *testing.T) { 91 srv := swarmhttp.NewTestSwarmServer(t, serverFunc, nil) 92 defer srv.Close() 93 94 client := NewClient(srv.URL) 95 upload := func(manifest, path string, data []byte) string { 96 file := &File{ 97 ReadCloser: ioutil.NopCloser(bytes.NewReader(data)), 98 ManifestEntry: api.ManifestEntry{ 99 Path: path, 100 ContentType: "text/plain", 101 Size: int64(len(data)), 102 }, 103 } 104 hash, err := client.Upload(file, manifest, toEncrypt) 105 if err != nil { 106 t.Fatal(err) 107 } 108 return hash 109 } 110 checkDownload := func(manifest, path string, expected []byte) { 111 file, err := client.Download(manifest, path) 112 if err != nil { 113 t.Fatal(err) 114 } 115 defer file.Close() 116 if file.Size != int64(len(expected)) { 117 t.Fatalf("expected downloaded file to be %d bytes, got %d", len(expected), file.Size) 118 } 119 if file.ContentType != "text/plain" { 120 t.Fatalf("expected downloaded file to have type %q, got %q", "text/plain", file.ContentType) 121 } 122 data, err := ioutil.ReadAll(file) 123 if err != nil { 124 t.Fatal(err) 125 } 126 if !bytes.Equal(data, expected) { 127 t.Fatalf("expected downloaded data to be %q, got %q", expected, data) 128 } 129 } 130 131 // upload a file to the root of a manifest 132 rootData := []byte("some-data") 133 rootHash := upload("", "", rootData) 134 135 // check we can download the root file 136 checkDownload(rootHash, "", rootData) 137 138 // upload another file to the same manifest 139 otherData := []byte("some-other-data") 140 newHash := upload(rootHash, "some/other/path", otherData) 141 142 // check we can download both files from the new manifest 143 checkDownload(newHash, "", rootData) 144 checkDownload(newHash, "some/other/path", otherData) 145 146 // replace the root file with different data 147 newHash = upload(newHash, "", otherData) 148 149 // check both files have the other data 150 checkDownload(newHash, "", otherData) 151 checkDownload(newHash, "some/other/path", otherData) 152 } 153 154 var testDirFiles = []string{ 155 "file1.txt", 156 "file2.txt", 157 "dir1/file3.txt", 158 "dir1/file4.txt", 159 "dir2/file5.txt", 160 "dir2/dir3/file6.txt", 161 "dir2/dir4/file7.txt", 162 "dir2/dir4/file8.txt", 163 } 164 165 func newTestDirectory(t *testing.T) string { 166 dir, err := ioutil.TempDir("", "swarm-client-test") 167 if err != nil { 168 t.Fatal(err) 169 } 170 171 for _, file := range testDirFiles { 172 path := filepath.Join(dir, file) 173 if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { 174 os.RemoveAll(dir) 175 t.Fatalf("error creating dir for %s: %s", path, err) 176 } 177 if err := ioutil.WriteFile(path, []byte(file), 0644); err != nil { 178 os.RemoveAll(dir) 179 t.Fatalf("error writing file %s: %s", path, err) 180 } 181 } 182 183 return dir 184 } 185 186 // TestClientUploadDownloadDirectory tests uploading and downloading a 187 // directory of files to a swarm manifest 188 func TestClientUploadDownloadDirectory(t *testing.T) { 189 srv := swarmhttp.NewTestSwarmServer(t, serverFunc, nil) 190 defer srv.Close() 191 192 dir := newTestDirectory(t) 193 defer os.RemoveAll(dir) 194 195 // upload the directory 196 client := NewClient(srv.URL) 197 defaultPath := testDirFiles[0] 198 hash, err := client.UploadDirectory(dir, defaultPath, "", false) 199 if err != nil { 200 t.Fatalf("error uploading directory: %s", err) 201 } 202 203 // check we can download the individual files 204 checkDownloadFile := func(path string, expected []byte) { 205 file, err := client.Download(hash, path) 206 if err != nil { 207 t.Fatal(err) 208 } 209 defer file.Close() 210 data, err := ioutil.ReadAll(file) 211 if err != nil { 212 t.Fatal(err) 213 } 214 if !bytes.Equal(data, expected) { 215 t.Fatalf("expected data to be %q, got %q", expected, data) 216 } 217 } 218 for _, file := range testDirFiles { 219 checkDownloadFile(file, []byte(file)) 220 } 221 222 // check we can download the default path 223 checkDownloadFile("", []byte(testDirFiles[0])) 224 225 // check we can download the directory 226 tmp, err := ioutil.TempDir("", "swarm-client-test") 227 if err != nil { 228 t.Fatal(err) 229 } 230 defer os.RemoveAll(tmp) 231 if err := client.DownloadDirectory(hash, "", tmp, ""); err != nil { 232 t.Fatal(err) 233 } 234 for _, file := range testDirFiles { 235 data, err := ioutil.ReadFile(filepath.Join(tmp, file)) 236 if err != nil { 237 t.Fatal(err) 238 } 239 if !bytes.Equal(data, []byte(file)) { 240 t.Fatalf("expected data to be %q, got %q", file, data) 241 } 242 } 243 } 244 245 // TestClientFileList tests listing files in a swarm manifest 246 func TestClientFileList(t *testing.T) { 247 testClientFileList(false, t) 248 } 249 250 func TestClientFileListEncrypted(t *testing.T) { 251 testClientFileList(true, t) 252 } 253 254 func testClientFileList(toEncrypt bool, t *testing.T) { 255 srv := swarmhttp.NewTestSwarmServer(t, serverFunc, nil) 256 defer srv.Close() 257 258 dir := newTestDirectory(t) 259 defer os.RemoveAll(dir) 260 261 client := NewClient(srv.URL) 262 hash, err := client.UploadDirectory(dir, "", "", toEncrypt) 263 if err != nil { 264 t.Fatalf("error uploading directory: %s", err) 265 } 266 267 ls := func(prefix string) []string { 268 list, err := client.List(hash, prefix, "") 269 if err != nil { 270 t.Fatal(err) 271 } 272 paths := make([]string, 0, len(list.CommonPrefixes)+len(list.Entries)) 273 paths = append(paths, list.CommonPrefixes...) 274 for _, entry := range list.Entries { 275 paths = append(paths, entry.Path) 276 } 277 sort.Strings(paths) 278 return paths 279 } 280 281 tests := map[string][]string{ 282 "": {"dir1/", "dir2/", "file1.txt", "file2.txt"}, 283 "file": {"file1.txt", "file2.txt"}, 284 "file1": {"file1.txt"}, 285 "file2.txt": {"file2.txt"}, 286 "file12": {}, 287 "dir": {"dir1/", "dir2/"}, 288 "dir1": {"dir1/"}, 289 "dir1/": {"dir1/file3.txt", "dir1/file4.txt"}, 290 "dir1/file": {"dir1/file3.txt", "dir1/file4.txt"}, 291 "dir1/file3.txt": {"dir1/file3.txt"}, 292 "dir1/file34": {}, 293 "dir2/": {"dir2/dir3/", "dir2/dir4/", "dir2/file5.txt"}, 294 "dir2/file": {"dir2/file5.txt"}, 295 "dir2/dir": {"dir2/dir3/", "dir2/dir4/"}, 296 "dir2/dir3/": {"dir2/dir3/file6.txt"}, 297 "dir2/dir4/": {"dir2/dir4/file7.txt", "dir2/dir4/file8.txt"}, 298 "dir2/dir4/file": {"dir2/dir4/file7.txt", "dir2/dir4/file8.txt"}, 299 "dir2/dir4/file7.txt": {"dir2/dir4/file7.txt"}, 300 "dir2/dir4/file78": {}, 301 } 302 for prefix, expected := range tests { 303 actual := ls(prefix) 304 if !reflect.DeepEqual(actual, expected) { 305 t.Fatalf("expected prefix %q to return %v, got %v", prefix, expected, actual) 306 } 307 } 308 } 309 310 // TestClientMultipartUpload tests uploading files to swarm using a multipart 311 // upload 312 func TestClientMultipartUpload(t *testing.T) { 313 srv := swarmhttp.NewTestSwarmServer(t, serverFunc, nil) 314 defer srv.Close() 315 316 // define an uploader which uploads testDirFiles with some data 317 data := []byte("some-data") 318 uploader := UploaderFunc(func(upload UploadFn) error { 319 for _, name := range testDirFiles { 320 file := &File{ 321 ReadCloser: ioutil.NopCloser(bytes.NewReader(data)), 322 ManifestEntry: api.ManifestEntry{ 323 Path: name, 324 ContentType: "text/plain", 325 Size: int64(len(data)), 326 }, 327 } 328 if err := upload(file); err != nil { 329 return err 330 } 331 } 332 return nil 333 }) 334 335 // upload the files as a multipart upload 336 client := NewClient(srv.URL) 337 hash, err := client.MultipartUpload("", uploader) 338 if err != nil { 339 t.Fatal(err) 340 } 341 342 // check we can download the individual files 343 checkDownloadFile := func(path string) { 344 file, err := client.Download(hash, path) 345 if err != nil { 346 t.Fatal(err) 347 } 348 defer file.Close() 349 gotData, err := ioutil.ReadAll(file) 350 if err != nil { 351 t.Fatal(err) 352 } 353 if !bytes.Equal(gotData, data) { 354 t.Fatalf("expected data to be %q, got %q", data, gotData) 355 } 356 } 357 for _, file := range testDirFiles { 358 checkDownloadFile(file) 359 } 360 } 361 362 func newTestSigner() (*feed.GenericSigner, error) { 363 privKey, err := crypto.HexToECDSA("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef") 364 if err != nil { 365 return nil, err 366 } 367 return feed.NewGenericSigner(privKey), nil 368 } 369 370 // Test the transparent resolving of feed updates with bzz:// scheme 371 // 372 // First upload data to bzz:, and store the Swarm hash to the resulting manifest in a feed update. 373 // This effectively uses a feed to store a pointer to content rather than the content itself 374 // Retrieving the update with the Swarm hash should return the manifest pointing directly to the data 375 // and raw retrieve of that hash should return the data 376 func TestClientBzzWithFeed(t *testing.T) { 377 378 signer, _ := newTestSigner() 379 380 // Initialize a Swarm test server 381 srv := swarmhttp.NewTestSwarmServer(t, serverFunc, nil) 382 swarmClient := NewClient(srv.URL) 383 defer srv.Close() 384 385 // put together some data for our test: 386 dataBytes := []byte(` 387 // 388 // Create some data our manifest will point to. Data that could be very big and wouldn't fit in a feed update. 389 // So what we are going to do is upload it to Swarm bzz:// and obtain a **manifest hash** pointing to it: 390 // 391 // MANIFEST HASH --> DATA 392 // 393 // Then, we store that **manifest hash** into a Swarm Feed update. Once we have done this, 394 // we can use the **feed manifest hash** in bzz:// instead, this way: bzz://feed-manifest-hash. 395 // 396 // FEED MANIFEST HASH --> MANIFEST HASH --> DATA 397 // 398 // Given that we can update the feed at any time with a new **manifest hash** but the **feed manifest hash** 399 // stays constant, we have effectively created a fixed address to changing content. (Applause) 400 // 401 // FEED MANIFEST HASH (the same) --> MANIFEST HASH(2) --> DATA(2) 402 // 403 `) 404 405 // Create a virtual File out of memory containing the above data 406 f := &File{ 407 ReadCloser: ioutil.NopCloser(bytes.NewReader(dataBytes)), 408 ManifestEntry: api.ManifestEntry{ 409 ContentType: "text/plain", 410 Mode: 0660, 411 Size: int64(len(dataBytes)), 412 }, 413 } 414 415 // upload data to bzz:// and retrieve the content-addressed manifest hash, hex-encoded. 416 manifestAddressHex, err := swarmClient.Upload(f, "", false) 417 if err != nil { 418 t.Fatalf("Error creating manifest: %s", err) 419 } 420 421 // convert the hex-encoded manifest hash to a 32-byte slice 422 manifestAddress := common.FromHex(manifestAddressHex) 423 424 if len(manifestAddress) != storage.AddressLength { 425 t.Fatalf("Something went wrong. Got a hash of an unexpected length. Expected %d bytes. Got %d", storage.AddressLength, len(manifestAddress)) 426 } 427 428 // Now create a **feed manifest**. For that, we need a topic: 429 topic, _ := feed.NewTopic("interesting topic indeed", nil) 430 431 // Build a feed request to update data 432 request := feed.NewFirstRequest(topic) 433 434 // Put the 32-byte address of the manifest into the feed update 435 request.SetData(manifestAddress) 436 437 // Sign the update 438 if err := request.Sign(signer); err != nil { 439 t.Fatalf("Error signing update: %s", err) 440 } 441 442 // Publish the update and at the same time request a **feed manifest** to be created 443 feedManifestAddressHex, err := swarmClient.CreateFeedWithManifest(request) 444 if err != nil { 445 t.Fatalf("Error creating feed manifest: %s", err) 446 } 447 448 // Check we have received the exact **feed manifest** to be expected 449 // given the topic and user signing the updates: 450 correctFeedManifestAddrHex := "747c402e5b9dc715a25a4393147512167bab018a007fad7cdcd9adc7fce1ced2" 451 if feedManifestAddressHex != correctFeedManifestAddrHex { 452 t.Fatalf("Response feed manifest mismatch, expected '%s', got '%s'", correctFeedManifestAddrHex, feedManifestAddressHex) 453 } 454 455 // Check we get a not found error when trying to get feed updates with a made-up manifest 456 _, err = swarmClient.QueryFeed(nil, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") 457 if err != ErrNoFeedUpdatesFound { 458 t.Fatalf("Expected to receive ErrNoFeedUpdatesFound error. Got: %s", err) 459 } 460 461 // If we query the feed directly we should get **manifest hash** back: 462 reader, err := swarmClient.QueryFeed(nil, correctFeedManifestAddrHex) 463 if err != nil { 464 t.Fatalf("Error retrieving feed updates: %s", err) 465 } 466 defer reader.Close() 467 gotData, err := ioutil.ReadAll(reader) 468 if err != nil { 469 t.Fatal(err) 470 } 471 472 //Check that indeed the **manifest hash** is retrieved 473 if !bytes.Equal(manifestAddress, gotData) { 474 t.Fatalf("Expected: %v, got %v", manifestAddress, gotData) 475 } 476 477 // Now the final test we were looking for: Use bzz://<feed-manifest> and that should resolve all manifests 478 // and return the original data directly: 479 f, err = swarmClient.Download(feedManifestAddressHex, "") 480 if err != nil { 481 t.Fatal(err) 482 } 483 gotData, err = ioutil.ReadAll(f) 484 if err != nil { 485 t.Fatal(err) 486 } 487 488 // Check that we get back the original data: 489 if !bytes.Equal(dataBytes, gotData) { 490 t.Fatalf("Expected: %v, got %v", manifestAddress, gotData) 491 } 492 } 493 494 // TestClientCreateUpdateFeed will check that feeds can be created and updated via the HTTP client. 495 func TestClientCreateUpdateFeed(t *testing.T) { 496 497 signer, _ := newTestSigner() 498 499 srv := swarmhttp.NewTestSwarmServer(t, serverFunc, nil) 500 client := NewClient(srv.URL) 501 defer srv.Close() 502 503 // set raw data for the feed update 504 databytes := []byte("En un lugar de La Mancha, de cuyo nombre no quiero acordarme...") 505 506 // our feed topic name 507 topic, _ := feed.NewTopic("El Quijote", nil) 508 createRequest := feed.NewFirstRequest(topic) 509 510 createRequest.SetData(databytes) 511 if err := createRequest.Sign(signer); err != nil { 512 t.Fatalf("Error signing update: %s", err) 513 } 514 515 feedManifestHash, err := client.CreateFeedWithManifest(createRequest) 516 if err != nil { 517 t.Fatal(err) 518 } 519 520 correctManifestAddrHex := "0e9b645ebc3da167b1d56399adc3276f7a08229301b72a03336be0e7d4b71882" 521 if feedManifestHash != correctManifestAddrHex { 522 t.Fatalf("Response feed manifest mismatch, expected '%s', got '%s'", correctManifestAddrHex, feedManifestHash) 523 } 524 525 reader, err := client.QueryFeed(nil, correctManifestAddrHex) 526 if err != nil { 527 t.Fatalf("Error retrieving feed updates: %s", err) 528 } 529 defer reader.Close() 530 gotData, err := ioutil.ReadAll(reader) 531 if err != nil { 532 t.Fatal(err) 533 } 534 if !bytes.Equal(databytes, gotData) { 535 t.Fatalf("Expected: %v, got %v", databytes, gotData) 536 } 537 538 // define different data 539 databytes = []byte("... no ha mucho tiempo que vivĂa un hidalgo de los de lanza en astillero ...") 540 541 updateRequest, err := client.GetFeedRequest(nil, correctManifestAddrHex) 542 if err != nil { 543 t.Fatalf("Error retrieving update request template: %s", err) 544 } 545 546 updateRequest.SetData(databytes) 547 if err := updateRequest.Sign(signer); err != nil { 548 t.Fatalf("Error signing update: %s", err) 549 } 550 551 if err = client.UpdateFeed(updateRequest); err != nil { 552 t.Fatalf("Error updating feed: %s", err) 553 } 554 555 reader, err = client.QueryFeed(nil, correctManifestAddrHex) 556 if err != nil { 557 t.Fatalf("Error retrieving feed updates: %s", err) 558 } 559 defer reader.Close() 560 gotData, err = ioutil.ReadAll(reader) 561 if err != nil { 562 t.Fatal(err) 563 } 564 if !bytes.Equal(databytes, gotData) { 565 t.Fatalf("Expected: %v, got %v", databytes, gotData) 566 } 567 568 // now try retrieving feed updates without a manifest 569 570 fd := &feed.Feed{ 571 Topic: topic, 572 User: signer.Address(), 573 } 574 575 lookupParams := feed.NewQueryLatest(fd, lookup.NoClue) 576 reader, err = client.QueryFeed(lookupParams, "") 577 if err != nil { 578 t.Fatalf("Error retrieving feed updates: %s", err) 579 } 580 defer reader.Close() 581 gotData, err = ioutil.ReadAll(reader) 582 if err != nil { 583 t.Fatal(err) 584 } 585 if !bytes.Equal(databytes, gotData) { 586 t.Fatalf("Expected: %v, got %v", databytes, gotData) 587 } 588 }