From 806ef2cf8472c7391e74542d42ea92018d5d3f16 Mon Sep 17 00:00:00 2001 From: Martin Boehm Date: Thu, 10 May 2018 11:41:50 +0200 Subject: [PATCH] Add api/block-index/ handler for website monitoring --- server/socketio.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/server/socketio.go b/server/socketio.go index 6da0d070..d0861248 100644 --- a/server/socketio.go +++ b/server/socketio.go @@ -8,6 +8,7 @@ import ( "encoding/json" "fmt" "net/http" + "strconv" "strings" "time" @@ -18,6 +19,8 @@ import ( "github.com/martinboehm/golang-socketio/transport" ) +const blockbookAbout = "Blockbook v0.0.1, blockchain indexer for TREZOR wallet https://trezor.io/. Do not use for any other purpose." + // SocketIoServer is handle to SocketIoServer type SocketIoServer struct { binding string @@ -79,6 +82,8 @@ func NewSocketIoServer(binding string, certFiles string, db *db.RocksDB, chain b serveMux.Handle(path+"test.html", http.FileServer(http.Dir("./static/"))) // redirect to Bitcore for details of transaction serveMux.HandleFunc(path+"tx/", s.txRedirect) + // API call used to detect state of Blockbook + serveMux.HandleFunc(path+"api/block-index/", s.apiBlockIndex) // handle socket.io serveMux.Handle(path, server) @@ -124,6 +129,32 @@ func (s *SocketIoServer) txRedirect(w http.ResponseWriter, r *http.Request) { } } +func (s *SocketIoServer) apiBlockIndex(w http.ResponseWriter, r *http.Request) { + type resBlockIndex struct { + BlockHash string `json:"blockHash"` + About string `json:"about"` + } + var err error + var hash string + height := -1 + if i := strings.LastIndexByte(r.URL.Path, '/'); i > 0 { + if h, err := strconv.Atoi(r.URL.Path[i+1:]); err == nil { + height = h + } + } + if height >= 0 { + hash, err = s.db.GetBlockHash(uint32(height)) + } else { + _, hash, err = s.db.GetBestBlock() + } + if err != nil { + glog.Error(err) + } else { + r := resBlockIndex{BlockHash: hash, About: blockbookAbout} + json.NewEncoder(w).Encode(r) + } +} + type addrOpts struct { Start int `json:"start"` End int `json:"end"`