client_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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/common"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/swarm/api"
  28. swarmhttp "github.com/ethereum/go-ethereum/swarm/api/http"
  29. "github.com/ethereum/go-ethereum/swarm/multihash"
  30. "github.com/ethereum/go-ethereum/swarm/storage/mru"
  31. "github.com/ethereum/go-ethereum/swarm/testutil"
  32. )
  33. func serverFunc(api *api.API) testutil.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 := testutil.NewTestSwarmServer(t, serverFunc)
  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 := testutil.NewTestSwarmServer(t, serverFunc)
  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 := testutil.NewTestSwarmServer(t, serverFunc)
  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 := testutil.NewTestSwarmServer(t, serverFunc)
  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 := testutil.NewTestSwarmServer(t, serverFunc)
  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() (*mru.GenericSigner, error) {
  322. privKey, err := crypto.HexToECDSA("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")
  323. if err != nil {
  324. return nil, err
  325. }
  326. return mru.NewGenericSigner(privKey), nil
  327. }
  328. // test the transparent resolving of multihash resource types with bzz:// scheme
  329. //
  330. // first upload data, and store the multihash to the resulting manifest in a resource 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 TestClientCreateResourceMultihash(t *testing.T) {
  334. signer, _ := newTestSigner()
  335. srv := testutil.NewTestSwarmServer(t, serverFunc)
  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 mutable resource "name"
  347. resourceName := "foo.eth"
  348. createRequest, err := mru.NewCreateUpdateRequest(&mru.ResourceMetadata{
  349. Name: resourceName,
  350. Frequency: 13,
  351. StartTime: srv.GetCurrentTime(),
  352. Owner: signer.Address(),
  353. })
  354. if err != nil {
  355. t.Fatal(err)
  356. }
  357. createRequest.SetData(mh, true)
  358. if err := createRequest.Sign(signer); err != nil {
  359. t.Fatalf("Error signing update: %s", err)
  360. }
  361. resourceManifestHash, err := client.CreateResource(createRequest)
  362. if err != nil {
  363. t.Fatalf("Error creating resource: %s", err)
  364. }
  365. correctManifestAddrHex := "6d3bc4664c97d8b821cb74bcae43f592494fb46d2d9cd31e69f3c7c802bbbd8e"
  366. if resourceManifestHash != correctManifestAddrHex {
  367. t.Fatalf("Response resource key mismatch, expected '%s', got '%s'", correctManifestAddrHex, resourceManifestHash)
  368. }
  369. reader, err := client.GetResource(correctManifestAddrHex)
  370. if err != nil {
  371. t.Fatalf("Error retrieving resource: %s", err)
  372. }
  373. defer reader.Close()
  374. gotData, err := ioutil.ReadAll(reader)
  375. if err != nil {
  376. t.Fatal(err)
  377. }
  378. if !bytes.Equal(mh, gotData) {
  379. t.Fatalf("Expected: %v, got %v", mh, gotData)
  380. }
  381. }
  382. // TestClientCreateUpdateResource will check that mutable resources can be created and updated via the HTTP client.
  383. func TestClientCreateUpdateResource(t *testing.T) {
  384. signer, _ := newTestSigner()
  385. srv := testutil.NewTestSwarmServer(t, serverFunc)
  386. client := NewClient(srv.URL)
  387. defer srv.Close()
  388. // set raw data for the resource
  389. databytes := []byte("En un lugar de La Mancha, de cuyo nombre no quiero acordarme...")
  390. // our mutable resource name
  391. resourceName := "El Quijote"
  392. createRequest, err := mru.NewCreateUpdateRequest(&mru.ResourceMetadata{
  393. Name: resourceName,
  394. Frequency: 13,
  395. StartTime: srv.GetCurrentTime(),
  396. Owner: signer.Address(),
  397. })
  398. if err != nil {
  399. t.Fatal(err)
  400. }
  401. createRequest.SetData(databytes, false)
  402. if err := createRequest.Sign(signer); err != nil {
  403. t.Fatalf("Error signing update: %s", err)
  404. }
  405. resourceManifestHash, err := client.CreateResource(createRequest)
  406. correctManifestAddrHex := "cc7904c17b49f9679e2d8006fe25e87e3f5c2072c2b49cab50f15e544471b30a"
  407. if resourceManifestHash != correctManifestAddrHex {
  408. t.Fatalf("Response resource key mismatch, expected '%s', got '%s'", correctManifestAddrHex, resourceManifestHash)
  409. }
  410. reader, err := client.GetResource(correctManifestAddrHex)
  411. if err != nil {
  412. t.Fatalf("Error retrieving resource: %s", err)
  413. }
  414. defer reader.Close()
  415. gotData, err := ioutil.ReadAll(reader)
  416. if err != nil {
  417. t.Fatal(err)
  418. }
  419. if !bytes.Equal(databytes, gotData) {
  420. t.Fatalf("Expected: %v, got %v", databytes, gotData)
  421. }
  422. // define different data
  423. databytes = []byte("... no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero ...")
  424. updateRequest, err := client.GetResourceMetadata(correctManifestAddrHex)
  425. if err != nil {
  426. t.Fatalf("Error retrieving update request template: %s", err)
  427. }
  428. updateRequest.SetData(databytes, false)
  429. if err := updateRequest.Sign(signer); err != nil {
  430. t.Fatalf("Error signing update: %s", err)
  431. }
  432. if err = client.UpdateResource(updateRequest); err != nil {
  433. t.Fatalf("Error updating resource: %s", err)
  434. }
  435. reader, err = client.GetResource(correctManifestAddrHex)
  436. if err != nil {
  437. t.Fatalf("Error retrieving resource: %s", err)
  438. }
  439. defer reader.Close()
  440. gotData, err = ioutil.ReadAll(reader)
  441. if err != nil {
  442. t.Fatal(err)
  443. }
  444. if !bytes.Equal(databytes, gotData) {
  445. t.Fatalf("Expected: %v, got %v", databytes, gotData)
  446. }
  447. }