open-ethereum-pool以太坊礦池原始碼分析(2)API分析

尹成發表於2018-05-21
# open-ethereum-pool以太坊礦池-api模組

## ApiServer相關定義

```go
type ApiConfig struct {
Enabled bool `json:"enabled"`
Listen string `json:"listen"`
StatsCollectInterval string `json:"statsCollectInterval"`
HashrateWindow string `json:"hashrateWindow"`
HashrateLargeWindow string `json:"hashrateLargeWindow"`
LuckWindow []int `json:"luckWindow"`
Payments int64 `json:"payments"`
Blocks int64 `json:"blocks"`
PurgeOnly bool `json:"purgeOnly"`
PurgeInterval string `json:"purgeInterval"`
}

type ApiServer struct {
config *ApiConfig
backend *storage.RedisClient
hashrateWindow time.Duration
hashrateLargeWindow time.Duration
stats atomic.Value
miners map[string]*Entry
minersMu sync.RWMutex
statsIntv time.Duration
}

type Entry struct {
stats map[string]interface{}
updatedAt int64
}
//程式碼位置api/server.go
```

## startApi流程圖



## CollectStats原理

```go
//config.StatsCollectInterval為CollectStats定時器,時間為5秒
//調取:stats, err := s.backend.CollectStats(s.hashrateWindow, s.config.Blocks, s.config.Payments)
//s.hashrateWindow即cfg.HashrateWindow,即:為每個礦工估計算力的快速時間間隔,30分鐘
//s.config.Blocks即:前端顯示的最大塊數,50個
//s.config.Payments即:前端顯示的最大付款數量,50個
func (r *RedisClient) CollectStats(smallWindow time.Duration, maxBlocks, maxPayments int64) (map[string]interface{}, error) {
    //換算成秒
    window := int64(smallWindow / time.Second)
    //建立map
    stats := make(map[string]interface{})

    //Redis事務塊
    tx := r.client.Multi()
    defer tx.Close()

    //換算成秒
    now := util.MakeTimestamp() / 1000

    cmds, err := tx.Exec(func() error {
        //針對min和max引數需要額外說明的是,-inf和+inf分別表示Sorted-Sets中分數的最高值和最低值
        //預設情況下,min和max表示的範圍是閉區間範圍,即min <= score <= max內的成員將被返回
        //然而我們可以通過在min和max的前面新增"("字元來表示開區間,如(min max表示min < score <= max,而(min (max表示min < score < max
        //-inf <= score < now-window
        
        //Zremrangebyscore 命令用於移除有序集中,指定分數(score)區間內的所有成員
        //ZREMRANGEBYSCORE eth:hashrate -inf (now-window
        //慎重使用
        tx.ZRemRangeByScore(r.formatKey("hashrate"), "-inf", fmt.Sprint("(", now-window))
        
        //顯示整個有序整合員
        //ZRANGE eth:hashrate 0 -1 WITHSCORES
        tx.ZRangeWithScores(r.formatKey("hashrate"), 0, -1)
        
        //Hgetall 命令用於返回雜湊表中,所有的欄位和值
        //HGETALL eth:stats
        tx.HGetAllMap(r.formatKey("stats"))
        
        //Zrevrange 命令返回有序集中,指定區間內的成員
        //ZREVRANGE eth:blocks:candidates 0 -1 WITHSCORES
        //candidates為候選者
        tx.ZRevRangeWithScores(r.formatKey("blocks", "candidates"), 0, -1)
        
        //同上
        //ZREVRANGE eth:blocks:immature 0 -1 WITHSCORES
        //immature為未成年
        tx.ZRevRangeWithScores(r.formatKey("blocks", "immature"), 0, -1)
        
        //同上
        //ZREVRANGE eth:blocks:matured 0 49 WITHSCORES
        //matured為成熟
        tx.ZRevRangeWithScores(r.formatKey("blocks", "matured"), 0, maxBlocks-1)
        
        //Zcard 命令用於計算集合中元素的數量
        //ZCARD eth:blocks:candidates
        tx.ZCard(r.formatKey("blocks", "candidates"))
        
        //同上
        //ZCARD eth:blocks:immature
        tx.ZCard(r.formatKey("blocks", "immature"))
        
        //同上
        //ZCARD eth:blocks:matured
        tx.ZCard(r.formatKey("blocks", "matured"))
        
        //同上
        //ZCARD eth:payments:all
        tx.ZCard(r.formatKey("payments", "all"))
        
        //同上
        //ZREVRANGE eth:payments:all 0 49 WITHSCORES
        tx.ZRevRangeWithScores(r.formatKey("payments", "all"), 0, maxPayments-1)
        return nil
    })

    if err != nil {
        return nil, err
    }

    //Hgetall 命令用於返回雜湊表中,所有的欄位和值
    //HGETALL eth:stats
    result, _ := cmds[2].(*redis.StringStringMapCmd).Result()
    stats["stats"] = convertStringMap(result)
    
    //Zrevrange 命令返回有序集中,指定區間內的成員
    //ZREVRANGE eth:blocks:candidates 0 -1 WITHSCORES
    //Zcard 命令用於計算集合中元素的數量
    //ZCARD eth:blocks:candidates
    candidates := convertCandidateResults(cmds[3].(*redis.ZSliceCmd))
    stats["candidates"] = candidates
    stats["candidatesTotal"] = cmds[6].(*redis.IntCmd).Val()

    //ZREVRANGE eth:blocks:immature 0 -1 WITHSCORES
    //ZCARD eth:blocks:immature
    immature := convertBlockResults(cmds[4].(*redis.ZSliceCmd))
    stats["immature"] = immature
    stats["immatureTotal"] = cmds[7].(*redis.IntCmd).Val()

    //ZREVRANGE eth:blocks:matured 0 49 WITHSCORES
    //ZCARD eth:blocks:matured
    matured := convertBlockResults(cmds[5].(*redis.ZSliceCmd))
    stats["matured"] = matured
    stats["maturedTotal"] = cmds[8].(*redis.IntCmd).Val()

    //ZREVRANGE eth:payments:all 0 49 WITHSCORES
    //ZCARD eth:payments:all
    payments := convertPaymentsResults(cmds[10].(*redis.ZSliceCmd))
    stats["payments"] = payments
    stats["paymentsTotal"] = cmds[9].(*redis.IntCmd).Val()

    //顯示整個有序整合員
    //ZRANGE eth:hashrate 0 -1 WITHSCORES
    totalHashrate, miners := convertMinersStats(window, cmds[1].(*redis.ZSliceCmd))
    stats["miners"] = miners
    stats["minersTotal"] = len(miners)
    stats["hashrate"] = totalHashrate
    return stats, nil
}
```

## CollectLuckStats原理

```go
//調取:stats["luck"], err = s.backend.CollectLuckStats(s.config.LuckWindow)
//"luckWindow": [64, 128, 256],
//Collect stats for shares/diff ratio for this number of blocks
func (r *RedisClient) CollectLuckStats(windows []int) (map[string]interface{}, error) {
    //建立stats map
    stats := make(map[string]interface{})

    tx := r.client.Multi()
    defer tx.Close()

    //max即256
    max := int64(windows[len(windows)-1])

    cmds, err := tx.Exec(func() error {
        //Zrevrange 命令返回有序集中,指定區間內的成員
        //ZREVRANGE eth:blocks:immature 0 -1 WITHSCORES
        tx.ZRevRangeWithScores(r.formatKey("blocks", "immature"), 0, -1)
        
        //ZREVRANGE eth:blocks:matured 0 max-1 WITHSCORES
        tx.ZRevRangeWithScores(r.formatKey("blocks", "matured"), 0, max-1)
        return nil
    })
    if err != nil {
        return stats, err
    }
    //獲取blocks
    blocks := convertBlockResults(cmds[0].(*redis.ZSliceCmd), cmds[1].(*redis.ZSliceCmd))

    calcLuck := func(max int) (int, float64, float64, float64) {
        var total int
        var sharesDiff, uncles, orphans float64
        for i, block := range blocks {
            if i > (max - 1) {
                break
            }
            //叔塊
            if block.Uncle {
                uncles++
            }
            //孤塊
            if block.Orphan {
                orphans++
            }
            //shares/Diff
            sharesDiff += float64(block.TotalShares) / float64(block.Difficulty)
            //total計數
            total++
        }
        if total > 0 {
            //單塊平均shares/Diff
            sharesDiff /= float64(total)
            //uncles率
            uncles /= float64(total)
            //孤塊率
            orphans /= float64(total)
        }
        //返回total計數,平均shares/Diff,uncles率,孤塊率
        return total, sharesDiff, uncles, orphans
    }
    
    //遍歷windows,逐一計算calcLuck,即最近64塊、128塊、256塊的資料統計
    for _, max := range windows {
        total, sharesDiff, uncleRate, orphanRate := calcLuck(max)
        row := map[string]float64{
            "luck": sharesDiff, "uncleRate": uncleRate, "orphanRate": orphanRate,
        }
        //寫入stats map
        stats[strconv.Itoa(total)] = row
        //計數不對
        if total < max {
            break
        }
    }
    return stats, nil
}

func convertBlockResults(rows ...*redis.ZSliceCmd) []*BlockData {
    var result []*BlockData
    //遍歷rows
    for _, row := range rows {
        //遍歷blocks
        for _, v := range row.Val() {
            // "uncleHeight:orphan:nonce:blockHash:timestamp:diff:totalShares:rewardInWei"
            block := BlockData{}
            block.Height = int64(v.Score)
            block.RoundHeight = block.Height
            fields := strings.Split(v.Member.(string), ":")
            block.UncleHeight, _ = strconv.ParseInt(fields[0], 10, 64)
            block.Uncle = block.UncleHeight > 0
            block.Orphan, _ = strconv.ParseBool(fields[1])
            block.Nonce = fields[2]
            block.Hash = fields[3]
            block.Timestamp, _ = strconv.ParseInt(fields[4], 10, 64)
            block.Difficulty, _ = strconv.ParseInt(fields[5], 10, 64)
            block.TotalShares, _ = strconv.ParseInt(fields[6], 10, 64)
            block.RewardString = fields[7]
            block.ImmatureReward = fields[7]
            block.immatureKey = v.Member.(string)
            result = append(result, &block)
        }
    }
    return result
}
```

## purgeStale原理

```go
//config.PurgeInterval為FlushStaleStats定時器,時間為10分鐘
//調取:total, err := s.backend.FlushStaleStats(s.hashrateWindow, s.hashrateLargeWindow)
//s.hashrateWindow即cfg.HashrateWindow,即:為每個礦工估計算力的快速時間間隔,30分鐘
//s.hashrateLargeWindow即cfg.HashrateLargeWindow,即:長期和精確的hashrate時間間隔,3小時
func (r *RedisClient) FlushStaleStats(window, largeWindow time.Duration) (int64, error) {
    //換算成秒
    now := util.MakeTimestamp() / 1000
    
    //max即(now-window,即<(now-window
    max := fmt.Sprint("(", now-int64(window/time.Second))
    
    //Zremrangebyscore 命令用於移除有序集中,指定分數(score)區間內的所有成員
    //ZREMRANGEBYSCORE eth:hashrate -inf (now-window
    //慎重使用
    total, err := r.client.ZRemRangeByScore(r.formatKey("hashrate"), "-inf", max).Result()
    if err != nil {
        return total, err
    }

    var c int64
    //建立map
    miners := make(map[string]struct{})
    //即(now-largeWindow,即<now-largeWindow
    max = fmt.Sprint("(", now-int64(largeWindow/time.Second))

    for {
        var keys []string
        var err error
        
        //SCAN 命令用於迭代當前資料庫中的資料庫鍵
        //SCAN 0 MATCH eth:hashrate:* COUNT 100
        //SCAN c MATCH eth:hashrate:* COUNT 100
        c, keys, err = r.client.Scan(c, r.formatKey("hashrate", "*"), 100).Result()
        if err != nil {
            return total, err
        }
        for _, row := range keys {
            //eth:hashrate:login中擷取login
            login := strings.Split(row, ":")[2]
            //沒有處理過miners[login]
            if _, ok := miners[login]; !ok {
                //Zremrangebyscore 命令用於移除有序集中,指定分數(score)區間內的所有成員
                //ZREMRANGEBYSCORE eth:hashrate:login -inf (now-window
                n, err := r.client.ZRemRangeByScore(r.formatKey("hashrate", login), "-inf", max).Result()
                if err != nil {
                    return total, err
                }
                //已處理的計入miners[login]
                miners[login] = struct{}{}
                //已處理的數量
                total += n
            }
        }
        if c == 0 {
            break
        }
    }
    return total, nil
}
```

## 參考文件

* [gopkg.in/redis.v3](https://godoc.org/gopkg.in/redis.v3)
* [Redis學習手冊(Sorted-Sets資料型別)](https://www.cnblogs.com/stephen-liu74/archive/2012/03/23/2354994.html)
* [Redis Command 命令](http://www.runoob.com/redis/server-command.html)






網址:http://www.qukuailianxueyuan.io/



欲領取造幣技術與全套虛擬機器資料

區塊鏈技術交流QQ群:756146052  備註:CSDN

尹成學院微信:備註:CSDN




網址:http://www.qukuailianxueyuan.io/



欲領取造幣技術與全套虛擬機器資料

區塊鏈技術交流QQ群:756146052  備註:CSDN

尹成學院微信:備註:CSDN

相關文章