package crypto var MnemonicWords []string = []string{ "like", "just", "love", "know", "never", "want", "time", "out", "there", "make", "look", "eye", "down", "only", "think", "heart", "back", "then", "into", "about", "more", "away", "still", "them", "take", "thing", "even", "through", "long", "always", "world", "too", "friend", "tell", "try", "hand", "thought", "over", "here", "other", "need", "smile", "again", "much", "cry", "been", "night", "ever", "little", "said", "end", "some", "those", "around", "mind", "people", "girl", "leave", "dream", "left", "turn", "myself", "give", "nothing", "really", "off", "before", "something", "find", "walk", "wish", "good", "once", "place", "ask", "stop", "keep", "watch", "seem", "everything", "wait", "got", "yet", "made", "remember", "start", "alone", "run", "hope", "maybe", "believe", "body", "hate", "after", "close", "talk", "stand", "own", "each", "hurt", "help", "home", "god", "soul", "new", "many", "two", "inside", "should", "true", "first", "fear", "mean", "better", "play", "another", "gone", "change", "use", "wonder", "someone", "hair", "cold", "open", "best", "any", "behind", "happen", "water", "dark", "laugh", "stay", "forever", "name", "work", "show", "sky", "break", "came", "deep", "door", "put", "black", "together", "upon", "happy", "such", "great", "white", "matter", "fill", "past", "please", "burn", "cause", "enough", "touch", "moment", "soon", "voice", "scream", "anything", "stare", "sound", "red", "everyone", "hide", "kiss", "truth", "death", "beautiful", "mine", "blood", "broken", "very", "pass", "next", "forget", "tree", "wrong", "air", "mother", "understand", "lip", "hit", "wall", "memory", "sleep", "free", "high", "realize", "school", "might", "skin", "sweet", "perfect", "blue", "kill", "breath", "dance", "against", "fly", "between", "grow", "strong", "under", "listen", "bring", "sometimes", "speak", "pull", "person", "become", "family", "begin", "ground", "real", "small", "father", "sure", "feet", "rest", "young", "finally", "land", "across", "today", "different", "guy", "line", "fire", "reason", "reach", "second", "slowly", "write", "eat", "smell", "mouth", "step", "learn", "three", "floor", "promise", "breathe", "darkness", "push", "earth", "guess", "save", "song", "above", "along", "both", "color", "house", "almost", "sorry", "anymore", "brother", "okay", "dear", "game", "fade", "already", "apart", "warm", "beauty", "heard", "notice", "question", "shine", "began", "piece", "whole", "shadow", "secret", "street", "within", "finger", "point", "morning", "whisper", "child", "moon", "green", "story", "glass", "kid", "silence", "since", "soft", "yourself", "empty", "shall", "angel", "answer", "baby", "bright", "dad", "path", "worry", "hour", "drop", "follow", "power", "war", "half", "flow", "heaven", "act", "chance", "fact", "least", "tired", "children", "near", "quite", "afraid", "rise", "sea", "taste", "window", "cover", "nice", "trust", "lot", "sad", "cool", "force", "peace", "return", "blind", "easy", "ready", "roll", "rose", "drive", "held", "music", "beneath", "hang", "mom", "paint", "emotion", "quiet", "clear", "cloud", "few", "pretty", "bird", "outside", "paper", "picture", "front", "rock", "simple", "anyone", "meant", "reality", "road", "sense", "waste", "bit", "leaf", "thank", "happiness", "meet", "men", "smoke", "truly", "decide", "self", "age", "book", "form", "alive", "carry", "escape", "damn", "instead", "able", "ice", "minute", "throw", "catch", "leg", "ring", "course", "goodbye", "lead", "poem", "sick", "corner", "desire", "known", "problem", "remind", "shoulder", "suppose", "toward", "wave", "drink", "jump", "woman", "pretend", "sister", "week", "human", "joy", "crack", "grey", "pray", "surprise", "dry", "knee", "less", "search", "bleed", "caught", "clean", "embrace", "future", "king", "son", "sorrow", "chest", "hug", "remain", "sat", "worth", "blow", "daddy", "final", "parent", "tight", "also", "create", "lonely", "safe", "cross", "dress", "evil", "silent", "bone", "fate", "perhaps", "anger", "class", "scar", "snow", "tiny", "tonight", "continue", "control", "dog", "edge", "mirror", "month", "suddenly", "comfort", "given", "loud", "quickly", "gaze", "plan", "rush", "stone", "town", "battle", "ignore", "spirit", "stood", "stupid", "yours", "brown", "build", "dust", "hey", "kept", "pay", "phone", "twist", "although", "ball", "beyond", "hidden", "nose", "taken", "fail", "float", "pure", "somehow", "wash", "wrap", "angry", "cheek", "creature", "forgotten", "heat", "rip", "single", "space", "special", "weak", "whatever", "yell", "anyway", "blame", "job", "choose", "country", "curse", "drift", "echo", "figure", "grew", "laughter", "neck", "suffer", "worse", "yeah", "disappear", "foot", "forward", "knife", "mess", "somewhere", "stomach", "storm", "beg", "idea", "lift", "offer", "breeze", "field", "five", "often", "simply", "stuck", "win", "allow", "confuse", "enjoy", "except", "flower", "seek", "strength", "calm", "grin", "gun", "heavy", "hill", "large", "ocean", "shoe", "sigh", "straight", "summer", "tongue", "accept", "crazy", "everyday", "exist", "grass", "mistake", "sent", "shut", "surround", "table", "ache", "brain", "destroy", "heal", "nature", "shout", "sign", "stain", "choice", "doubt", "glance", "glow", "mountain", "queen", "stranger", "throat", "tomorrow", "city", "either", "fish", "flame", "rather", "shape", "spin", "spread", "ash", "distance", "finish", "image", "imagine", "important", "nobody", "shatter", "warmth", "became", "feed", "flesh", "funny", "lust", "shirt", "trouble", "yellow", "attention", "bare", "bite", "money", "protect", "amaze", "appear", "born", "choke", "completely", "daughter", "fresh", "friendship", "gentle", "probably", "six", "deserve", "expect", "grab", "middle", "nightmare", "river", "thousand", "weight", "worst", "wound", "barely", "bottle", "cream", "regret", "relationship", "stick", "test", "crush", "endless", "fault", "itself", "rule", "spill", "art", "circle", "join", "kick", "mask", "master", "passion", "quick", "raise", "smooth", "unless", "wander", "actually", "broke", "chair", "deal", "favorite", "gift", "note", "number", "sweat", "box", "chill", "clothes", "lady", "mark", "park", "poor", "sadness", "tie", "animal", "belong", "brush", "consume", "dawn", "forest", "innocent", "pen", "pride", "stream", "thick", "clay", "complete", "count", "draw", "faith", "press", "silver", "struggle", "surface", "taught", "teach", "wet", "bless", "chase", "climb", "enter", "letter", "melt", "metal", "movie", "stretch", "swing", "vision", "wife", "beside", "crash", "forgot", "guide", "haunt", "joke", "knock", "plant", "pour", "prove", "reveal", "steal", "stuff", "trip", "wood", "wrist", "bother", "bottom", "crawl", "crowd", "fix", "forgive", "frown", "grace", "loose", "lucky", "party", "release", "surely", "survive", "teacher", "gently", "grip", "speed", "suicide", "travel", "treat", "vein", "written", "cage", "chain", "conversation", "date", "enemy", "however", "interest", "million", "page", "pink", "proud", "sway", "themselves", "winter", "church", "cruel", "cup", "demon", "experience", "freedom", "pair", "pop", "purpose", "respect", "shoot", "softly", "state", "strange", "bar", "birth", "curl", "dirt", "excuse", "lord", "lovely", "monster", "order", "pack", "pants", "pool", "scene", "seven", "shame", "slide", "ugly", "among", "blade", "blonde", "closet", "creek", "deny", "drug", "eternity", "gain", "grade", "handle", "key", "linger", "pale", "prepare", "swallow", "swim", "tremble", "wheel", "won", "cast", "cigarette", "claim", "college", "direction", "dirty", "gather", "ghost", "hundred", "loss", "lung", "orange", "present", "swear", "swirl", "twice", "wild", "bitter", "blanket", "doctor", "everywhere", "flash", "grown", "knowledge", "numb", "pressure", "radio", "repeat", "ruin", "spend", "unknown", "buy", "clock", "devil", "early", "false", "fantasy", "pound", "precious", "refuse", "sheet", "teeth", "welcome", "add", "ahead", "block", "bury", "caress", "content", "depth", "despite", "distant", "marry", "purple", "threw", "whenever", "bomb", "dull", "easily", "grasp", "hospital", "innocence", "normal", "receive", "reply", "rhyme", "shade", "someday", "sword", "toe", "visit", "asleep", "bought", "center", "consider", "flat", "hero", "history", "ink", "insane", "muscle", "mystery", "pocket", "reflection", "shove", "silently", "smart", "soldier", "spot", "stress", "train", "type", "view", "whether", "bus", "energy", "explain", "holy", "hunger", "inch", "magic", "mix", "noise", "nowhere", "prayer", "presence", "shock", "snap", "spider", "study", "thunder", "trail", "admit", "agree", "bag", "bang", "bound", "butterfly", "cute", "exactly", "explode", "familiar", "fold", "further", "pierce", "reflect", "scent", "selfish", "sharp", "sink", "spring", "stumble", "universe", "weep", "women", "wonderful", "action", "ancient", "attempt", "avoid", "birthday", "branch", "chocolate", "core", "depress", "drunk", "especially", "focus", "fruit", "honest", "match", "palm", "perfectly", "pillow", "pity", "poison", "roar", "shift", "slightly", "thump", "truck", "tune", "twenty", "unable", "wipe", "wrote", "coat", "constant", "dinner", "drove", "egg", "eternal", "flight", "flood", "frame", "freak", "gasp", "glad", "hollow", "motion", "peer", "plastic", "root", "screen", "season", "sting", "strike", "team", "unlike", "victim", "volume", "warn", "weird", "attack", "await", "awake", "built", "charm", "crave", "despair", "fought", "grant", "grief", "horse", "limit", "message", "ripple", "sanity", "scatter", "serve", "split", "string", "trick", "annoy", "blur", "boat", "brave", "clearly", "cling", "connect", "fist", "forth", "imagination", "iron", "jock", "judge", "lesson", "milk", "misery", "nail", "naked", "ourselves", "poet", "possible", "princess", "sail", "size", "snake", "society", "stroke", "torture", "toss", "trace", "wise", "bloom", "bullet", "cell", "check", "cost", "darling", "during", "footstep", "fragile", "hallway", "hardly", "horizon", "invisible", "journey", "midnight", "mud", "nod", "pause", "relax", "shiver", "sudden", "value", "youth", "abuse", "admire", "blink", "breast", "bruise", "constantly", "couple", "creep", "curve", "difference", "dumb", "emptiness", "gotta", "honor", "plain", "planet", "recall", "rub", "ship", "slam", "soar", "somebody", "tightly", "weather", "adore", "approach", "bond", "bread", "burst", "candle", "coffee", "cousin", "crime", "desert", "flutter", "frozen", "grand", "heel", "hello", "language", "level", "movement", "pleasure", "powerful", "random", "rhythm", "settle", "silly", "slap", "sort", "spoken", "steel", "threaten", "tumble", "upset", "aside", "awkward", "bee", "blank", "board", "button", "card", "carefully", "complain", "crap", "deeply", "discover", "drag", "dread", "effort", "entire", "fairy", "giant", "gotten", "greet", "illusion", "jeans", "leap", "liquid", "march", "mend", "nervous", "nine", "replace", "rope", "spine", "stole", "terror", "accident", "apple", "balance", "boom", "childhood", "collect", "demand", "depression", "eventually", "faint", "glare", "goal", "group", "honey", "kitchen", "laid", "limb", "machine", "mere", "mold", "murder", "nerve", "painful", "poetry", "prince", "rabbit", "shelter", "shore", "shower", "soothe", "stair", "steady", "sunlight", "tangle", "tease", "treasure", "uncle", "begun", "bliss", "canvas", "cheer", "claw", "clutch", "commit", "crimson", "crystal", "delight", "doll", "existence", "express", "fog", "football", "gay", "goose", "guard", "hatred", "illuminate", "mass", "math", "mourn", "rich", "rough", "skip", "stir", "student", "style", "support", "thorn", "tough", "yard", "yearn", "yesterday", "advice", "appreciate", "autumn", "bank", "beam", "bowl", "capture", "carve", "collapse", "confusion", "creation", "dove", "feather", "girlfriend", "glory", "government", "harsh", "hop", "inner", "loser", "moonlight", "neighbor", "neither", "peach", "pig", "praise", "screw", "shield", "shimmer", "sneak", "stab", "subject", "throughout", "thrown", "tower", "twirl", "wow", "army", "arrive", "bathroom", "bump", "cease", "cookie", "couch", "courage", "dim", "guilt", "howl", "hum", "husband", "insult", "led", "lunch", "mock", "mostly", "natural", "nearly", "needle", "nerd", "peaceful", "perfection", "pile", "price", "remove", "roam", "sanctuary", "serious", "shiny", "shook", "sob", "stolen", "tap", "vain", "void", "warrior", "wrinkle", "affection", "apologize", "blossom", "bounce", "bridge", "cheap", "crumble", "decision", "descend", "desperately", "dig", "dot", "flip", "frighten", "heartbeat", "huge", "lazy", "lick", "odd", "opinion", "process", "puzzle", "quietly", "retreat", "score", "sentence", "separate", "situation", "skill", "soak", "square", "stray", "taint", "task", "tide", "underneath", "veil", "whistle", "anywhere", "bedroom", "bid", "bloody", "burden", "careful", "compare", "concern", "curtain", "decay", "defeat", "describe", "double", "dreamer", "driver", "dwell", "evening", "flare", "flicker", "grandma", "guitar", "harm", "horrible", "hungry", "indeed", "lace", "melody", "monkey", "nation", "object", "obviously", "rainbow", "salt", "scratch", "shown", "shy", "stage", "stun", "third", "tickle", "useless", "weakness", "worship", "worthless", "afternoon", "beard", "boyfriend", "bubble", "busy", "certain", "chin", "concrete", "desk", "diamond", "doom", "drawn", "due", "felicity", "freeze", "frost", "garden", "glide", "harmony", "hopefully", "hunt", "jealous", "lightning", "mama", "mercy", "peel", "physical", "position", "pulse", "punch", "quit", "rant", "respond", "salty", "sane", "satisfy", "savior", "sheep", "slept", "social", "sport", "tuck", "utter", "valley", "wolf", "aim", "alas", "alter", "arrow", "awaken", "beaten", "belief", "brand", "ceiling", "cheese", "clue", "confidence", "connection", "daily", "disguise", "eager", "erase", "essence", "everytime", "expression", "fan", "flag", "flirt", "foul", "fur", "giggle", "glorious", "ignorance", "law", "lifeless", "measure", "mighty", "muse", "north", "opposite", "paradise", "patience", "patient", "pencil", "petal", "plate", "ponder", "possibly", "practice", "slice", "spell", "stock", "strife", "strip", "suffocate", "suit", "tender", "tool", "trade", "velvet", "verse", "waist", "witch", "aunt", "bench", "bold", "cap", "certainly", "click", "companion", "creator", "dart", "delicate", "determine", "dish", "dragon", "drama", "drum", "dude", "everybody", "feast", "forehead", "former", "fright", "fully", "gas", "hook", "hurl", "invite", "juice", "manage", "moral", "possess", "raw", "rebel", "royal", "scale", "scary", "several", "slight", "stubborn", "swell", "talent", "tea", "terrible", "thread", "torment", "trickle", "usually", "vast", "violence", "weave", "acid", "agony", "ashamed", "awe", "belly", "blend", "blush", "character", "cheat", "common", "company", "coward", "creak", "danger", "deadly", "defense", "define", "depend", "desperate", "destination", "dew", "duck", "dusty", "embarrass", "engine", "example", "explore", "foe", "freely", "frustrate", "generation", "glove", "guilty", "health", "hurry", "idiot", "impossible", "inhale", "jaw", "kingdom", "mention", "mist", "moan", "mumble", "mutter", "observe", "ode", "pathetic", "pattern", "pie", "prefer", "puff", "rape", "rare", "revenge", "rude", "scrape", "spiral", "squeeze", "strain", "sunset", "suspend", "sympathy", "thigh", "throne", "total", "unseen", "weapon", "weary", } 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package client

import (
    "bytes"
    "io/ioutil"
    "os"
    "path/filepath"
    "reflect"
    "sort"
    "testing"

    "github.com/ethereum/go-ethereum/swarm/storage/mru/lookup"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/swarm/api"
    swarmhttp "github.com/ethereum/go-ethereum/swarm/api/http"
    "github.com/ethereum/go-ethereum/swarm/multihash"
    "github.com/ethereum/go-ethereum/swarm/storage/mru"
    "github.com/ethereum/go-ethereum/swarm/testutil"
)

func serverFunc(api *api.API) testutil.TestServer {
    return swarmhttp.NewServer(api, "")
}

// TestClientUploadDownloadRaw test uploading and downloading raw data to swarm
func TestClientUploadDownloadRaw(t *testing.T) {
    testClientUploadDownloadRaw(false, t)
}
func TestClientUploadDownloadRawEncrypted(t *testing.T) {
    testClientUploadDownloadRaw(true, t)
}

func testClientUploadDownloadRaw(toEncrypt bool, t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    client := NewClient(srv.URL)

    // upload some raw data
    data := []byte("foo123")
    hash, err := client.UploadRaw(bytes.NewReader(data), int64(len(data)), toEncrypt)
    if err != nil {
        t.Fatal(err)
    }

    // check we can download the same data
    res, isEncrypted, err := client.DownloadRaw(hash)
    if err != nil {
        t.Fatal(err)
    }
    if isEncrypted != toEncrypt {
        t.Fatalf("Expected encyption status %v got %v", toEncrypt, isEncrypted)
    }
    defer res.Close()
    gotData, err := ioutil.ReadAll(res)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(gotData, data) {
        t.Fatalf("expected downloaded data to be %q, got %q", data, gotData)
    }
}

// TestClientUploadDownloadFiles test uploading and downloading files to swarm
// manifests
func TestClientUploadDownloadFiles(t *testing.T) {
    testClientUploadDownloadFiles(false, t)
}

func TestClientUploadDownloadFilesEncrypted(t *testing.T) {
    testClientUploadDownloadFiles(true, t)
}

func testClientUploadDownloadFiles(toEncrypt bool, t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    client := NewClient(srv.URL)
    upload := func(manifest, path string, data []byte) string {
        file := &File{
            ReadCloser: ioutil.NopCloser(bytes.NewReader(data)),
            ManifestEntry: api.ManifestEntry{
                Path:        path,
                ContentType: "text/plain",
                Size:        int64(len(data)),
            },
        }
        hash, err := client.Upload(file, manifest, toEncrypt)
        if err != nil {
            t.Fatal(err)
        }
        return hash
    }
    checkDownload := func(manifest, path string, expected []byte) {
        file, err := client.Download(manifest, path)
        if err != nil {
            t.Fatal(err)
        }
        defer file.Close()
        if file.Size != int64(len(expected)) {
            t.Fatalf("expected downloaded file to be %d bytes, got %d", len(expected), file.Size)
        }
        if file.ContentType != "text/plain" {
            t.Fatalf("expected downloaded file to have type %q, got %q", "text/plain", file.ContentType)
        }
        data, err := ioutil.ReadAll(file)
        if err != nil {
            t.Fatal(err)
        }
        if !bytes.Equal(data, expected) {
            t.Fatalf("expected downloaded data to be %q, got %q", expected, data)
        }
    }

    // upload a file to the root of a manifest
    rootData := []byte("some-data")
    rootHash := upload("", "", rootData)

    // check we can download the root file
    checkDownload(rootHash, "", rootData)

    // upload another file to the same manifest
    otherData := []byte("some-other-data")
    newHash := upload(rootHash, "some/other/path", otherData)

    // check we can download both files from the new manifest
    checkDownload(newHash, "", rootData)
    checkDownload(newHash, "some/other/path", otherData)

    // replace the root file with different data
    newHash = upload(newHash, "", otherData)

    // check both files have the other data
    checkDownload(newHash, "", otherData)
    checkDownload(newHash, "some/other/path", otherData)
}

var testDirFiles = []string{
    "file1.txt",
    "file2.txt",
    "dir1/file3.txt",
    "dir1/file4.txt",
    "dir2/file5.txt",
    "dir2/dir3/file6.txt",
    "dir2/dir4/file7.txt",
    "dir2/dir4/file8.txt",
}

func newTestDirectory(t *testing.T) string {
    dir, err := ioutil.TempDir("", "swarm-client-test")
    if err != nil {
        t.Fatal(err)
    }

    for _, file := range testDirFiles {
        path := filepath.Join(dir, file)
        if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
            os.RemoveAll(dir)
            t.Fatalf("error creating dir for %s: %s", path, err)
        }
        if err := ioutil.WriteFile(path, []byte(file), 0644); err != nil {
            os.RemoveAll(dir)
            t.Fatalf("error writing file %s: %s", path, err)
        }
    }

    return dir
}

// TestClientUploadDownloadDirectory tests uploading and downloading a
// directory of files to a swarm manifest
func TestClientUploadDownloadDirectory(t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    dir := newTestDirectory(t)
    defer os.RemoveAll(dir)

    // upload the directory
    client := NewClient(srv.URL)
    defaultPath := testDirFiles[0]
    hash, err := client.UploadDirectory(dir, defaultPath, "", false)
    if err != nil {
        t.Fatalf("error uploading directory: %s", err)
    }

    // check we can download the individual files
    checkDownloadFile := func(path string, expected []byte) {
        file, err := client.Download(hash, path)
        if err != nil {
            t.Fatal(err)
        }
        defer file.Close()
        data, err := ioutil.ReadAll(file)
        if err != nil {
            t.Fatal(err)
        }
        if !bytes.Equal(data, expected) {
            t.Fatalf("expected data to be %q, got %q", expected, data)
        }
    }
    for _, file := range testDirFiles {
        checkDownloadFile(file, []byte(file))
    }

    // check we can download the default path
    checkDownloadFile("", []byte(testDirFiles[0]))

    // check we can download the directory
    tmp, err := ioutil.TempDir("", "swarm-client-test")
    if err != nil {
        t.Fatal(err)
    }
    defer os.RemoveAll(tmp)
    if err := client.DownloadDirectory(hash, "", tmp, ""); err != nil {
        t.Fatal(err)
    }
    for _, file := range testDirFiles {
        data, err := ioutil.ReadFile(filepath.Join(tmp, file))
        if err != nil {
            t.Fatal(err)
        }
        if !bytes.Equal(data, []byte(file)) {
            t.Fatalf("expected data to be %q, got %q", file, data)
        }
    }
}

// TestClientFileList tests listing files in a swarm manifest
func TestClientFileList(t *testing.T) {
    testClientFileList(false, t)
}

func TestClientFileListEncrypted(t *testing.T) {
    testClientFileList(true, t)
}

func testClientFileList(toEncrypt bool, t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    dir := newTestDirectory(t)
    defer os.RemoveAll(dir)

    client := NewClient(srv.URL)
    hash, err := client.UploadDirectory(dir, "", "", toEncrypt)
    if err != nil {
        t.Fatalf("error uploading directory: %s", err)
    }

    ls := func(prefix string) []string {
        list, err := client.List(hash, prefix, "")
        if err != nil {
            t.Fatal(err)
        }
        paths := make([]string, 0, len(list.CommonPrefixes)+len(list.Entries))
        paths = append(paths, list.CommonPrefixes...)
        for _, entry := range list.Entries {
            paths = append(paths, entry.Path)
        }
        sort.Strings(paths)
        return paths
    }

    tests := map[string][]string{
        "":                    {"dir1/", "dir2/", "file1.txt", "file2.txt"},
        "file":                {"file1.txt", "file2.txt"},
        "file1":               {"file1.txt"},
        "file2.txt":           {"file2.txt"},
        "file12":              {},
        "dir":                 {"dir1/", "dir2/"},
        "dir1":                {"dir1/"},
        "dir1/":               {"dir1/file3.txt", "dir1/file4.txt"},
        "dir1/file":           {"dir1/file3.txt", "dir1/file4.txt"},
        "dir1/file3.txt":      {"dir1/file3.txt"},
        "dir1/file34":         {},
        "dir2/":               {"dir2/dir3/", "dir2/dir4/", "dir2/file5.txt"},
        "dir2/file":           {"dir2/file5.txt"},
        "dir2/dir":            {"dir2/dir3/", "dir2/dir4/"},
        "dir2/dir3/":          {"dir2/dir3/file6.txt"},
        "dir2/dir4/":          {"dir2/dir4/file7.txt", "dir2/dir4/file8.txt"},
        "dir2/dir4/file":      {"dir2/dir4/file7.txt", "dir2/dir4/file8.txt"},
        "dir2/dir4/file7.txt": {"dir2/dir4/file7.txt"},
        "dir2/dir4/file78":    {},
    }
    for prefix, expected := range tests {
        actual := ls(prefix)
        if !reflect.DeepEqual(actual, expected) {
            t.Fatalf("expected prefix %q to return %v, got %v", prefix, expected, actual)
        }
    }
}

// TestClientMultipartUpload tests uploading files to swarm using a multipart
// upload
func TestClientMultipartUpload(t *testing.T) {
    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    defer srv.Close()

    // define an uploader which uploads testDirFiles with some data
    data := []byte("some-data")
    uploader := UploaderFunc(func(upload UploadFn) error {
        for _, name := range testDirFiles {
            file := &File{
                ReadCloser: ioutil.NopCloser(bytes.NewReader(data)),
                ManifestEntry: api.ManifestEntry{
                    Path:        name,
                    ContentType: "text/plain",
                    Size:        int64(len(data)),
                },
            }
            if err := upload(file); err != nil {
                return err
            }
        }
        return nil
    })

    // upload the files as a multipart upload
    client := NewClient(srv.URL)
    hash, err := client.MultipartUpload("", uploader)
    if err != nil {
        t.Fatal(err)
    }

    // check we can download the individual files
    checkDownloadFile := func(path string) {
        file, err := client.Download(hash, path)
        if err != nil {
            t.Fatal(err)
        }
        defer file.Close()
        gotData, err := ioutil.ReadAll(file)
        if err != nil {
            t.Fatal(err)
        }
        if !bytes.Equal(gotData, data) {
            t.Fatalf("expected data to be %q, got %q", data, gotData)
        }
    }
    for _, file := range testDirFiles {
        checkDownloadFile(file)
    }
}

func newTestSigner() (*mru.GenericSigner, error) {
    privKey, err := crypto.HexToECDSA("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")
    if err != nil {
        return nil, err
    }
    return mru.NewGenericSigner(privKey), nil
}

// test the transparent resolving of multihash resource types with bzz:// scheme
//
// first upload data, and store the multihash to the resulting manifest in a resource update
// retrieving the update with the multihash should return the manifest pointing directly to the data
// and raw retrieve of that hash should return the data
func TestClientCreateResourceMultihash(t *testing.T) {

    signer, _ := newTestSigner()

    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    client := NewClient(srv.URL)
    defer srv.Close()

    // add the data our multihash aliased manifest will point to
    databytes := []byte("bar")

    swarmHash, err := client.UploadRaw(bytes.NewReader(databytes), int64(len(databytes)), false)
    if err != nil {
        t.Fatalf("Error uploading raw test data: %s", err)
    }

    s := common.FromHex(swarmHash)
    mh := multihash.ToMultihash(s)

    // our mutable resource topic
    topic, _ := mru.NewTopic("foo.eth", nil)

    createRequest := mru.NewFirstRequest(topic)

    createRequest.SetData(mh)
    if err := createRequest.Sign(signer); err != nil {
        t.Fatalf("Error signing update: %s", err)
    }

    resourceManifestHash, err := client.CreateResource(createRequest)

    if err != nil {
        t.Fatalf("Error creating resource: %s", err)
    }

    correctManifestAddrHex := "6ef40ba1492cf2a029dc9a8b5896c822cf689d3cd010842f4f1744e6db8824bd"
    if resourceManifestHash != correctManifestAddrHex {
        t.Fatalf("Response resource manifest mismatch, expected '%s', got '%s'", correctManifestAddrHex, resourceManifestHash)
    }

    // Check we get a not found error when trying to get the resource with a made-up manifest
    _, err = client.GetResource(nil, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
    if err != ErrNoResourceUpdatesFound {
        t.Fatalf("Expected to receive ErrNoResourceUpdatesFound error. Got: %s", err)
    }

    reader, err := client.GetResource(nil, correctManifestAddrHex)
    if err != nil {
        t.Fatalf("Error retrieving resource: %s", err)
    }
    defer reader.Close()
    gotData, err := ioutil.ReadAll(reader)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(mh, gotData) {
        t.Fatalf("Expected: %v, got %v", mh, gotData)
    }

}

// TestClientCreateUpdateResource will check that mutable resources can be created and updated via the HTTP client.
func TestClientCreateUpdateResource(t *testing.T) {

    signer, _ := newTestSigner()

    srv := testutil.NewTestSwarmServer(t, serverFunc, nil)
    client := NewClient(srv.URL)
    defer srv.Close()

    // set raw data for the resource
    databytes := []byte("En un lugar de La Mancha, de cuyo nombre no quiero acordarme...")

    // our mutable resource name
    topic, _ := mru.NewTopic("El Quijote", nil)
    createRequest := mru.NewFirstRequest(topic)

    createRequest.SetData(databytes)
    if err := createRequest.Sign(signer); err != nil {
        t.Fatalf("Error signing update: %s", err)
    }

    resourceManifestHash, err := client.CreateResource(createRequest)

    correctManifestAddrHex := "fcb8e75f53e480e197c083ad1976d265674d0ce776f2bf359c09c413fb5230b8"
    if resourceManifestHash != correctManifestAddrHex {
        t.Fatalf("Response resource manifest mismatch, expected '%s', got '%s'", correctManifestAddrHex, resourceManifestHash)
    }

    reader, err := client.GetResource(nil, correctManifestAddrHex)
    if err != nil {
        t.Fatalf("Error retrieving resource: %s", err)
    }
    defer reader.Close()
    gotData, err := ioutil.ReadAll(reader)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(databytes, gotData) {
        t.Fatalf("Expected: %v, got %v", databytes, gotData)
    }

    // define different data
    databytes = []byte("... no ha mucho tiempo que vivĂ­a un hidalgo de los de lanza en astillero ...")

    updateRequest, err := client.GetResourceMetadata(nil, correctManifestAddrHex)
    if err != nil {
        t.Fatalf("Error retrieving update request template: %s", err)
    }

    updateRequest.SetData(databytes)
    if err := updateRequest.Sign(signer); err != nil {
        t.Fatalf("Error signing update: %s", err)
    }

    if err = client.UpdateResource(updateRequest); err != nil {
        t.Fatalf("Error updating resource: %s", err)
    }

    reader, err = client.GetResource(nil, correctManifestAddrHex)
    if err != nil {
        t.Fatalf("Error retrieving resource: %s", err)
    }
    defer reader.Close()
    gotData, err = ioutil.ReadAll(reader)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(databytes, gotData) {
        t.Fatalf("Expected: %v, got %v", databytes, gotData)
    }

    // now try retrieving resource without a manifest

    view := &mru.Feed{
        Topic: topic,
        User:  signer.Address(),
    }

    lookupParams := mru.NewQueryLatest(view, lookup.NoClue)
    reader, err = client.GetResource(lookupParams, "")
    if err != nil {
        t.Fatalf("Error retrieving resource: %s", err)
    }
    defer reader.Close()
    gotData, err = ioutil.ReadAll(reader)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(databytes, gotData) {
        t.Fatalf("Expected: %v, got %v", databytes, gotData)
    }
}