From 46bf846ef68099704451da3fd6dc7d7cb8f76d2b Mon Sep 17 00:00:00 2001 From: arnaucode Date: Mon, 24 Jul 2017 09:57:11 +0200 Subject: [PATCH] added server, route Get NetworkMap, added save to mongodb Nodes and Edges --- exploreBlockchain.go | 22 ++++++++ ipFilter.go | 30 +++++++++++ main.go | 19 ++++++- mongoModels.go | 7 ++- mongoOperations.go | 51 ++++++++++++++++--- serverConfig.go | 69 +++++++++++++++++++++++++ serverRoutes.go | 117 +++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 304 insertions(+), 11 deletions(-) create mode 100644 ipFilter.go create mode 100644 serverConfig.go create mode 100644 serverRoutes.go diff --git a/exploreBlockchain.go b/exploreBlockchain.go index 7cfe019..0a7b241 100644 --- a/exploreBlockchain.go +++ b/exploreBlockchain.go @@ -91,6 +91,28 @@ func explore(client *btcrpcclient.Client, blockHash string) { blockHash = block.NextHash //analyze block creator + for _, t := range newBlock.Tx { + var n1 NodeModel + var n2 NodeModel + n1.Id = t.From + n1.Label = t.From + n1.Value = 1 + n1.Shape = "dot" + n2.Id = t.To + n2.Label = t.To + n2.Value = 1 + n2.Shape = "dot" + + var e EdgeModel + e.From = t.From + e.To = t.To + e.Label = t.Amount + e.Txid = t.Txid + + saveNode(nodeCollection, n1) + saveNode(nodeCollection, n2) + saveEdge(edgeCollection, e) + } } fmt.Print("realBlocks (blocks with Fee and Amount values): ") diff --git a/ipFilter.go b/ipFilter.go new file mode 100644 index 0000000..67b513a --- /dev/null +++ b/ipFilter.go @@ -0,0 +1,30 @@ +package main + +import ( + "errors" + "fmt" + "net/http" + "strings" +) + +func ipFilter(w http.ResponseWriter, r *http.Request) { + var err error + fmt.Println(r.RemoteAddr) + reqIP := strings.Split(r.RemoteAddr, ":")[0] + for _, ip := range serverConfig.BlockedIPs { + if reqIP == ip { + err = errors.New("ip not allowed to post images") + } + } + + for _, ip := range serverConfig.AllowedIPs { + if reqIP != ip { + err = errors.New("ip not allowed to post images") + } + } + //return err + if err != nil { + fmt.Fprintln(w, err.Error()) + return + } +} diff --git a/main.go b/main.go index a444924..e0d3e76 100644 --- a/main.go +++ b/main.go @@ -1,11 +1,15 @@ package main import ( + "fmt" "log" + "net/http" + "os" mgo "gopkg.in/mgo.v2" "github.com/btcsuite/btcrpcclient" + "github.com/fatih/color" ) var blockCollection *mgo.Collection @@ -45,8 +49,12 @@ func main() { for label, amount := range accounts { log.Printf("%s: %s", label, amount) } - - explore(client, config.GenesisBlock) + if len(os.Args) > 1 { + if os.Args[1] == "-explore" { + fmt.Println("starting to explore blockchain") + explore(client, config.GenesisBlock) + } + } // Get the current block count. blockCount, err := client.GetBlockCount() @@ -54,4 +62,11 @@ func main() { log.Fatal(err) } log.Printf("Block count: %d", blockCount) + + //http server start + readServerConfig("./serverConfig.json") + color.Green("server running") + router := NewRouter() + log.Fatal(http.ListenAndServe(":"+serverConfig.ServerPort, router)) + } diff --git a/mongoModels.go b/mongoModels.go index 3d8d419..6d3a557 100644 --- a/mongoModels.go +++ b/mongoModels.go @@ -25,8 +25,13 @@ type NodeModel struct { } type EdgeModel struct { + Txid string From string To string - Label string + Label float64 Arrows string } +type NetworkModel struct { + Nodes []NodeModel + Edges []EdgeModel +} diff --git a/mongoOperations.go b/mongoOperations.go index 71b9def..b4fa91e 100644 --- a/mongoOperations.go +++ b/mongoOperations.go @@ -63,13 +63,48 @@ func saveBlock(c *mgo.Collection, block BlockModel) { } } -func saveNode(c *mgo.Collection, block BlockModel) { - var node NodeModel - node.Id = block.Hash - node.Label = block.Hash - node.Title = block.Hash - node.Value = 1 - node.Shape = "dot" + +func getAllNodes() ([]NodeModel, error) { + result := []NodeModel{} + iter := nodeCollection.Find(bson.M{}).Limit(500).Iter() + err := iter.All(&result) + return result, err +} + +func saveNode(c *mgo.Collection, node NodeModel) { + //first, check if the node already exists + result := NodeModel{} + err := c.Find(bson.M{"id": node.Id}).One(&result) + if err != nil { + //node not found, so let's add a new entry + err = c.Insert(node) + check(err) + } else { + err = c.Update(bson.M{"id": node.Id}, &node) + if err != nil { + log.Fatal(err) + } + } } -func saveEdge(c *mgo.Collection, block BlockModel) { + +func getAllEdges() ([]EdgeModel, error) { + result := []EdgeModel{} + iter := edgeCollection.Find(bson.M{}).Limit(500).Iter() + err := iter.All(&result) + return result, err +} +func saveEdge(c *mgo.Collection, edge EdgeModel) { + //first, check if the edge already exists + result := EdgeModel{} + err := c.Find(bson.M{"txid": edge.Txid}).One(&result) + if err != nil { + //edge not found, so let's add a new entry + err = c.Insert(edge) + check(err) + } else { + err = c.Update(bson.M{"txid": edge.Txid}, &edge) + if err != nil { + log.Fatal(err) + } + } } diff --git a/serverConfig.go b/serverConfig.go new file mode 100644 index 0000000..3411e09 --- /dev/null +++ b/serverConfig.go @@ -0,0 +1,69 @@ +package main + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "log" + "net/http" + "time" + + "github.com/gorilla/mux" +) + +type Route struct { + Name string + Method string + Pattern string + HandlerFunc http.HandlerFunc +} + +//server config +type ServerConfig struct { + ServerIP string `json:"serverIP"` + ServerPort string `json:"serverPort"` + AllowedIPs []string `json:"allowedIPs"` + BlockedIPs []string `json:"blockedIPs"` +} + +var serverConfig ServerConfig + +func readServerConfig(path string) { + file, err := ioutil.ReadFile(path) + if err != nil { + fmt.Println("error: ", err) + } + content := string(file) + json.Unmarshal([]byte(content), &serverConfig) +} + +func Logger(inner http.Handler, name string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + inner.ServeHTTP(w, r) + + log.Printf( + "%s\t%s\t%s\t%s", + r.Method, + r.RequestURI, + name, + time.Since(start), + ) + }) +} +func NewRouter() *mux.Router { + router := mux.NewRouter().StrictSlash(true) + for _, route := range routes { + var handler http.Handler + handler = route.HandlerFunc + handler = Logger(handler, route.Name) + + router. + Methods(route.Method). + Path(route.Pattern). + Name(route.Name). + Handler(handler) + } + return router +} diff --git a/serverRoutes.go b/serverRoutes.go new file mode 100644 index 0000000..b564fea --- /dev/null +++ b/serverRoutes.go @@ -0,0 +1,117 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" +) + +type Routes []Route + +var routes = Routes{ + Route{ + "Index", + "GET", + "/", + Index, + }, + /* Route{ + "Recommendations", + "GET", + "/r/{userid}/{nrec}", + Recommendations, + }, + */ + Route{ + "NetworkMap", + "Get", + "/map", + NetworkMap, + }, + /* + Route{ + "SelectItem", + "GET", + "/selectItem/{userid}/{itemid}", + SelectItem, + }, + */ +} + +//ROUTES + +func Index(w http.ResponseWriter, r *http.Request) { + fmt.Fprintln(w, "ask for recommendations in /r") +} + +/* +func NewUser(w http.ResponseWriter, r *http.Request) { + ipFilter(w, r) + decoder := json.NewDecoder(r.Body) + var newUser UserModel + err := decoder.Decode(&newUser) + check(err) + defer r.Body.Close() + + saveUser(userCollection, newUser) + + fmt.Println(newUser) + fmt.Fprintln(w, "new user added: ", newUser.ID) +} +*/ +func NetworkMap(w http.ResponseWriter, r *http.Request) { + ipFilter(w, r) + + nodes, err := getAllNodes() + check(err) + edges, err := getAllEdges() + check(err) + + var network NetworkModel + network.Nodes = nodes + network.Edges = edges + + //convert []resp struct to json + jNetwork, err := json.Marshal(network) + check(err) + + fmt.Fprintln(w, string(jNetwork)) +} + +/* +func SelectItem(w http.ResponseWriter, r *http.Request) { + ipFilter(w, r) + vars := mux.Vars(r) + userid := vars["userid"] + itemid := vars["itemid"] + //find item + item, err := getItemById(itemid) + if err != nil { + fmt.Fprintln(w, "item "+itemid+" not found") + } + + //find user + user, err := getUserById(userid) + if err != nil { + fmt.Fprintln(w, "user "+userid+" not found") + } + + //increase TActed in item + item.TActed = item.TActed + 1 + + //save item + item, err = updateItem(item) + check(err) + fmt.Println(item) + + //add item to []Actions of user + user.Actions = append(user.Actions, itemid) + + //save user + user, err = updateUser(user) + check(err) + fmt.Println(user) + + fmt.Fprintln(w, "user: "+userid+", selects item: "+itemid) +} +*/