arnaucube
arnaucube/goBlockchainDataAnalysisPublic Self-hosted repository
goBlockchainDataAnalysis/serverRoutes.go
serverRoutes.goRaw
  1package main
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"net/http"
  7	"sort"
  8	"strconv"
  9	"time"
 10
 11	"gopkg.in/mgo.v2/bson"
 12
 13	"github.com/gorilla/mux"
 14)
 15
 16type Routes []Route
 17
 18var routes = Routes{
 19	Route{
 20		"Index",
 21		"GET",
 22		"/",
 23		Index,
 24	},
 25	Route{
 26		"Stats",
 27		"Get",
 28		"/stats",
 29		Stats,
 30	},
 31	Route{
 32		"AllAddresses",
 33		"Get",
 34		"/alladdresses",
 35		AllAddresses,
 36	},
 37	Route{
 38		"GetLastAddr",
 39		"Get",
 40		"/lastaddr",
 41		GetLastAddr,
 42	},
 43	Route{
 44		"GetLastTx",
 45		"Get",
 46		"/lasttx",
 47		GetLastTx,
 48	},
 49	Route{
 50		"AddressNetwork",
 51		"GET",
 52		"/address/network/{address}",
 53		AddressNetwork,
 54	},
 55	Route{
 56		"Address",
 57		"GET",
 58		"/address/{hash}",
 59		Address,
 60	},
 61	Route{
 62		"AddressSankey",
 63		"GET",
 64		"/address/sankey/{address}",
 65		AddressSankey,
 66	},
 67	Route{
 68		"NetworkMap",
 69		"Get",
 70		"/map",
 71		NetworkMap,
 72	},
 73	Route{
 74		"GetTotalHourAnalysis",
 75		"Get",
 76		"/totalhouranalysis",
 77		GetTotalHourAnalysis,
 78	},
 79	Route{
 80		"GetLast24HourAnalysis",
 81		"Get",
 82		"/last24hour",
 83		GetLast24HourAnalysis,
 84	},
 85	Route{
 86		"GetLast7DayAnalysis",
 87		"Get",
 88		"/last7day",
 89		GetLast7DayAnalysis,
 90	},
 91	Route{
 92		"GetLast7DayHourAnalysis",
 93		"Get",
 94		"/last7dayhour",
 95		GetLast7DayHourAnalysis,
 96	},
 97}
 98
 99//ROUTES
100
101func Index(w http.ResponseWriter, r *http.Request) {
102	fmt.Fprintln(w, "ask for recommendations in /r")
103	//http.FileServer(http.Dir("./web"))
104}
105
106/*
107func NewUser(w http.ResponseWriter, r *http.Request) {
108	ipFilter(w, r)
109	decoder := json.NewDecoder(r.Body)
110	var newUser UserModel
111	err := decoder.Decode(&newUser)
112	check(err)
113	defer r.Body.Close()
114
115	saveUser(userCollection, newUser)
116
117	fmt.Println(newUser)
118	fmt.Fprintln(w, "new user added: ", newUser.ID)
119}
120*/
121func Stats(w http.ResponseWriter, r *http.Request) {
122	ipFilter(w, r)
123
124	stats := getStats()
125
126	jsonResp, err := json.Marshal(stats)
127	check(err)
128
129	fmt.Fprintln(w, string(jsonResp))
130}
131func AllAddresses(w http.ResponseWriter, r *http.Request) {
132	ipFilter(w, r)
133
134	nodes := []NodeModel{}
135	iter := nodeCollection.Find(bson.M{"type": "address"}).Limit(10000).Iter()
136	err := iter.All(&nodes)
137
138	//convert []resp struct to json
139	jsonNodes, err := json.Marshal(nodes)
140	check(err)
141
142	fmt.Fprintln(w, string(jsonNodes))
143}
144func GetLastAddr(w http.ResponseWriter, r *http.Request) {
145	ipFilter(w, r)
146
147	addresses := []AddressModel{}
148	err := addressCollection.Find(bson.M{}).Limit(10).Sort("-$natural").All(&addresses)
149	check(err)
150
151	//convert []resp struct to json
152	jsonResp, err := json.Marshal(addresses)
153	check(err)
154
155	fmt.Fprintln(w, string(jsonResp))
156}
157func GetLastTx(w http.ResponseWriter, r *http.Request) {
158	ipFilter(w, r)
159
160	txs := []TxModel{}
161	err := txCollection.Find(bson.M{}).Limit(10).Sort("-$natural").All(&txs)
162	check(err)
163
164	//convert []resp struct to json
165	jsonData, err := json.Marshal(txs)
166	check(err)
167
168	fmt.Fprintln(w, string(jsonData))
169}
170func AddressNetwork(w http.ResponseWriter, r *http.Request) {
171	ipFilter(w, r)
172
173	vars := mux.Vars(r)
174	address := vars["address"]
175	if address == "undefined" {
176		fmt.Fprintln(w, "not valid address")
177	} else {
178		network := addressTree(address)
179		network.Nodes[0].Shape = "triangle"
180
181		//convert []resp struct to json
182		jNetwork, err := json.Marshal(network)
183		check(err)
184
185		fmt.Fprintln(w, string(jNetwork))
186	}
187}
188func Address(w http.ResponseWriter, r *http.Request) {
189	ipFilter(w, r)
190
191	vars := mux.Vars(r)
192	hash := vars["hash"]
193	if hash == "undefined" {
194		fmt.Fprintln(w, "not valid hash")
195	} else {
196		address := AddressModel{}
197		err := addressCollection.Find(bson.M{"hash": hash}).One(&address)
198
199		txs := []TxModel{}
200		err = txCollection.Find(bson.M{"$or": []bson.M{bson.M{"from": hash}, bson.M{"to": hash}}}).All(&txs)
201		address.Txs = txs
202
203		for _, tx := range address.Txs {
204			blocks := []BlockModel{}
205			err = blockCollection.Find(bson.M{"hash": tx.BlockHash}).All(&blocks)
206			for _, block := range blocks {
207				address.Blocks = append(address.Blocks, block)
208			}
209		}
210
211		//convert []resp struct to json
212		jsonResp, err := json.Marshal(address)
213		check(err)
214
215		fmt.Fprintln(w, string(jsonResp))
216	}
217}
218func AddressSankey(w http.ResponseWriter, r *http.Request) {
219	ipFilter(w, r)
220	vars := mux.Vars(r)
221	address := vars["address"]
222	if address == "undefined" {
223		fmt.Fprintln(w, "not valid address")
224	} else {
225		network := addressTree(address)
226		var sankey SankeyModel
227
228		fmt.Println("network generated")
229		mapNodeK := make(map[string]int)
230		for k, n := range network.Nodes {
231			var sankeyNode SankeyNodeModel
232			//sankeyNode.StringNode = n.Id
233			sankeyNode.Node = k
234			sankeyNode.Name = n.Id
235			sankey.Nodes = append(sankey.Nodes, sankeyNode)
236			mapNodeK[n.Id] = k
237		}
238		for _, e := range network.Edges {
239			var sankeyLink SankeyLinkModel
240			//sankeyLink.StringSource = e.From
241			sankeyLink.Source = mapNodeK[e.From]
242			//sankeyLink.StringTarget = e.To
243			sankeyLink.Target = mapNodeK[e.To]
244			sankeyLink.Value = e.Label
245			sankey.Links = append(sankey.Links, sankeyLink)
246		}
247		fmt.Println("Sankey generated")
248
249		//convert []resp struct to json
250		jsonSankey, err := json.Marshal(sankey)
251		check(err)
252
253		fmt.Fprintln(w, string(jsonSankey))
254	}
255}
256func NetworkMap(w http.ResponseWriter, r *http.Request) {
257	ipFilter(w, r)
258
259	nodes, err := getAllNodes()
260	check(err)
261	edges, err := getAllEdges()
262	check(err)
263
264	var network NetworkModel
265	network.Nodes = nodes
266	network.Edges = edges
267
268	//convert []resp struct to json
269	jNetwork, err := json.Marshal(network)
270	check(err)
271
272	fmt.Fprintln(w, string(jNetwork))
273}
274
275func GetTotalHourAnalysis(w http.ResponseWriter, r *http.Request) {
276	ipFilter(w, r)
277
278	hourAnalysis := []ChartCountModel{}
279	iter := hourCountCollection.Find(bson.M{}).Limit(10000).Iter()
280	err := iter.All(&hourAnalysis)
281
282	//sort by hour
283	sort.Slice(hourAnalysis, func(i, j int) bool {
284		return hourAnalysis[i].Elem < hourAnalysis[j].Elem
285	})
286
287	var resp ChartAnalysisResp
288	for _, d := range hourAnalysis {
289		resp.Labels = append(resp.Labels, strconv.Itoa(d.Elem))
290		resp.Data = append(resp.Data, d.Count)
291	}
292
293	//convert []resp struct to json
294	jsonResp, err := json.Marshal(resp)
295	check(err)
296	fmt.Fprintln(w, string(jsonResp))
297}
298
299func GetLast24HourAnalysis(w http.ResponseWriter, r *http.Request) {
300	ipFilter(w, r)
301
302	fromDate := time.Now().AddDate(0, 0, -1)
303	toDate := time.Now()
304
305	txs := []TxModel{}
306	err := txCollection.Find(bson.M{
307		"datet": bson.M{
308			"$gt": fromDate,
309			"$lt": toDate,
310		},
311	}).Sort("-$natural").All(&txs)
312	check(err)
313
314	//generate map with 24 hours
315	hourFrequencies := map24hours()
316	for _, tx := range txs {
317		hourFrequencies[tx.Date.Hour]++
318	}
319	var hourCount []ChartCountModel
320	for hour, frequency := range hourFrequencies {
321		hourCount = append(hourCount, ChartCountModel{hour, frequency})
322	}
323	//sort by hour
324	sort.Slice(hourCount, func(i, j int) bool {
325		return hourCount[i].Elem < hourCount[j].Elem
326	})
327
328	var resp ChartAnalysisResp
329	for _, d := range hourCount {
330		resp.Labels = append(resp.Labels, strconv.Itoa(d.Elem))
331		resp.Data = append(resp.Data, d.Count)
332	}
333
334	//convert []resp struct to json
335	jsonResp, err := json.Marshal(resp)
336	check(err)
337	fmt.Fprintln(w, string(jsonResp))
338}
339func GetLast7DayAnalysis(w http.ResponseWriter, r *http.Request) {
340	ipFilter(w, r)
341
342	fromDate := time.Now().AddDate(0, 0, -7)
343	toDate := time.Now()
344
345	txs := []TxModel{}
346	err := txCollection.Find(bson.M{
347		"datet": bson.M{
348			"$gt": fromDate,
349			"$lt": toDate,
350		},
351	}).Sort("-$natural").All(&txs)
352	check(err)
353
354	//generate map with 24 hours
355	//hourFrequencies := map24hours()
356	dayFrequencies := make(map[int]int)
357	for _, tx := range txs {
358		dayFrequencies[tx.Date.Day]++
359	}
360	var dayCount []ChartCountModel
361	for day, frequency := range dayFrequencies {
362		dayCount = append(dayCount, ChartCountModel{day, frequency})
363	}
364	//sort by hour
365	sort.Slice(dayCount, func(i, j int) bool {
366		return dayCount[i].Elem < dayCount[j].Elem
367	})
368
369	var resp ChartAnalysisResp
370	for _, d := range dayCount {
371		resp.Labels = append(resp.Labels, strconv.Itoa(d.Elem))
372		resp.Data = append(resp.Data, d.Count)
373	}
374
375	//convert []resp struct to json
376	jsonResp, err := json.Marshal(resp)
377	check(err)
378	fmt.Fprintln(w, string(jsonResp))
379}
380
381func GetLast7DayHourAnalysis(w http.ResponseWriter, r *http.Request) {
382	ipFilter(w, r)
383
384	var resp ChartSeriesAnalysisResp
385
386	for i := 0; i < 7; i++ {
387		fromDate := time.Now().AddDate(0, 0, -i-1)
388		toDate := time.Now().AddDate(0, 0, -i)
389		txs := []TxModel{}
390		err := txCollection.Find(bson.M{
391			"datet": bson.M{
392				"$gt": fromDate,
393				"$lt": toDate,
394			},
395		}).Sort("-$natural").All(&txs)
396		check(err)
397
398		//generate map with 24 hours
399		hourFrequencies := map24hours()
400		for _, tx := range txs {
401			hourFrequencies[tx.Date.Hour]++
402		}
403		var hourCount []ChartCountModel
404		for hour, frequency := range hourFrequencies {
405			hourCount = append(hourCount, ChartCountModel{hour, frequency})
406		}
407		//sort by hour
408		sort.Slice(hourCount, func(i, j int) bool {
409			return hourCount[i].Elem < hourCount[j].Elem
410		})
411		var dayData []int
412		for _, d := range hourCount {
413			dayData = append(dayData, d.Count)
414		}
415		if len(txs) > 0 {
416			resp.Series = append(resp.Series, txs[0].Date.Day)
417			resp.Data = append(resp.Data, dayData)
418		}
419	}
420	hourLabels := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"}
421	resp.Labels = hourLabels
422
423	//convert []resp struct to json
424	jsonResp, err := json.Marshal(resp)
425	check(err)
426	fmt.Fprintln(w, string(jsonResp))
427}