upload_test.go 9.1 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. swarm "github.com/ethereum/go-ethereum/swarm/api/client"
  32. swarmhttp "github.com/ethereum/go-ethereum/swarm/api/http"
  33. "github.com/ethereum/go-ethereum/swarm/testutil"
  34. "github.com/mattn/go-colorable"
  35. )
  36. func init() {
  37. log.PrintOrigins(true)
  38. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
  39. }
  40. // TestCLISwarmUp tests that running 'swarm up' makes the resulting file
  41. // available from all nodes via the HTTP API
  42. func TestCLISwarmUp(t *testing.T) {
  43. if runtime.GOOS == "windows" {
  44. t.Skip()
  45. }
  46. testCLISwarmUp(false, t)
  47. }
  48. func TestCLISwarmUpRecursive(t *testing.T) {
  49. if runtime.GOOS == "windows" {
  50. t.Skip()
  51. }
  52. testCLISwarmUpRecursive(false, t)
  53. }
  54. // TestCLISwarmUpEncrypted tests that running 'swarm encrypted-up' makes the resulting file
  55. // available from all nodes via the HTTP API
  56. func TestCLISwarmUpEncrypted(t *testing.T) {
  57. if runtime.GOOS == "windows" {
  58. t.Skip()
  59. }
  60. testCLISwarmUp(true, t)
  61. }
  62. func TestCLISwarmUpEncryptedRecursive(t *testing.T) {
  63. if runtime.GOOS == "windows" {
  64. t.Skip()
  65. }
  66. testCLISwarmUpRecursive(true, t)
  67. }
  68. func testCLISwarmUp(toEncrypt bool, t *testing.T) {
  69. log.Info("starting 3 node cluster")
  70. cluster := newTestCluster(t, 3)
  71. defer cluster.Shutdown()
  72. tmpFileName := testutil.TempFileWithContent(t, data)
  73. defer os.Remove(tmpFileName)
  74. // write data to file
  75. hashRegexp := `[a-f\d]{64}`
  76. flags := []string{
  77. "--bzzapi", cluster.Nodes[0].URL,
  78. "up",
  79. tmpFileName}
  80. if toEncrypt {
  81. hashRegexp = `[a-f\d]{128}`
  82. flags = []string{
  83. "--bzzapi", cluster.Nodes[0].URL,
  84. "up",
  85. "--encrypt",
  86. tmpFileName}
  87. }
  88. // upload the file with 'swarm up' and expect a hash
  89. log.Info(fmt.Sprintf("uploading file with 'swarm up'"))
  90. up := runSwarm(t, flags...)
  91. _, matches := up.ExpectRegexp(hashRegexp)
  92. up.ExpectExit()
  93. hash := matches[0]
  94. log.Info("file uploaded", "hash", hash)
  95. // get the file from the HTTP API of each node
  96. for _, node := range cluster.Nodes {
  97. log.Info("getting file from node", "node", node.Name)
  98. res, err := http.Get(node.URL + "/bzz:/" + hash)
  99. if err != nil {
  100. t.Fatal(err)
  101. }
  102. defer res.Body.Close()
  103. reply, err := ioutil.ReadAll(res.Body)
  104. if err != nil {
  105. t.Fatal(err)
  106. }
  107. if res.StatusCode != 200 {
  108. t.Fatalf("expected HTTP status 200, got %s", res.Status)
  109. }
  110. if string(reply) != data {
  111. t.Fatalf("expected HTTP body %q, got %q", data, reply)
  112. }
  113. log.Debug("verifying uploaded file using `swarm down`")
  114. //try to get the content with `swarm down`
  115. tmpDownload, err := ioutil.TempDir("", "swarm-test")
  116. tmpDownload = path.Join(tmpDownload, "tmpfile.tmp")
  117. if err != nil {
  118. t.Fatal(err)
  119. }
  120. defer os.RemoveAll(tmpDownload)
  121. bzzLocator := "bzz:/" + hash
  122. flags = []string{
  123. "--bzzapi", cluster.Nodes[0].URL,
  124. "down",
  125. bzzLocator,
  126. tmpDownload,
  127. }
  128. down := runSwarm(t, flags...)
  129. down.ExpectExit()
  130. fi, err := os.Stat(tmpDownload)
  131. if err != nil {
  132. t.Fatalf("could not stat path: %v", err)
  133. }
  134. switch mode := fi.Mode(); {
  135. case mode.IsRegular():
  136. downloadedBytes, err := ioutil.ReadFile(tmpDownload)
  137. if err != nil {
  138. t.Fatalf("had an error reading the downloaded file: %v", err)
  139. }
  140. if !bytes.Equal(downloadedBytes, bytes.NewBufferString(data).Bytes()) {
  141. t.Fatalf("retrieved data and posted data not equal!")
  142. }
  143. default:
  144. t.Fatalf("expected to download regular file, got %s", fi.Mode())
  145. }
  146. }
  147. timeout := time.Duration(2 * time.Second)
  148. httpClient := http.Client{
  149. Timeout: timeout,
  150. }
  151. // try to squeeze a timeout by getting an non-existent hash from each node
  152. for _, node := range cluster.Nodes {
  153. _, err := httpClient.Get(node.URL + "/bzz:/1023e8bae0f70be7d7b5f74343088ba408a218254391490c85ae16278e230340")
  154. // we're speeding up the timeout here since netstore has a 60 seconds timeout on a request
  155. if err != nil && !strings.Contains(err.Error(), "Client.Timeout exceeded while awaiting headers") {
  156. t.Fatal(err)
  157. }
  158. // this is disabled since it takes 60s due to netstore timeout
  159. // if res.StatusCode != 404 {
  160. // t.Fatalf("expected HTTP status 404, got %s", res.Status)
  161. // }
  162. }
  163. }
  164. func testCLISwarmUpRecursive(toEncrypt bool, t *testing.T) {
  165. fmt.Println("starting 3 node cluster")
  166. cluster := newTestCluster(t, 3)
  167. defer cluster.Shutdown()
  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 := swarm.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. // TestCLISwarmUpDefaultPath tests swarm recursive upload with relative and absolute
  249. // default paths and with encryption.
  250. func TestCLISwarmUpDefaultPath(t *testing.T) {
  251. if runtime.GOOS == "windows" {
  252. t.Skip()
  253. }
  254. testCLISwarmUpDefaultPath(false, false, t)
  255. testCLISwarmUpDefaultPath(false, true, t)
  256. testCLISwarmUpDefaultPath(true, false, t)
  257. testCLISwarmUpDefaultPath(true, true, t)
  258. }
  259. func testCLISwarmUpDefaultPath(toEncrypt bool, absDefaultPath bool, t *testing.T) {
  260. srv := swarmhttp.NewTestSwarmServer(t, serverFunc, nil)
  261. defer srv.Close()
  262. tmp, err := ioutil.TempDir("", "swarm-defaultpath-test")
  263. if err != nil {
  264. t.Fatal(err)
  265. }
  266. defer os.RemoveAll(tmp)
  267. err = ioutil.WriteFile(filepath.Join(tmp, "index.html"), []byte("<h1>Test</h1>"), 0666)
  268. if err != nil {
  269. t.Fatal(err)
  270. }
  271. err = ioutil.WriteFile(filepath.Join(tmp, "robots.txt"), []byte("Disallow: /"), 0666)
  272. if err != nil {
  273. t.Fatal(err)
  274. }
  275. defaultPath := "index.html"
  276. if absDefaultPath {
  277. defaultPath = filepath.Join(tmp, defaultPath)
  278. }
  279. args := []string{
  280. "--bzzapi",
  281. srv.URL,
  282. "--recursive",
  283. "--defaultpath",
  284. defaultPath,
  285. "up",
  286. tmp,
  287. }
  288. if toEncrypt {
  289. args = append(args, "--encrypt")
  290. }
  291. up := runSwarm(t, args...)
  292. hashRegexp := `[a-f\d]{64,128}`
  293. _, matches := up.ExpectRegexp(hashRegexp)
  294. up.ExpectExit()
  295. hash := matches[0]
  296. client := swarm.NewClient(srv.URL)
  297. m, isEncrypted, err := client.DownloadManifest(hash)
  298. if err != nil {
  299. t.Fatal(err)
  300. }
  301. if toEncrypt != isEncrypted {
  302. t.Error("downloaded manifest is not encrypted")
  303. }
  304. var found bool
  305. var entriesCount int
  306. for _, e := range m.Entries {
  307. entriesCount++
  308. if e.Path == "" {
  309. found = true
  310. }
  311. }
  312. if !found {
  313. t.Error("manifest default entry was not found")
  314. }
  315. if entriesCount != 3 {
  316. t.Errorf("manifest contains %v entries, expected %v", entriesCount, 3)
  317. }
  318. }