upload_test.go 8.9 KB

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