From 99a71873b85531f51b8958ed590d6c560c9555bb Mon Sep 17 00:00:00 2001 From: imw Date: Fri, 7 Dec 2018 14:27:38 +0100 Subject: [PATCH] initial implementation of publish, pin, and retrieve functions --- data/data.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++ data/data_test.go | 34 +++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 data/data.go create mode 100644 data/data_test.go diff --git a/data/data.go b/data/data.go new file mode 100644 index 0000000..ca1d5bb --- /dev/null +++ b/data/data.go @@ -0,0 +1,51 @@ +package data + +import ( + "os" + "fmt" + "bytes" + "io/ioutil" + shell "github.com/ipfs/go-ipfs-api" +) + +type votePacket struct { + PID uint + Nullifier string + Vote string + Franchise string +} + +func publish(object []byte) (string) { + sh := shell.NewShell("localhost:5001") + cid, err := sh.Add(bytes.NewBuffer(object)) + if err != nil { + fmt.Fprintf(os.Stderr, "error: %s", err) + os.Exit(1) + } + return cid +} + +func pin(path string) { + sh := shell.NewShell("localhost:5001") + err := sh.Pin(path) + if err != nil{ + fmt.Fprintf(os.Stderr, "error: %s", err) + os.Exit(1) + } +} + + +func retrieve(hash string) ([]byte){ + sh := shell.NewShell("localhost:5001") + reader, err := sh.Cat(hash) + if err != nil { + fmt.Fprintf(os.Stderr, "error: %s", err) + os.Exit(1) + } + content, err := ioutil.ReadAll(reader) + if err != nil { + fmt.Fprintf(os.Stderr, "error: %s", err) + os.Exit(1) + } + return content +} diff --git a/data/data_test.go b/data/data_test.go new file mode 100644 index 0000000..60b49b0 --- /dev/null +++ b/data/data_test.go @@ -0,0 +1,34 @@ +package data + +import ( + "testing" + "fmt" + "encoding/json" + "strings" +) + +func TestPublishAndRetrieve(t *testing.T) { + t.Log("Testing adding json") + + exampleVote := votePacket{ + 000001, + "12309801002", + "nynnynnnynnnyy", + "132498-0-02103908", + } + + testObject, err := json.Marshal(exampleVote) + if err != nil { + t.Errorf("Bad test JSON: %s", err) + } + prepub := string(testObject) + + hash := publish(testObject) + content := retrieve(hash) + postpub := string(content) + //fmt.Println(hash) + //fmt.Println(string(content)) + if strings.Compare(prepub,postpub) != 0 { + t.Errorf("Published file doesn't match. Expected:\n %s \n Got: \n %s \n", prepub, postpub) + } +}