client_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. package client
  17. import (
  18. "bytes"
  19. "io/ioutil"
  20. "os"
  21. "path/filepath"
  22. "reflect"
  23. "sort"
  24. "testing"
  25. "github.com/ethereum/go-ethereum/swarm/storage/mru/lookup"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/swarm/api"
  29. swarmhttp "github.com/ethereum/go-ethereum/swarm/api/http"
  30. "github.com/ethereum/go-ethereum/swarm/multihash"
  31. "github.com/ethereum/go-ethereum/swarm/storage/mru"
  32. "github.com/ethereum/go-ethereum/swarm/testutil"
  33. )
  34. func serverFunc(api *api.API) testutil.TestServer {
  35. return swarmhttp.NewServer(api, "")
  36. }
  37. // TestClientUploadDownloadRaw test uploading and downloading raw data to swarm
  38. func TestClientUploadDownloadRaw(t *testing.T) {
  39. testClientUploadDownloadRaw(false, t)
  40. }
  41. func TestClientUploadDownloadRawEncrypted(t *testing.T) {
  42. testClientUploadDownloadRaw(true, t)
  43. }
  44. func testClientUploadDownloadRaw(toEncrypt bool, t *testing.T) {
  45. srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
  46. defer srv.Close()
  47. client := NewClient(srv.URL)
  48. // upload some raw data
  49. data := []byte("foo123")
  50. hash, err := client.UploadRaw(bytes.NewReader(data), int64(len(data)), toEncrypt)
  51. if err != nil {
  52. t.Fatal(err)
  53. }
  54. // check we can download the same data
  55. res, isEncrypted, err := client.DownloadRaw(hash)
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. if isEncrypted != toEncrypt {
  60. t.Fatalf("Expected encyption status %v got %v", toEncrypt, isEncrypted)
  61. }
  62. defer res.Close()
  63. gotData, err := ioutil.ReadAll(res)
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. if !bytes.Equal(gotData, data) {
  68. t.Fatalf("expected downloaded data to be %q, got %q", data, gotData)
  69. }
  70. }
  71. // TestClientUploadDownloadFiles test uploading and downloading files to swarm
  72. // manifests
  73. func TestClientUploadDownloadFiles(t *testing.T) {
  74. testClientUploadDownloadFiles(false, t)
  75. }
  76. func TestClientUploadDownloadFilesEncrypted(t *testing.T) {
  77. testClientUploadDownloadFiles(true, t)
  78. }
  79. func testClientUploadDownloadFiles(toEncrypt bool, t *testing.T) {
  80. srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
  81. defer srv.Close()
  82. client := NewClient(srv.URL)
  83. upload := func(manifest, path string, data []byte) string {
  84. file := &File{
  85. ReadCloser: ioutil.NopCloser(bytes.NewReader(data)),
  86. ManifestEntry: api.ManifestEntry{
  87. Path: path,
  88. ContentType: "text/plain",
  89. Size: int64(len(data)),
  90. },
  91. }
  92. hash, err := client.Upload(file, manifest, toEncrypt)
  93. if err != nil {
  94. t.Fatal(err)
  95. }
  96. return hash
  97. }
  98. checkDownload := func(manifest, path string, expected []byte) {
  99. file, err := client.Download(manifest, path)
  100. if err != nil {
  101. t.Fatal(err)
  102. }
  103. defer file.Close()
  104. if file.Size != int64(len(expected)) {
  105. t.Fatalf("expected downloaded file to be %d bytes, got %d", len(expected), file.Size)
  106. }
  107. if file.ContentType != "text/plain" {
  108. t.Fatalf("expected downloaded file to have type %q, got %q", "text/plain", file.ContentType)
  109. }
  110. data, err := ioutil.ReadAll(file)
  111. if err != nil {
  112. t.Fatal(err)
  113. }
  114. if !bytes.Equal(data, expected) {
  115. t.Fatalf("expected downloaded data to be %q, got %q", expected, data)
  116. }
  117. }
  118. // upload a file to the root of a manifest
  119. rootData := []byte("some-data")
  120. rootHash := upload("", "", rootData)
  121. // check we can download the root file
  122. checkDownload(rootHash, "", rootData)
  123. // upload another file to the same manifest
  124. otherData := []byte("some-other-data")
  125. newHash := upload(rootHash, "some/other/path", otherData)
  126. // check we can download both files from the new manifest
  127. checkDownload(newHash, "", rootData)
  128. checkDownload(newHash, "some/other/path", otherData)
  129. // replace the root file with different data
  130. newHash = upload(newHash, "", otherData)
  131. // check both files have the other data
  132. checkDownload(newHash, "", otherData)
  133. checkDownload(newHash, "some/other/path", otherData)
  134. }
  135. var testDirFiles = []string{
  136. "file1.txt",
  137. "file2.txt",
  138. "dir1/file3.txt",
  139. "dir1/file4.txt",
  140. "dir2/file5.txt",
  141. "dir2/dir3/file6.txt",
  142. "dir2/dir4/file7.txt",
  143. "dir2/dir4/file8.txt",
  144. }
  145. func newTestDirectory(t *testing.T) string {
  146. dir, err := ioutil.TempDir("", "swarm-client-test")
  147. if err != nil {
  148. t.Fatal(err)
  149. }
  150. for _, file := range testDirFiles {
  151. path := filepath.Join(dir, file)
  152. if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
  153. os.RemoveAll(dir)
  154. t.Fatalf("error creating dir for %s: %s", path, err)
  155. }
  156. if err := ioutil.WriteFile(path, []byte(file), 0644); err != nil {
  157. os.RemoveAll(dir)
  158. t.Fatalf("error writing file %s: %s", path, err)
  159. }
  160. }
  161. return dir
  162. }
  163. // TestClientUploadDownloadDirectory tests uploading and downloading a
  164. // directory of files to a swarm manifest
  165. func TestClientUploadDownloadDirectory(t *testing.T) {
  166. srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
  167. defer srv.Close()
  168. dir := newTestDirectory(t)
  169. defer os.RemoveAll(dir)
  170. // upload the directory
  171. client := NewClient(srv.URL)
  172. defaultPath := testDirFiles[0]
  173. hash, err := client.UploadDirectory(dir, defaultPath, "", false)
  174. if err != nil {
  175. t.Fatalf("error uploading directory: %s", err)
  176. }
  177. // check we can download the individual files
  178. checkDownloadFile := func(path string, expected []byte) {
  179. file, err := client.Download(hash, path)
  180. if err != nil {
  181. t.Fatal(err)
  182. }
  183. defer file.Close()
  184. data, err := ioutil.ReadAll(file)
  185. if err != nil {
  186. t.Fatal(err)
  187. }
  188. if !bytes.Equal(data, expected) {
  189. t.Fatalf("expected data to be %q, got %q", expected, data)
  190. }
  191. }
  192. for _, file := range testDirFiles {
  193. checkDownloadFile(file, []byte(file))
  194. }
  195. // check we can download the default path
  196. checkDownloadFile("", []byte(testDirFiles[0]))
  197. // check we can download the directory
  198. tmp, err := ioutil.TempDir("", "swarm-client-test")
  199. if err != nil {
  200. t.Fatal(err)
  201. }
  202. defer os.RemoveAll(tmp)
  203. if err := client.DownloadDirectory(hash, "", tmp, ""); err != nil {
  204. t.Fatal(err)
  205. }
  206. for _, file := range testDirFiles {
  207. data, err := ioutil.ReadFile(filepath.Join(tmp, file))
  208. if err != nil {
  209. t.Fatal(err)
  210. }
  211. if !bytes.Equal(data, []byte(file)) {
  212. t.Fatalf("expected data to be %q, got %q", file, data)
  213. }
  214. }
  215. }
  216. // TestClientFileList tests listing files in a swarm manifest
  217. func TestClientFileList(t *testing.T) {
  218. testClientFileList(false, t)
  219. }
  220. func TestClientFileListEncrypted(t *testing.T) {
  221. testClientFileList(true, t)
  222. }
  223. func testClientFileList(toEncrypt bool, t *testing.T) {
  224. srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
  225. defer srv.Close()
  226. dir := newTestDirectory(t)
  227. defer os.RemoveAll(dir)
  228. client := NewClient(srv.URL)
  229. hash, err := client.UploadDirectory(dir, "", "", toEncrypt)
  230. if err != nil {
  231. t.Fatalf("error uploading directory: %s", err)
  232. }
  233. ls := func(prefix string) []string {
  234. list, err := client.List(hash, prefix, "")
  235. if err != nil {
  236. t.Fatal(err)
  237. }
  238. paths := make([]string, 0, len(list.CommonPrefixes)+len(list.Entries))
  239. paths = append(paths, list.CommonPrefixes...)
  240. for _, entry := range list.Entries {
  241. paths = append(paths, entry.Path)
  242. }
  243. sort.Strings(paths)
  244. return paths
  245. }
  246. tests := map[string][]string{
  247. "": {"dir1/", "dir2/", "file1.txt", "file2.txt"},
  248. "file": {"file1.txt", "file2.txt"},
  249. "file1": {"file1.txt"},
  250. "file2.txt": {"file2.txt"},
  251. "file12": {},
  252. "dir": {"dir1/", "dir2/"},
  253. "dir1": {"dir1/"},
  254. "dir1/": {"dir1/file3.txt", "dir1/file4.txt"},
  255. "dir1/file": {"dir1/file3.txt", "dir1/file4.txt"},
  256. "dir1/file3.txt": {"dir1/file3.txt"},
  257. "dir1/file34": {},
  258. "dir2/": {"dir2/dir3/", "dir2/dir4/", "dir2/file5.txt"},
  259. "dir2/file": {"dir2/file5.txt"},
  260. "dir2/dir": {"dir2/dir3/", "dir2/dir4/"},
  261. "dir2/dir3/": {"dir2/dir3/file6.txt"},
  262. "dir2/dir4/": {"dir2/dir4/file7.txt", "dir2/dir4/file8.txt"},
  263. "dir2/dir4/file": {"dir2/dir4/file7.txt", "dir2/dir4/file8.txt"},
  264. "dir2/dir4/file7.txt": {"dir2/dir4/file7.txt"},
  265. "dir2/dir4/file78": {},
  266. }
  267. for prefix, expected := range tests {
  268. actual := ls(prefix)
  269. if !reflect.DeepEqual(actual, expected) {
  270. t.Fatalf("expected prefix %q to return %v, got %v", prefix, expected, actual)
  271. }
  272. }
  273. }
  274. // TestClientMultipartUpload tests uploading files to swarm using a multipart
  275. // upload
  276. func TestClientMultipartUpload(t *testing.T) {
  277. srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
  278. defer srv.Close()
  279. // define an uploader which uploads testDirFiles with some data
  280. data := []byte("some-data")
  281. uploader := UploaderFunc(func(upload UploadFn) error {
  282. for _, name := range testDirFiles {
  283. file := &File{
  284. ReadCloser: ioutil.NopCloser(bytes.NewReader(data)),
  285. ManifestEntry: api.ManifestEntry{
  286. Path: name,
  287. ContentType: "text/plain",
  288. Size: int64(len(data)),
  289. },
  290. }
  291. if err := upload(file); err != nil {
  292. return err
  293. }
  294. }
  295. return nil
  296. })
  297. // upload the files as a multipart upload
  298. client := NewClient(srv.URL)
  299. hash, err := client.MultipartUpload("", uploader)
  300. if err != nil {
  301. t.Fatal(err)
  302. }
  303. // check we can download the individual files
  304. checkDownloadFile := func(path string) {
  305. file, err := client.Download(hash, path)
  306. if err != nil {
  307. t.Fatal(err)
  308. }
  309. defer file.Close()
  310. gotData, err := ioutil.ReadAll(file)
  311. if err != nil {
  312. t.Fatal(err)
  313. }
  314. if !bytes.Equal(gotData, data) {
  315. t.Fatalf("expected data to be %q, got %q", data, gotData)
  316. }
  317. }
  318. for _, file := range testDirFiles {
  319. checkDownloadFile(file)
  320. }
  321. }
  322. func newTestSigner() (*mru.GenericSigner, error) {
  323. privKey, err := crypto.HexToECDSA("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")
  324. if err != nil {
  325. return nil, err
  326. }
  327. return mru.NewGenericSigner(privKey), nil
  328. }
  329. // test the transparent resolving of multihash feed updates with bzz:// scheme
  330. //
  331. // first upload data, and store the multihash to the resulting manifest in a feed update
  332. // retrieving the update with the multihash should return the manifest pointing directly to the data
  333. // and raw retrieve of that hash should return the data
  334. func TestClientCreateFeedMultihash(t *testing.T) {
  335. signer, _ := newTestSigner()
  336. srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
  337. client := NewClient(srv.URL)
  338. defer srv.Close()
  339. // add the data our multihash aliased manifest will point to
  340. databytes := []byte("bar")
  341. swarmHash, err := client.UploadRaw(bytes.NewReader(databytes), int64(len(databytes)), false)
  342. if err != nil {
  343. t.Fatalf("Error uploading raw test data: %s", err)
  344. }
  345. s := common.FromHex(swarmHash)
  346. mh := multihash.ToMultihash(s)
  347. // our feed topic
  348. topic, _ := mru.NewTopic("foo.eth", nil)
  349. createRequest := mru.NewFirstRequest(topic)
  350. createRequest.SetData(mh)
  351. if err := createRequest.Sign(signer); err != nil {
  352. t.Fatalf("Error signing update: %s", err)
  353. }
  354. feedManifestHash, err := client.CreateFeedWithManifest(createRequest)
  355. if err != nil {
  356. t.Fatalf("Error creating feed manifest: %s", err)
  357. }
  358. correctManifestAddrHex := "bb056a5264c295c2b0f613c8409b9c87ce9d71576ace02458160df4cc894210b"
  359. if feedManifestHash != correctManifestAddrHex {
  360. t.Fatalf("Response feed manifest mismatch, expected '%s', got '%s'", correctManifestAddrHex, feedManifestHash)
  361. }
  362. // Check we get a not found error when trying to get feed updates with a made-up manifest
  363. _, err = client.QueryFeed(nil, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
  364. if err != ErrNoFeedUpdatesFound {
  365. t.Fatalf("Expected to receive ErrNoFeedUpdatesFound error. Got: %s", err)
  366. }
  367. reader, err := client.QueryFeed(nil, correctManifestAddrHex)
  368. if err != nil {
  369. t.Fatalf("Error retrieving feed updates: %s", err)
  370. }
  371. defer reader.Close()
  372. gotData, err := ioutil.ReadAll(reader)
  373. if err != nil {
  374. t.Fatal(err)
  375. }
  376. if !bytes.Equal(mh, gotData) {
  377. t.Fatalf("Expected: %v, got %v", mh, gotData)
  378. }
  379. }
  380. // TestClientCreateUpdateFeed will check that feeds can be created and updated via the HTTP client.
  381. func TestClientCreateUpdateFeed(t *testing.T) {
  382. signer, _ := newTestSigner()
  383. srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
  384. client := NewClient(srv.URL)
  385. defer srv.Close()
  386. // set raw data for the feed update
  387. databytes := []byte("En un lugar de La Mancha, de cuyo nombre no quiero acordarme...")
  388. // our feed topic name
  389. topic, _ := mru.NewTopic("El Quijote", nil)
  390. createRequest := mru.NewFirstRequest(topic)
  391. createRequest.SetData(databytes)
  392. if err := createRequest.Sign(signer); err != nil {
  393. t.Fatalf("Error signing update: %s", err)
  394. }
  395. feedManifestHash, err := client.CreateFeedWithManifest(createRequest)
  396. correctManifestAddrHex := "0e9b645ebc3da167b1d56399adc3276f7a08229301b72a03336be0e7d4b71882"
  397. if feedManifestHash != correctManifestAddrHex {
  398. t.Fatalf("Response feed manifest mismatch, expected '%s', got '%s'", correctManifestAddrHex, feedManifestHash)
  399. }
  400. reader, err := client.QueryFeed(nil, correctManifestAddrHex)
  401. if err != nil {
  402. t.Fatalf("Error retrieving feed updates: %s", err)
  403. }
  404. defer reader.Close()
  405. gotData, err := ioutil.ReadAll(reader)
  406. if err != nil {
  407. t.Fatal(err)
  408. }
  409. if !bytes.Equal(databytes, gotData) {
  410. t.Fatalf("Expected: %v, got %v", databytes, gotData)
  411. }
  412. // define different data
  413. databytes = []byte("... no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero ...")
  414. updateRequest, err := client.GetFeedMetadata(nil, correctManifestAddrHex)
  415. if err != nil {
  416. t.Fatalf("Error retrieving update request template: %s", err)
  417. }
  418. updateRequest.SetData(databytes)
  419. if err := updateRequest.Sign(signer); err != nil {
  420. t.Fatalf("Error signing update: %s", err)
  421. }
  422. if err = client.UpdateFeed(updateRequest); err != nil {
  423. t.Fatalf("Error updating feed: %s", err)
  424. }
  425. reader, err = client.QueryFeed(nil, correctManifestAddrHex)
  426. if err != nil {
  427. t.Fatalf("Error retrieving feed updates: %s", err)
  428. }
  429. defer reader.Close()
  430. gotData, err = ioutil.ReadAll(reader)
  431. if err != nil {
  432. t.Fatal(err)
  433. }
  434. if !bytes.Equal(databytes, gotData) {
  435. t.Fatalf("Expected: %v, got %v", databytes, gotData)
  436. }
  437. // now try retrieving feed updates without a manifest
  438. feed := &mru.Feed{
  439. Topic: topic,
  440. User: signer.Address(),
  441. }
  442. lookupParams := mru.NewQueryLatest(feed, lookup.NoClue)
  443. reader, err = client.QueryFeed(lookupParams, "")
  444. if err != nil {
  445. t.Fatalf("Error retrieving feed updates: %s", err)
  446. }
  447. defer reader.Close()
  448. gotData, err = ioutil.ReadAll(reader)
  449. if err != nil {
  450. t.Fatal(err)
  451. }
  452. if !bytes.Equal(databytes, gotData) {
  453. t.Fatalf("Expected: %v, got %v", databytes, gotData)
  454. }
  455. }