From 2d0a7cb87ce097fc1c96cb4950ef8deae44d6d13 Mon Sep 17 00:00:00 2001 From: Tocard Date: Mon, 19 Jul 2021 21:53:30 +0200 Subject: [PATCH 1/6] code cleanup --- data/farmer.go | 36 ++++++++++++------------------------ data/miningstatpool.go | 22 ---------------------- data/partial.go | 28 ---------------------------- 3 files changed, 12 insertions(+), 74 deletions(-) diff --git a/data/farmer.go b/data/farmer.go index f0dbfd1..4a49868 100644 --- a/data/farmer.go +++ b/data/farmer.go @@ -6,19 +6,19 @@ func (Farmer) TableName() string { } type Farmer struct { - LauncherId string `gorm:"launcher_id" json:"launcher_id"` - P2SingletonPuzzleHash string `gorm:"p2_singleton_puzzle_hash" json:"p2_singleton_puzzle_hash"` - DelayTime int64 `gorm:"delay_time" json:"delay_time"` - DelayPuzzleHash string `gorm:"delay_puzzle_hash" json:"delay_puzzle_hash"` - AuthenticationPublicKey string `gorm:"authentication_public_key" json:"authentication_public_key"` - SingletonTip []byte `gorm:"singleton_tip" json:"singleton_tip"` - SingletonTipState []byte `gorm:"singleton_tip_state" json:"singleton_tip_state"` - Points int `gorm:"points" json:"points"` + LauncherId string `gorm:"launcher_id" json:"launcher_id"` + P2SingletonPuzzleHash string `gorm:"p2_singleton_puzzle_hash" json:"p2_singleton_puzzle_hash"` + DelayTime int64 `gorm:"delay_time" json:"delay_time"` + DelayPuzzleHash string `gorm:"delay_puzzle_hash" json:"delay_puzzle_hash"` + AuthenticationPublicKey string `gorm:"authentication_public_key" json:"authentication_public_key"` + SingletonTip []byte `gorm:"singleton_tip" json:"singleton_tip"` + SingletonTipState []byte `gorm:"singleton_tip_state" json:"singleton_tip_state"` + Points int `gorm:"points" json:"points"` //Difficulty int `gorm:"difficulty" json:"difficulty"` - PayoutInstructions string `gorm:"payout_instructions" json:"payout_instructions"` - IsPoolMember bool `gorm:"is_pool_member" json:"is_pool_member"` - FarmerNetSpace float64 `gorm:"farmer_netspace" json:"farmer_netspace"` - LastSeen int64 `gorm:"farmer_lastseen" json:"farmer_lastseen"` + PayoutInstructions string `gorm:"payout_instructions" json:"payout_instructions"` + IsPoolMember bool `gorm:"is_pool_member" json:"is_pool_member"` + FarmerNetSpace float64 `gorm:"farmer_netspace" json:"farmer_netspace"` + LastSeen int64 `gorm:"farmer_lastseen" json:"farmer_lastseen"` } // GetFarmer get farmer from launcher_id. @@ -38,18 +38,6 @@ func GetFarmer(LauncherId string) (*Farmer, error) { return &toreturn, nil } -// UpdateFarmerPoint update points of user -func UpdateFarmerPoint(farmer *Farmer) error { - db := GetConn() - defer db.Close() - db.Model(&Farmer{}).Where("launcher_id = ?", farmer.LauncherId).Update("points", farmer.Points) - errs := db.GetErrors() - if len(errs) > 0 { - return errs[0] - } - return nil -} - // GetFarmers get all farmer func GetFarmers() ([]*Farmer, error) { db := GetConn() diff --git a/data/miningstatpool.go b/data/miningstatpool.go index 73e9381..018b455 100644 --- a/data/miningstatpool.go +++ b/data/miningstatpool.go @@ -1,13 +1,5 @@ package data -import ( - "io/ioutil" - "log" - "strconv" - "strings" -) - - type MiningStatPool struct { Status string `json:"status"` Data Data `json:"data"` @@ -28,20 +20,6 @@ type Data struct { PoolStats PoolStats `json:"poolStats"` } - -func LoadFileSoloPlot() float64 { - content, err := ioutil.ReadFile("solo_plot.txt") - if err != nil { - log.Fatal(err) - } - - // Convert []byte to string and print to screen - text := string(content) - Stringfloat := strings.TrimSuffix(text, "\n") - soloNetspace, _ := strconv.ParseFloat(Stringfloat, 64) - return soloNetspace -} - // GetMiningStatPool return structure for minig stat pool func GetMiningStatPool() (*MiningStatPool, error) { toreturn := MiningStatPool{} diff --git a/data/partial.go b/data/partial.go index 9028a9b..00adbd0 100644 --- a/data/partial.go +++ b/data/partial.go @@ -19,11 +19,6 @@ type Partial struct { Difficulty int64 `gorm:"difficulty" json:"difficulty"` } -type SolotPlot struct { - LauncherId string `gorm:"-" json:"launcher_id"` - Point int `gorm:"-" json:"pointPerHour"` -} - // GetPartials get all partial func GetPartials() ([]*Partial, error) { db := GetConn() @@ -66,29 +61,6 @@ func GetPartial(LauncherId string) ([]*Partial, error) { return toreturn, nil } -// GetTotalPoint return total of points -func GetTotalPoint() (int, error) { - db := GetConn() - defer db.Close() - var points int - db.Raw("SELECT SUM(points) FROM farmer").Row().Scan(&points) - errs := db.GetErrors() - if len(errs) > 0 { - return 0, errs[0] - } - return points, nil -} - -// GetPoints Value -func GetValuePoint() (float64, error) { - var points int - points, _ = GetTotalPoint() - var value float64 - value = float64(1750000000000 / points) - - return value, nil -} - // NewPArtial returns a Admin pointer. func NewPArtial(launcherId string, timestamp int64, difficulty int64) *Partial { p := &Partial{} From 081160d6775688fb54dc5e117e93bb027af0d005 Mon Sep 17 00:00:00 2001 From: Tocard Date: Mon, 19 Jul 2021 22:35:24 +0200 Subject: [PATCH 2/6] some cleanup add route GetFarmerFromP2SingletonPuzzleHash retieve launcher_id from singleton --- data/farmer.go | 46 ++++++++++++++++++++++++++++++--------------- data/poolinfo.go | 25 ++++++++++-------------- handlers/farmer.go | 16 +++++++++++++--- handlers/partial.go | 2 +- server/main.go | 1 + 5 files changed, 56 insertions(+), 34 deletions(-) diff --git a/data/farmer.go b/data/farmer.go index 4a49868..fbd221c 100644 --- a/data/farmer.go +++ b/data/farmer.go @@ -1,24 +1,26 @@ package data +import "fmt" + // TableName overrides the table name used by User to `profiles` func (Farmer) TableName() string { return "farmer" } type Farmer struct { - LauncherId string `gorm:"launcher_id" json:"launcher_id"` - P2SingletonPuzzleHash string `gorm:"p2_singleton_puzzle_hash" json:"p2_singleton_puzzle_hash"` - DelayTime int64 `gorm:"delay_time" json:"delay_time"` - DelayPuzzleHash string `gorm:"delay_puzzle_hash" json:"delay_puzzle_hash"` - AuthenticationPublicKey string `gorm:"authentication_public_key" json:"authentication_public_key"` - SingletonTip []byte `gorm:"singleton_tip" json:"singleton_tip"` - SingletonTipState []byte `gorm:"singleton_tip_state" json:"singleton_tip_state"` - Points int `gorm:"points" json:"points"` - //Difficulty int `gorm:"difficulty" json:"difficulty"` - PayoutInstructions string `gorm:"payout_instructions" json:"payout_instructions"` - IsPoolMember bool `gorm:"is_pool_member" json:"is_pool_member"` - FarmerNetSpace float64 `gorm:"farmer_netspace" json:"farmer_netspace"` - LastSeen int64 `gorm:"farmer_lastseen" json:"farmer_lastseen"` + LauncherId string `gorm:"launcher_id" json:"launcher_id"` + P2SingletonPuzzleHash string `gorm:"p2_singleton_puzzle_hash" json:"p2_singleton_puzzle_hash"` + DelayTime int64 `gorm:"delay_time" json:"delay_time"` + DelayPuzzleHash string `gorm:"delay_puzzle_hash" json:"delay_puzzle_hash"` + AuthenticationPublicKey string `gorm:"authentication_public_key" json:"authentication_public_key"` + SingletonTip []byte `gorm:"singleton_tip" json:"singleton_tip"` + SingletonTipState []byte `gorm:"singleton_tip_state" json:"singleton_tip_state"` + Points float64 `gorm:"points" json:"points"` + Difficulty int `gorm:"difficulty" json:"difficulty"` + PayoutInstructions string `gorm:"payout_instructions" json:"payout_instructions"` + IsPoolMember bool `gorm:"is_pool_member" json:"is_pool_member"` + FarmerNetSpace float64 `gorm:"farmer_netspace" json:"farmer_netspace"` + LastSeen int64 `gorm:"farmer_lastseen" json:"farmer_lastseen"` } // GetFarmer get farmer from launcher_id. @@ -54,7 +56,7 @@ func GetFarmers() ([]*Farmer, error) { return toreturn, nil } -// GetFarmers top farmer +// GetTopFarmers get top farmer func GetTopFarmers() ([]*Farmer, error) { db := GetConn() defer db.Close() @@ -71,7 +73,7 @@ func GetTopFarmers() ([]*Farmer, error) { return toreturn, nil } -// GetFarmers get all farmer +// GetFarmersCount sum all farmer func GetFarmersCount() (int, error) { db := GetConn() defer db.Close() @@ -83,3 +85,17 @@ func GetFarmersCount() (int, error) { } return toreturn, nil } + +// GetFarmerFromP2SingletonPuzzleHash get farmer from puzzlehash. +func GetFarmerFromP2SingletonPuzzleHash(P2SingletonPuzzleHash string) (string, error) { + db := GetConn() + defer db.Close() + toreturn := Farmer{} + query := fmt.Sprintf("p2_singleton_puzzle_hash=\"%s\" AND is_pool_member=1", P2SingletonPuzzleHash) + db.Table("farmer").Where(query).Scan(&toreturn) + errs := db.GetErrors() + if len(errs) > 0 { + return "", errs[0] + } + return toreturn.P2SingletonPuzzleHash, nil +} diff --git a/data/poolinfo.go b/data/poolinfo.go index 478b756..be682b2 100644 --- a/data/poolinfo.go +++ b/data/poolinfo.go @@ -1,23 +1,20 @@ package data - type PoolInfo struct { - Status string `json:"status"` - Data DataPool `json:"data"` + Status string `json:"status"` + Data DataPool `json:"data"` } type DataPool struct { - LastBlocks []LastBlocks `json:"lastBlocks"` - PoolSpaceTiB float64 `json:"poolSpaceTiB"` - Farmers int `json:"farmers"` - CurrentFeeType string `json:"currentFeeType"` - CurrentFee float64 `json:"currentFee"` - TotalPoints int `json:"totalPoints"` - PointValue float64 `json:"pointValue"` + LastBlocks []LastBlocks `json:"lastBlocks"` + PoolSpaceTiB float64 `json:"poolSpaceTiB"` + Farmers int `json:"farmers"` + CurrentFeeType string `json:"currentFeeType"` + CurrentFee float64 `json:"currentFee"` + TotalPoints float64 `json:"totalPoints"` + PointValue float64 `json:"pointValue"` } - - -// GetMiningStatPool return structure for minig stat pool +// GetPoolInfo return for pool info func GetPoolInfo() (*PoolInfo, error) { toreturn := PoolInfo{} fees, feestype := GetFees() @@ -33,5 +30,3 @@ func GetPoolInfo() (*PoolInfo, error) { return &toreturn, nil } - - diff --git a/handlers/farmer.go b/handlers/farmer.go index e4c499a..88b5452 100644 --- a/handlers/farmer.go +++ b/handlers/farmer.go @@ -30,18 +30,18 @@ func GetFarmers() (int, string) { return http.StatusOK, string(d) } -// GetFarmers top get farmer. +// GetTopFarmers get farmer. func GetTopFarmers() (int, string) { redisTop := redis.GetFromToRedis(0, "topFarmer") if redisTop != "" { return http.StatusOK, string(redisTop) - }else{ + } else { u, err := data.GetTopFarmers() if err != nil { return http.StatusInternalServerError, err.Error() } d, _ := json.Marshal(u) - redis.WriteToRedis(0, "topFarmer", string(d)) + redis.WriteToRedis(0, "topFarmer", string(d)) return http.StatusOK, string(d) } } @@ -80,3 +80,13 @@ func PostFarmerDiscord(params martini.Params) (int, string) { d, _ := json.Marshal(u) return http.StatusOK, string(d) } + +// GetFarmerFromP2SingletonPuzzleHash get launcher_id from GetFarmerFromP2SingletonPuzzleHash. +func GetFarmerFromP2SingletonPuzzleHash(params martini.Params) (int, string) { + u, err := data.GetFarmerFromP2SingletonPuzzleHash(params["p2_singleton_puzzle_hash"]) + if err != nil { + return http.StatusInternalServerError, err.Error() + } + d, _ := json.Marshal(u) + return http.StatusOK, string(d) +} diff --git a/handlers/partial.go b/handlers/partial.go index ccb1bd0..778e130 100644 --- a/handlers/partial.go +++ b/handlers/partial.go @@ -83,7 +83,7 @@ func PostPartialSoloplot(r *http.Request) (int, string) { if err != nil { return http.StatusServiceUnavailable, err.Error() } - for i := 0; i < soloFarmer.Point; i++ { + for i := 0.0; i < soloFarmer.Point; i++ { p := data.NewPArtial(soloFarmer.LauncherId, t+int64(interval), 1) err := p.AddSoloPartial() if err != nil { diff --git a/server/main.go b/server/main.go index a95505f..bb1835a 100644 --- a/server/main.go +++ b/server/main.go @@ -67,6 +67,7 @@ func server() *martini.ClassicMartini { r.Get("/top", handlers.GetTopFarmers) r.Get("/totalpoints", handlers.GetTotalPoint) r.Get("/count", handlers.GetFarmersCount) + r.Get("/puzzle/:p2_singleton_puzzle_hash", handlers.GetFarmerFromP2SingletonPuzzleHash) r.Get("/:launcher_id", handlers.GetFarmer) r.Post("/:launcher_id", handlers.PostFarmerDiscord) }) From e95bcc4ead56d60a7ec27a6f2ccd381337a0295b Mon Sep 17 00:00:00 2001 From: Tocard Date: Tue, 20 Jul 2021 07:31:49 +0200 Subject: [PATCH 3/6] some cleanup again fetch auto last coin from pool --- data/miningstatpool.go | 36 +++++++++++++++++++++++++++++++++++- data/netspace.go | 5 ++--- redis/redis.go | 1 - 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/data/miningstatpool.go b/data/miningstatpool.go index 018b455..a07fb4c 100644 --- a/data/miningstatpool.go +++ b/data/miningstatpool.go @@ -1,5 +1,28 @@ package data +import ( + "encoding/json" + "net/http" + "time" +) + +type Coins struct { + Txns []struct { + ID string `json:"id"` + Coin string `json:"coin"` + Amount int `json:"amount"` + From string `json:"from"` + Spent bool `json:"spent"` + To string `json:"to"` + Timestamp int `json:"timestamp"` + Block struct { + ID string `json:"id"` + Height int `json:"height"` + HeaderHash string `json:"header_hash"` + } `json:"block"` + } `json:"txns"` +} + type MiningStatPool struct { Status string `json:"status"` Data Data `json:"data"` @@ -29,7 +52,18 @@ func GetMiningStatPool() (*MiningStatPool, error) { toreturn.Data.PoolStats.CurrentFeeType = feestype toreturn.Data.PoolStats.PoolSpaceTiB, _ = GetNetSpaceTotal() toreturn.Data.PoolStats.PoolSpaceTiB += LoadFileSoloPlot() - toreturn.Data.LastBlocks = []LastBlocks{{Height: 585001, Timestamp: 1626533952}} + coins := Coins{} + var myClient = &http.Client{Timeout: 10 * time.Second} + r, err := myClient.Get("https://xchscan.com/api/txns?limit=1&offset=0") + if err != nil { + return nil, err + } + defer r.Body.Close() + err = json.NewDecoder(r.Body).Decode(&coins) + if err != nil { + return nil, err + } + toreturn.Data.LastBlocks = []LastBlocks{{Height: coins.Txns[0].Block.Height, Timestamp: coins.Txns[0].Timestamp}} toreturn.Status = "OK" return &toreturn, nil } diff --git a/data/netspace.go b/data/netspace.go index 527cff4..e483f89 100644 --- a/data/netspace.go +++ b/data/netspace.go @@ -1,10 +1,10 @@ package data import ( - "fmt" - "time" "chia_api/redis" "chia_api/utils" + "fmt" + "time" ) // GetNetSpaceByLauncherId calculate size from partial share @@ -27,7 +27,6 @@ func GetNetSpaceByLauncherId(LauncherId string) (float64, error) { averageDifficulty = averageDifficulty / float64(count) size = (float64(count) / (float64(timeToCheck) * ((5 / averageDifficulty) / 43200 / 106364865085.00))) / 1099511627776 } - fmt.Printf("db %f\n", size) errs := db.GetErrors() if len(errs) > 0 { return 0, errs[0] diff --git a/redis/redis.go b/redis/redis.go index 9c21d41..b13d037 100644 --- a/redis/redis.go +++ b/redis/redis.go @@ -49,7 +49,6 @@ func WriteToRedis(DbNum int, key, value string) { func GetFromToRedis(DbNum int, key string) string { val, err := Clis[DbNum].Get(key).Result() - fmt.Printf("result from redis %s\n", val) if err == redis.Nil || err != nil { return "" } From 85fcc6599599eafe15b82d627e6f70ddf0f2bcdb Mon Sep 17 00:00:00 2001 From: Tocard Date: Tue, 20 Jul 2021 07:49:19 +0200 Subject: [PATCH 4/6] support farmer launchreid 0x mode --- handlers/farmer.go | 8 +++++++- handlers/netspace.go | 7 +++++-- handlers/partial.go | 12 ++++++++++-- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/handlers/farmer.go b/handlers/farmer.go index 88b5452..3b6a16c 100644 --- a/handlers/farmer.go +++ b/handlers/farmer.go @@ -4,6 +4,7 @@ import ( "chia_api/data" "chia_api/redis" "encoding/json" + "fmt" "github.com/go-martini/martini" "github.com/nickname32/discordhook" "net/http" @@ -11,7 +12,12 @@ import ( // GetFarmer get farmer. func GetFarmer(params martini.Params) (int, string) { - u, err := data.GetFarmer(params["launcher_id"]) + launcherId := params["launcher_id"] + if launcherId[0] == '0' && launcherId[1] == 'x' { + launcherId = launcherId[2:] + } + fmt.Println(launcherId) + u, err := data.GetFarmer(launcherId) if err != nil { return http.StatusInternalServerError, err.Error() } diff --git a/handlers/netspace.go b/handlers/netspace.go index ee9f8a5..9c02360 100644 --- a/handlers/netspace.go +++ b/handlers/netspace.go @@ -11,14 +11,17 @@ import ( // GetNetSpaceByLauncherId get netspace estimation from launcher_id. func GetNetSpaceByLauncherId(params martini.Params) (int, string) { - launcherId, _ := params["launcher_id"] + launcherId := params["launcher_id"] + if launcherId[0] == '0' && launcherId[1] == 'x' { + launcherId = launcherId[2:] + } redisValue := redis.GetFromToRedis(0, launcherId) redisNetspace := utils.StringToFloat(redisValue) if redisNetspace != 0.0 { d, _ := json.Marshal(redisNetspace) return http.StatusOK, string(d) } - u, err := data.GetNetSpaceByLauncherId(params["launcher_id"]) + u, err := data.GetNetSpaceByLauncherId(launcherId) if err != nil { return http.StatusInternalServerError, err.Error() } diff --git a/handlers/partial.go b/handlers/partial.go index 778e130..0cf4219 100644 --- a/handlers/partial.go +++ b/handlers/partial.go @@ -12,7 +12,11 @@ import ( // GetPartial get Partial. func GetPartial(params martini.Params) (int, string) { - u, err := data.GetPartial(params["launcher_id"]) + launcherId := params["launcher_id"] + if launcherId[0] == '0' && launcherId[1] == 'x' { + launcherId = launcherId[2:] + } + u, err := data.GetPartial(launcherId) if err != nil { return http.StatusInternalServerError, err.Error() } @@ -43,7 +47,11 @@ func GetPartials() (int, string) { // PostPartialDiscord post new partial on discord func PostPartialDiscord(params martini.Params) (int, string) { - u, err := data.GetPartial(params["launcher_id"]) + launcherId := params["launcher_id"] + if launcherId[0] == '0' && launcherId[1] == 'x' { + launcherId = launcherId[2:] + } + u, err := data.GetPartial(launcherId) wa, err := discordhook.NewWebhookAPI(861291081143681074, "dKHd1iYI71H0rc1rPM1vBNPawdE_uhodXSqKLNDb53wYXP_Y-EcR3zihdjKo3ullMEWX", true, nil) if err != nil { From 64080bf5e202ea1fb35ff13d0f81b0a1c7c4ec8f Mon Sep 17 00:00:00 2001 From: Tocard Date: Tue, 20 Jul 2021 08:01:09 +0200 Subject: [PATCH 5/6] cleanup & add route for post new bloc discord --- data/partial.go | 6 ------ handlers/admin.go | 2 -- handlers/blocs.go | 28 ++++++++++++++++++++++++++++ handlers/farmer.go | 2 -- handlers/partial.go | 2 -- handlers/utils.go | 4 ---- redis/redis.go | 1 - 7 files changed, 28 insertions(+), 17 deletions(-) create mode 100644 handlers/blocs.go diff --git a/data/partial.go b/data/partial.go index 00adbd0..dbabdcf 100644 --- a/data/partial.go +++ b/data/partial.go @@ -1,9 +1,5 @@ package data -import ( - "fmt" -) - type Tabler interface { TableName() string } @@ -37,7 +33,6 @@ func GetLastSeen(LauncherId string) (int64, error) { db := GetConn() defer db.Close() var toreturn int64 - fmt.Println() db.Raw("SELECT timestamp FROM partial where launcher_id=\"" + LauncherId + "\" ORDER BY timestamp DESC LIMIT 1").Row().Scan(&toreturn) errs := db.GetErrors() @@ -52,7 +47,6 @@ func GetPartial(LauncherId string) ([]*Partial, error) { db := GetConn() defer db.Close() toreturn := []*Partial{} - fmt.Println() db.Raw("SELECT * FROM partial where launcher_id=\"" + LauncherId + "\"").Scan(&toreturn) errs := db.GetErrors() if len(errs) > 0 { diff --git a/handlers/admin.go b/handlers/admin.go index a80cde9..3dead9d 100644 --- a/handlers/admin.go +++ b/handlers/admin.go @@ -2,7 +2,6 @@ package handlers import ( "chia_api/data" - "fmt" "github.com/go-martini/martini" "net/http" ) @@ -11,7 +10,6 @@ import ( func GenerateAdmin(params martini.Params) (int, string) { u := data.NewAdmin(params["launcher_id"]) - fmt.Println(u) err := u.Save() if err != nil { return http.StatusServiceUnavailable, err.Error() diff --git a/handlers/blocs.go b/handlers/blocs.go new file mode 100644 index 0000000..a17534e --- /dev/null +++ b/handlers/blocs.go @@ -0,0 +1,28 @@ +package handlers + +import ( + "github.com/go-martini/martini" + "github.com/nickname32/discordhook" + "net/http" +) + +// PostNewBlock post new block on discord +func PostNewBlock(params martini.Params) (int, string) { + + wa, err := discordhook.NewWebhookAPI(861291081143681074, "dKHd1iYI71H0rc1rPM1vBNPawdE_uhodXSqKLNDb53wYXP_Y-EcR3zihdjKo3ullMEWX", true, nil) + if err != nil { + return http.StatusInternalServerError, err.Error() + } + + _, err = wa.Execute(nil, &discordhook.WebhookExecuteParams{ + Embeds: []*discordhook.Embed{ + { + Title: "Un nouveau block pour la pool", + }, + }, + }, nil, "") + if err != nil { + return http.StatusInternalServerError, err.Error() + } + return http.StatusOK, "" +} diff --git a/handlers/farmer.go b/handlers/farmer.go index 3b6a16c..4888d0d 100644 --- a/handlers/farmer.go +++ b/handlers/farmer.go @@ -4,7 +4,6 @@ import ( "chia_api/data" "chia_api/redis" "encoding/json" - "fmt" "github.com/go-martini/martini" "github.com/nickname32/discordhook" "net/http" @@ -16,7 +15,6 @@ func GetFarmer(params martini.Params) (int, string) { if launcherId[0] == '0' && launcherId[1] == 'x' { launcherId = launcherId[2:] } - fmt.Println(launcherId) u, err := data.GetFarmer(launcherId) if err != nil { return http.StatusInternalServerError, err.Error() diff --git a/handlers/partial.go b/handlers/partial.go index 0cf4219..922569b 100644 --- a/handlers/partial.go +++ b/handlers/partial.go @@ -3,7 +3,6 @@ package handlers import ( "chia_api/data" "encoding/json" - "fmt" "github.com/go-martini/martini" "github.com/nickname32/discordhook" "net/http" @@ -85,7 +84,6 @@ func PostPartialSoloplot(r *http.Request) (int, string) { interval := 3600 / soloFarmer.Point farmer, _ := data.GetFarmer(soloFarmer.LauncherId) if farmer != nil { - fmt.Println(farmer.Points, soloFarmer.Point) farmer.Points += soloFarmer.Point err := data.UpdateFarmerPoint(farmer) if err != nil { diff --git a/handlers/utils.go b/handlers/utils.go index 97abeec..84ad430 100644 --- a/handlers/utils.go +++ b/handlers/utils.go @@ -4,7 +4,6 @@ import ( "chia_api/data" "chia_api/utils" "encoding/json" - "fmt" "net/http" "strings" ) @@ -17,7 +16,6 @@ func Login(r *http.Request) (int, string) { db := data.GetConn() defer db.Close() dec := json.NewDecoder(r.Body) - fmt.Println(r.Body) dec.Decode(&where) if len(strings.TrimSpace(where.LauncherId)) == 0 { @@ -55,5 +53,3 @@ func Name() (int, string) { func Version() (int, string) { return http.StatusOK, "0.0.0" } - - diff --git a/redis/redis.go b/redis/redis.go index b13d037..43044d7 100644 --- a/redis/redis.go +++ b/redis/redis.go @@ -32,7 +32,6 @@ func init() { }() } func connect(DbNum int) { - fmt.Println(Host, Port) Clis[DbNum] = redis.NewClient(&redis.Options{ Addr: Host + ":" + strconv.Itoa(Port), Password: Password, // no password set From 7499c99116b8cf0c5e32b3ebe8f8ec702bf82a15 Mon Sep 17 00:00:00 2001 From: Tocard Date: Wed, 21 Jul 2021 01:35:41 +0200 Subject: [PATCH 6/6] ajout de la methode permettant de chopper le dernier bloc par puzzle ou pool reward --- data/block.go | 17 +++++++++ data/farmer.go | 14 ++++++++ data/init.go | 2 +- data/miningstatpool.go | 79 ++++++++++++++++++++++++++++++------------ handlers/blocs.go | 9 +++-- main.go | 4 +-- server/main.go | 4 +++ utils/misc.go | 4 +++ 8 files changed, 104 insertions(+), 29 deletions(-) create mode 100644 data/block.go diff --git a/data/block.go b/data/block.go new file mode 100644 index 0000000..4cd2028 --- /dev/null +++ b/data/block.go @@ -0,0 +1,17 @@ +package data + +type WinBlock struct { + Height int `json:"height"` + Timestamp int `json:"timestamp"` + LauncherId string `json:"string"` +} + +// NewWinBlock returns a WinBlock pointer. +func NewWinBlock(timestamp, height int, launcherId string) *WinBlock { + u := &WinBlock{} + u.LauncherId = launcherId + u.Timestamp = timestamp + u.Height = height + + return u +} diff --git a/data/farmer.go b/data/farmer.go index fbd221c..d786d7c 100644 --- a/data/farmer.go +++ b/data/farmer.go @@ -99,3 +99,17 @@ func GetFarmerFromP2SingletonPuzzleHash(P2SingletonPuzzleHash string) (string, e } return toreturn.P2SingletonPuzzleHash, nil } + +// GetFarmerFromRewardAdress get farmer from puzzlehash. +func GetFarmerFromRewardAdress(rewardAdress string) (string, error) { + db := GetConn() + defer db.Close() + toreturn := Farmer{} + query := fmt.Sprintf("payout_instructions=\"%s\" AND is_pool_member=1", rewardAdress) + db.Table("farmer").Where(query).Scan(&toreturn) + errs := db.GetErrors() + if len(errs) > 0 { + return "", errs[0] + } + return toreturn.P2SingletonPuzzleHash, nil +} diff --git a/data/init.go b/data/init.go index 07303bc..56f6b68 100644 --- a/data/init.go +++ b/data/init.go @@ -35,7 +35,7 @@ func Migrate() { db := GetConn() defer db.Close() db.AutoMigrate( - &Farmer{}, &PoolAdmin{}, &Partial{}, + &PoolAdmin{}, ) } diff --git a/data/miningstatpool.go b/data/miningstatpool.go index a07fb4c..18eae74 100644 --- a/data/miningstatpool.go +++ b/data/miningstatpool.go @@ -1,26 +1,35 @@ package data import ( + "bytes" "encoding/json" + "fmt" + "log" "net/http" "time" ) type Coins struct { - Txns []struct { - ID string `json:"id"` - Coin string `json:"coin"` - Amount int `json:"amount"` - From string `json:"from"` - Spent bool `json:"spent"` - To string `json:"to"` - Timestamp int `json:"timestamp"` - Block struct { - ID string `json:"id"` - Height int `json:"height"` - HeaderHash string `json:"header_hash"` - } `json:"block"` - } `json:"txns"` + Page int `json:"page"` + Pages int `json:"pages"` + Total int `json:"total"` + Data []struct { + Hash string `json:"hash"` + Height int `json:"height"` + Time int `json:"time"` + TxCount int `json:"txCount"` + Generator string `json:"generator"` + Previousblockhash string `json:"previousblockhash"` + BlockDetail struct { + FarmerRewardAddress string `json:"farmerRewardAddress"` + PoolTargetAddress string `json:"poolTargetAddress"` + Time int `json:"time"` + BlockNo int `json:"blockNo"` + Fees int `json:"fees"` + PoolContractPuzzle string `gorm:"default:true" json:"poolContractPuzzleHash"` + } `json:"blockDetail"` + Nextblockhash string `json:"nextblockhash,omitempty"` + } `json:"data"` } type MiningStatPool struct { @@ -32,6 +41,7 @@ type LastBlocks struct { Height int `json:"height"` Timestamp int `json:"timestamp"` } + type PoolStats struct { PoolSpaceTiB float64 `json:"poolSpaceTiB"` Farmers int `json:"farmers"` @@ -54,16 +64,39 @@ func GetMiningStatPool() (*MiningStatPool, error) { toreturn.Data.PoolStats.PoolSpaceTiB += LoadFileSoloPlot() coins := Coins{} var myClient = &http.Client{Timeout: 10 * time.Second} - r, err := myClient.Get("https://xchscan.com/api/txns?limit=1&offset=0") - if err != nil { - return nil, err - } - defer r.Body.Close() - err = json.NewDecoder(r.Body).Decode(&coins) - if err != nil { - return nil, err + for p := 0; p < 300; p++ { // =4 minute d'exec + url := fmt.Sprintf("https://chia.tt/api/chia/blockchain/block?page=%d&count=20", p) + r, err := myClient.Get(url) + if err != nil { + return nil, err + } + err = json.NewDecoder(r.Body).Decode(&coins) + if err != nil { + return nil, err + } + for i := 0; i < len(coins.Data); i++ { + var launcherid string + if coins.Data[i].BlockDetail.PoolContractPuzzle != "" { + launcherid, _ = GetFarmerFromP2SingletonPuzzleHash(coins.Data[i].BlockDetail.PoolContractPuzzle[2:]) + } else { + launcherid, _ = GetFarmerFromRewardAdress(coins.Data[i].BlockDetail.FarmerRewardAddress) + } + if launcherid != "" { + r.Body.Close() + toreturn.Data.LastBlocks = []LastBlocks{{Height: coins.Data[i].Height, Timestamp: coins.Data[i].Time}} + values := NewWinBlock(coins.Data[i].Time, coins.Data[i].Height, launcherid) + json_data, err := json.Marshal(values) + + if err != nil { + log.Fatal(err) + } + + http.Post("https://localhost:8081/block/new_block_discord", "application/json", + bytes.NewBuffer(json_data)) + } + } + r.Body.Close() } - toreturn.Data.LastBlocks = []LastBlocks{{Height: coins.Txns[0].Block.Height, Timestamp: coins.Txns[0].Timestamp}} toreturn.Status = "OK" return &toreturn, nil } diff --git a/handlers/blocs.go b/handlers/blocs.go index a17534e..148ebde 100644 --- a/handlers/blocs.go +++ b/handlers/blocs.go @@ -1,14 +1,17 @@ package handlers import ( - "github.com/go-martini/martini" + "chia_api/data" + "encoding/json" "github.com/nickname32/discordhook" "net/http" ) // PostNewBlock post new block on discord -func PostNewBlock(params martini.Params) (int, string) { - +func PostNewBlock(r *http.Request) (int, string) { + block := data.WinBlock{} + dec := json.NewDecoder(r.Body) + err := dec.Decode(&block) wa, err := discordhook.NewWebhookAPI(861291081143681074, "dKHd1iYI71H0rc1rPM1vBNPawdE_uhodXSqKLNDb53wYXP_Y-EcR3zihdjKo3ullMEWX", true, nil) if err != nil { return http.StatusInternalServerError, err.Error() diff --git a/main.go b/main.go index a201da3..d0e77e0 100644 --- a/main.go +++ b/main.go @@ -64,7 +64,7 @@ func main() { data.API_PORT = apiPort data.API_HOST = apiHost - //data.Migrate() - //getConf() + data.Migrate() + getConf() server.GetServer().Run() } diff --git a/server/main.go b/server/main.go index bb1835a..18a88d2 100644 --- a/server/main.go +++ b/server/main.go @@ -79,6 +79,10 @@ func server() *martini.ClassicMartini { r.Post("/:launcher_id", handlers.PostPartialDiscord) r.Post("/update/solo_plot", handlers.PostPartialSoloplot) + }) + app.Group("/block", func(r martini.Router) { + r.Post("/new_block_discord", handlers.PostNewBlock) + }) return app diff --git a/utils/misc.go b/utils/misc.go index 970aed9..3a5a5ae 100644 --- a/utils/misc.go +++ b/utils/misc.go @@ -13,3 +13,7 @@ func StringToFloat(misc string) float64 { tmpFloat, _ := strconv.ParseFloat(misc, 64) return tmpFloat } + +func IntToString(misc int) string { + return fmt.Sprintf("%d", misc) +}