Skip to content

Commit

Permalink
[add&move] add unlocker.go for block verify & add "/blocks" api for m…
Browse files Browse the repository at this point in the history
…ined blocks & move owner_api to owner.go
  • Loading branch information
Command M committed Jan 29, 2020
1 parent 808281a commit b91646d
Show file tree
Hide file tree
Showing 8 changed files with 265 additions and 97 deletions.
42 changes: 34 additions & 8 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 22 additions & 4 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ func (as *apiServer) sharesHandler(w http.ResponseWriter, r *http.Request) {
}

func (as *apiServer) poolHandler(w http.ResponseWriter, r *http.Request) {
var blockBatch []string
//var blockBatch []string
header := w.Header()
header.Set("Content-Type", "application/json")
header.Set("Access-Control-Allow-Origin", "*")

blockBatch = as.db.getAllBlockHashes()
//blockBatch = as.db.getAllBlockHashes()

req, _ := http.NewRequest("GET", "http://"+as.conf.Node.Address+":"+strconv.Itoa(as.conf.Node.APIPort)+"/v1/status", nil)
req.SetBasicAuth(as.conf.Node.AuthUser, as.conf.Node.AuthPass)
Expand All @@ -61,8 +61,8 @@ func (as *apiServer) poolHandler(w http.ResponseWriter, r *http.Request) {
_ = dec.Decode(&nodeStatus)

table := map[string]interface{}{
"node_status": nodeStatus,
"mined_blocks": blockBatch,
"node_status": nodeStatus,
//"mined_blocks": blockBatch,
}
raw, err := json.Marshal(table)
if err != nil {
Expand Down Expand Up @@ -123,6 +123,23 @@ func (as *apiServer) minerHandler(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(raw)
}

func (as *apiServer) blocksHandler(w http.ResponseWriter, r *http.Request) {
var raw []byte

header := w.Header()
header.Set("Content-Type", "application/json")
header.Set("Access-Control-Allow-Origin", "*")

blocks := as.db.getAllMinedBlockHashes()
raw, err := json.Marshal(blocks)
if err != nil {
logger.Error(err)
return
}

_, _ = w.Write(raw)
}

func initAPIServer(db *database, conf *config) {
as := &apiServer{
db: db,
Expand All @@ -134,6 +151,7 @@ func initAPIServer(db *database, conf *config) {
r.HandleFunc("/miner/{miner_login}", as.minerHandler)
r.HandleFunc("/revenue", as.revenueHandler)
r.HandleFunc("/shares", as.sharesHandler)
r.HandleFunc("/blocks", as.blocksHandler)
http.Handle("/", r)
go logger.Fatal(
http.ListenAndServe(conf.APIServer.Address+":"+strconv.Itoa(conf.APIServer.Port), nil))
Expand Down
42 changes: 38 additions & 4 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ func (db *database) getMinerStatus(login string) map[string]interface{} {
}

monthStartDay := time.Date(time.Now().Year(), time.Now().Month(), 0, 0, 0, 0, 0, time.Now().Location())
dateStart, _ := strconv.ParseFloat(monthStartDay.Format("20190102"), 10)
dateEnd, _ := strconv.ParseFloat(time.Now().Format("20190102"), 10)
dateStart, _ := strconv.ParseFloat(monthStartDay.Format("20060102"), 10)
dateEnd, _ := strconv.ParseFloat(time.Now().Format("20060102"), 10)
dayRevenues, _ := db.client.ZRangeWithScores("revenue:"+login, int64(dateStart), int64(dateEnd)).Result()
table := make(map[string]interface{})
for _, z := range dayRevenues {
Expand Down Expand Up @@ -208,15 +208,49 @@ func (db *database) putBlockHash(hash string) {
}
}

func (db *database) getAllBlockHashes() []string {
l, err := db.client.LRange("blocksFound", 0, -1).Result()
func (db *database) getAllBlockHashesFrom(pos int64) []string {
l, err := db.client.LRange("blocksFound", pos, -1).Result()
if err != nil {
logger.Error(err)
}

return l
}

type MinedBlock struct {
Height uint64
Hash string
}

func (db *database) putMinedBlock(height uint64, hash string) {
minedBlock := MinedBlock{
Height: height,
Hash: hash,
}
raw, _ := json.Marshal(minedBlock)
_, err := db.client.LPush("blocksMined", raw).Result()
if err != nil {
logger.Error(err)
}
}

func (db *database) getAllMinedBlockHashes() []MinedBlock {
blocks := make([]MinedBlock, 0)

l, err := db.client.LRange("blocksMined", 0, -1).Result()
if err != nil {
logger.Error(err)
}

for i := range l {
var b MinedBlock
_ = json.Unmarshal([]byte(l[i]), &b)
blocks = append(blocks, b)
}

return blocks
}

func (db *database) calcRevenueToday(totalRevenue uint64) {
allMinersStrSharesTable, err := db.client.HGetAll("shares").Result()
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ func main() {
go initAPIServer(db, conf)
go initStratumServer(db, conf)
go initPayer(db, conf)
go initUnlocker(db, conf)
for {
select {}
}
Expand Down
92 changes: 92 additions & 0 deletions owner.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package main

import (
"encoding/json"
"github.com/google/logger"
"net/http"
"strconv"
"strings"
)

// https://docs.rs/grin_wallet_api/3.0.0/grin_wallet_api
type OwnerAPI struct {
db *database
conf *config
}

func NewOwnerAPI(db *database, conf *config) *OwnerAPI {
return &OwnerAPI{
db: db,
conf: conf,
}
}

// deprecated v1 wallet owner api
func (o *OwnerAPI) getNewBalanceV1() uint64 {
req, _ := http.NewRequest("GET", "http://"+o.conf.Wallet.Address+":"+strconv.Itoa(o.conf.Wallet.OwnerAPIPort)+"/v1/wallet/owner/retrieve_summary_info?refresh", nil)
req.SetBasicAuth(o.conf.Node.AuthUser, o.conf.Node.AuthPass)
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
logger.Error("failed to get balance from wallet, treat this as no income")
return 0
}

dec := json.NewDecoder(res.Body)
var summaryInfo []interface{}
_ = dec.Decode(&summaryInfo)

i, _ := summaryInfo[1].(map[string]interface{})
strSpendable := i["amount_currently_spendable"].(string)
spendable, _ := strconv.Atoi(strSpendable)
return uint64(spendable) // unit nanogrin
}

// The V2 Owner API (OwnerRpc) will be removed in grin-wallet 4.0.0. Please migrate to the V3 (OwnerRpcS) API as soon as possible.
func (o *OwnerAPI) getNewBalanceV2() uint64 {
req, _ := http.NewRequest("POST", "http://"+o.conf.Wallet.Address+":"+strconv.Itoa(o.conf.Wallet.OwnerAPIPort)+"/v2/wallet/owner", strings.NewReader(`{
"jsonrpc": "2.0",
"method": "retrieve_summary_info",
"params": [true, 10],
"id": 1
}`))
req.SetBasicAuth(o.conf.Node.AuthUser, o.conf.Node.AuthPass)
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
logger.Error("failed to get balance from wallet for failing to post request, treat this as no income")
return 0
}

dec := json.NewDecoder(res.Body)
var summaryInfo jsonRPCResponse
_ = dec.Decode(&summaryInfo)

result := summaryInfo.Result
if result == nil {
logger.Error(summaryInfo.Error)
logger.Error("failed to get balance from wallet for failing to get result request, treat this as no income")
return 0
}

mapResult, ok := result.(map[string]interface{})
if ok || mapResult["Ok"] != nil {
theOk, ok := mapResult["Ok"].([]interface{})
if ok {
for i := range theOk {
if balanceMap, ok := theOk[i].(map[string]interface{}); ok {
strSpendable := balanceMap["amount_currently_spendable"].(string)
spendable, _ := strconv.Atoi(strSpendable)
return uint64(spendable) // unit nanogrin
}
}
}
}

return 0
}

func (o *OwnerAPI) getNewBalanceV3() uint64 {
logger.Fatal("V3 support WIP!")
return 0
}
Loading

0 comments on commit b91646d

Please sign in to comment.