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