client_test.go 15 KB

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