upload_test.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU 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. // go-ethereum 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 General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bytes"
  19. "fmt"
  20. "io"
  21. "io/ioutil"
  22. "net/http"
  23. "os"
  24. "path"
  25. "path/filepath"
  26. "runtime"
  27. "strings"
  28. "testing"
  29. "time"
  30. "github.com/ethereum/go-ethereum/log"
  31. swarmapi "github.com/ethereum/go-ethereum/swarm/api/client"
  32. "github.com/ethereum/go-ethereum/swarm/testutil"
  33. "github.com/mattn/go-colorable"
  34. )
  35. func init() {
  36. log.PrintOrigins(true)
  37. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
  38. }
  39. func TestSwarmUp(t *testing.T) {
  40. if runtime.GOOS == "windows" {
  41. t.Skip()
  42. }
  43. cluster := newTestCluster(t, clusterSize)
  44. defer cluster.Shutdown()
  45. cases := []struct {
  46. name string
  47. f func(t *testing.T, cluster *testCluster)
  48. }{
  49. {"NoEncryption", testNoEncryption},
  50. {"Encrypted", testEncrypted},
  51. {"RecursiveNoEncryption", testRecursiveNoEncryption},
  52. {"RecursiveEncrypted", testRecursiveEncrypted},
  53. {"DefaultPathAll", testDefaultPathAll},
  54. }
  55. for _, tc := range cases {
  56. t.Run(tc.name, func(t *testing.T) {
  57. tc.f(t, cluster)
  58. })
  59. }
  60. }
  61. // testNoEncryption tests that running 'swarm up' makes the resulting file
  62. // available from all nodes via the HTTP API
  63. func testNoEncryption(t *testing.T, cluster *testCluster) {
  64. testDefault(t, cluster, false)
  65. }
  66. // testEncrypted tests that running 'swarm up --encrypted' makes the resulting file
  67. // available from all nodes via the HTTP API
  68. func testEncrypted(t *testing.T, cluster *testCluster) {
  69. testDefault(t, cluster, true)
  70. }
  71. func testRecursiveNoEncryption(t *testing.T, cluster *testCluster) {
  72. testRecursive(t, cluster, false)
  73. }
  74. func testRecursiveEncrypted(t *testing.T, cluster *testCluster) {
  75. testRecursive(t, cluster, true)
  76. }
  77. func testDefault(t *testing.T, cluster *testCluster, toEncrypt bool) {
  78. tmpFileName := testutil.TempFileWithContent(t, data)
  79. defer os.Remove(tmpFileName)
  80. // write data to file
  81. hashRegexp := `[a-f\d]{64}`
  82. flags := []string{
  83. "--bzzapi", cluster.Nodes[0].URL,
  84. "up",
  85. tmpFileName}
  86. if toEncrypt {
  87. hashRegexp = `[a-f\d]{128}`
  88. flags = []string{
  89. "--bzzapi", cluster.Nodes[0].URL,
  90. "up",
  91. "--encrypt",
  92. tmpFileName}
  93. }
  94. // upload the file with 'swarm up' and expect a hash
  95. log.Info(fmt.Sprintf("uploading file with 'swarm up'"))
  96. up := runSwarm(t, flags...)
  97. _, matches := up.ExpectRegexp(hashRegexp)
  98. up.ExpectExit()
  99. hash := matches[0]
  100. log.Info("file uploaded", "hash", hash)
  101. // get the file from the HTTP API of each node
  102. for _, node := range cluster.Nodes {
  103. log.Info("getting file from node", "node", node.Name)
  104. res, err := http.Get(node.URL + "/bzz:/" + hash)
  105. if err != nil {
  106. t.Fatal(err)
  107. }
  108. defer res.Body.Close()
  109. reply, err := ioutil.ReadAll(res.Body)
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. if res.StatusCode != 200 {
  114. t.Fatalf("expected HTTP status 200, got %s", res.Status)
  115. }
  116. if string(reply) != data {
  117. t.Fatalf("expected HTTP body %q, got %q", data, reply)
  118. }
  119. log.Debug("verifying uploaded file using `swarm down`")
  120. //try to get the content with `swarm down`
  121. tmpDownload, err := ioutil.TempDir("", "swarm-test")
  122. tmpDownload = path.Join(tmpDownload, "tmpfile.tmp")
  123. if err != nil {
  124. t.Fatal(err)
  125. }
  126. defer os.RemoveAll(tmpDownload)
  127. bzzLocator := "bzz:/" + hash
  128. flags = []string{
  129. "--bzzapi", cluster.Nodes[0].URL,
  130. "down",
  131. bzzLocator,
  132. tmpDownload,
  133. }
  134. down := runSwarm(t, flags...)
  135. down.ExpectExit()
  136. fi, err := os.Stat(tmpDownload)
  137. if err != nil {
  138. t.Fatalf("could not stat path: %v", err)
  139. }
  140. switch mode := fi.Mode(); {
  141. case mode.IsRegular():
  142. downloadedBytes, err := ioutil.ReadFile(tmpDownload)
  143. if err != nil {
  144. t.Fatalf("had an error reading the downloaded file: %v", err)
  145. }
  146. if !bytes.Equal(downloadedBytes, bytes.NewBufferString(data).Bytes()) {
  147. t.Fatalf("retrieved data and posted data not equal!")
  148. }
  149. default:
  150. t.Fatalf("expected to download regular file, got %s", fi.Mode())
  151. }
  152. }
  153. timeout := time.Duration(2 * time.Second)
  154. httpClient := http.Client{
  155. Timeout: timeout,
  156. }
  157. // try to squeeze a timeout by getting an non-existent hash from each node
  158. for _, node := range cluster.Nodes {
  159. _, err := httpClient.Get(node.URL + "/bzz:/1023e8bae0f70be7d7b5f74343088ba408a218254391490c85ae16278e230340")
  160. // we're speeding up the timeout here since netstore has a 60 seconds timeout on a request
  161. if err != nil && !strings.Contains(err.Error(), "Client.Timeout exceeded while awaiting headers") {
  162. t.Fatal(err)
  163. }
  164. // this is disabled since it takes 60s due to netstore timeout
  165. // if res.StatusCode != 404 {
  166. // t.Fatalf("expected HTTP status 404, got %s", res.Status)
  167. // }
  168. }
  169. }
  170. func testRecursive(t *testing.T, cluster *testCluster, toEncrypt bool) {
  171. tmpUploadDir, err := ioutil.TempDir("", "swarm-test")
  172. if err != nil {
  173. t.Fatal(err)
  174. }
  175. defer os.RemoveAll(tmpUploadDir)
  176. // create tmp files
  177. for _, path := range []string{"tmp1", "tmp2"} {
  178. if err := ioutil.WriteFile(filepath.Join(tmpUploadDir, path), bytes.NewBufferString(data).Bytes(), 0644); err != nil {
  179. t.Fatal(err)
  180. }
  181. }
  182. hashRegexp := `[a-f\d]{64}`
  183. flags := []string{
  184. "--bzzapi", cluster.Nodes[0].URL,
  185. "--recursive",
  186. "up",
  187. tmpUploadDir}
  188. if toEncrypt {
  189. hashRegexp = `[a-f\d]{128}`
  190. flags = []string{
  191. "--bzzapi", cluster.Nodes[0].URL,
  192. "--recursive",
  193. "up",
  194. "--encrypt",
  195. tmpUploadDir}
  196. }
  197. // upload the file with 'swarm up' and expect a hash
  198. log.Info(fmt.Sprintf("uploading file with 'swarm up'"))
  199. up := runSwarm(t, flags...)
  200. _, matches := up.ExpectRegexp(hashRegexp)
  201. up.ExpectExit()
  202. hash := matches[0]
  203. log.Info("dir uploaded", "hash", hash)
  204. // get the file from the HTTP API of each node
  205. for _, node := range cluster.Nodes {
  206. log.Info("getting file from node", "node", node.Name)
  207. //try to get the content with `swarm down`
  208. tmpDownload, err := ioutil.TempDir("", "swarm-test")
  209. if err != nil {
  210. t.Fatal(err)
  211. }
  212. defer os.RemoveAll(tmpDownload)
  213. bzzLocator := "bzz:/" + hash
  214. flagss := []string{
  215. "--bzzapi", cluster.Nodes[0].URL,
  216. "down",
  217. "--recursive",
  218. bzzLocator,
  219. tmpDownload,
  220. }
  221. fmt.Println("downloading from swarm with recursive")
  222. down := runSwarm(t, flagss...)
  223. down.ExpectExit()
  224. files, err := ioutil.ReadDir(tmpDownload)
  225. for _, v := range files {
  226. fi, err := os.Stat(path.Join(tmpDownload, v.Name()))
  227. if err != nil {
  228. t.Fatalf("got an error: %v", err)
  229. }
  230. switch mode := fi.Mode(); {
  231. case mode.IsRegular():
  232. if file, err := swarmapi.Open(path.Join(tmpDownload, v.Name())); err != nil {
  233. t.Fatalf("encountered an error opening the file returned from the CLI: %v", err)
  234. } else {
  235. ff := make([]byte, len(data))
  236. io.ReadFull(file, ff)
  237. buf := bytes.NewBufferString(data)
  238. if !bytes.Equal(ff, buf.Bytes()) {
  239. t.Fatalf("retrieved data and posted data not equal!")
  240. }
  241. }
  242. default:
  243. t.Fatalf("this shouldnt happen")
  244. }
  245. }
  246. if err != nil {
  247. t.Fatalf("could not list files at: %v", files)
  248. }
  249. }
  250. }
  251. // testDefaultPathAll tests swarm recursive upload with relative and absolute
  252. // default paths and with encryption.
  253. func testDefaultPathAll(t *testing.T, cluster *testCluster) {
  254. testDefaultPath(t, cluster, false, false)
  255. testDefaultPath(t, cluster, false, true)
  256. testDefaultPath(t, cluster, true, false)
  257. testDefaultPath(t, cluster, true, true)
  258. }
  259. func testDefaultPath(t *testing.T, cluster *testCluster, toEncrypt bool, absDefaultPath bool) {
  260. tmp, err := ioutil.TempDir("", "swarm-defaultpath-test")
  261. if err != nil {
  262. t.Fatal(err)
  263. }
  264. defer os.RemoveAll(tmp)
  265. err = ioutil.WriteFile(filepath.Join(tmp, "index.html"), []byte("<h1>Test</h1>"), 0666)
  266. if err != nil {
  267. t.Fatal(err)
  268. }
  269. err = ioutil.WriteFile(filepath.Join(tmp, "robots.txt"), []byte("Disallow: /"), 0666)
  270. if err != nil {
  271. t.Fatal(err)
  272. }
  273. defaultPath := "index.html"
  274. if absDefaultPath {
  275. defaultPath = filepath.Join(tmp, defaultPath)
  276. }
  277. args := []string{
  278. "--bzzapi",
  279. cluster.Nodes[0].URL,
  280. "--recursive",
  281. "--defaultpath",
  282. defaultPath,
  283. "up",
  284. tmp,
  285. }
  286. if toEncrypt {
  287. args = append(args, "--encrypt")
  288. }
  289. up := runSwarm(t, args...)
  290. hashRegexp := `[a-f\d]{64,128}`
  291. _, matches := up.ExpectRegexp(hashRegexp)
  292. up.ExpectExit()
  293. hash := matches[0]
  294. client := swarmapi.NewClient(cluster.Nodes[0].URL)
  295. m, isEncrypted, err := client.DownloadManifest(hash)
  296. if err != nil {
  297. t.Fatal(err)
  298. }
  299. if toEncrypt != isEncrypted {
  300. t.Error("downloaded manifest is not encrypted")
  301. }
  302. var found bool
  303. var entriesCount int
  304. for _, e := range m.Entries {
  305. entriesCount++
  306. if e.Path == "" {
  307. found = true
  308. }
  309. }
  310. if !found {
  311. t.Error("manifest default entry was not found")
  312. }
  313. if entriesCount != 3 {
  314. t.Errorf("manifest contains %v entries, expected %v", entriesCount, 3)
  315. }
  316. }