Skip to content

Commit

Permalink
Revert "Fix/status page error (bittorrent#225)" (bittorrent#226)
Browse files Browse the repository at this point in the history
This reverts commit 05bc559.
  • Loading branch information
Shawn-Huang-Tron authored and daniel-tron committed Sep 1, 2022
1 parent 17469b9 commit 71c8274
Show file tree
Hide file tree
Showing 5 changed files with 679 additions and 6 deletions.
145 changes: 145 additions & 0 deletions chain/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,148 @@ func StoreChainIdIfNotExists(chainID int64, statestore storage.StateStorer) erro

return nil
}

// GetReportStatus from leveldb
var keyReportStatus = "keyReportStatus"

type ReportStatusInfo struct {
ReportStatusSeconds int64
LastReportTime time.Time
}

func GetReportStatus() (*ReportStatusInfo, error) {
if StateStore == nil {
return nil, errors.New("please start btfs node, at first! ")
}

var reportStatusInfo ReportStatusInfo
err := StateStore.Get(keyReportStatus, &reportStatusInfo)
if err != nil {
if err == storage.ErrNotFound {
reportStatusInfo = ReportStatusInfo{ReportStatusSeconds: int64(rand.Intn(100000000) % 86400), LastReportTime: time.Time{}}
err := StateStore.Put(keyReportStatus, reportStatusInfo)
if err != nil {
fmt.Println("StoreChainIdIfNotExists: init StoreChainId err: ", err)
return nil, err
}
}
return nil, err
}
return &reportStatusInfo, nil
}

func SetReportStatusOK() (*ReportStatusInfo, error) {
var reportStatusInfo ReportStatusInfo
err := StateStore.Get(keyReportStatus, &reportStatusInfo)
if err != nil {
return nil, err
}
reportStatusInfo.LastReportTime = time.Now()
err = StateStore.Put(keyReportStatus, reportStatusInfo)
if err != nil {
return nil, err
}
//fmt.Println("... ReportStatus, SetReportStatus: ok! ")
return &reportStatusInfo, nil
}

// GetReportStatus from leveldb
var keyReportStatusList = "keyReportStatusList"

type LevelDbReportStatusInfo struct {
Peer string `json:"peer"`
BttcAddress string `json:"bttc_addr"`
StatusContract string `json:"status_contract"`
Nonce uint32 `json:"nonce"`
TxHash string `json:"tx_hash"`
GasSpend string `json:"gas_spend"`
ReportTime time.Time `json:"report_time"`
IncreaseNonce uint32 `json:"increase_nonce"`
}

// SetReportStatusListOK store tx list
func SetReportStatusListOK(r *LevelDbReportStatusInfo) ([]*LevelDbReportStatusInfo, error) {
if StateStore == nil {
return nil, errors.New("please start btfs node, at first! ")
}

init := false

rList := make([]*LevelDbReportStatusInfo, 0)
err := StateStore.Get(keyReportStatusList, &rList)
if err != nil {
if err.Error() == "storage: not found" {
init = true
// continue
} else {
return nil, err
}
}

if init {
r.IncreaseNonce = r.Nonce
} else {
r.IncreaseNonce = r.Nonce - rList[len(rList)-1].Nonce
}

rList = append(rList, r)
err = StateStore.Put(keyReportStatusList, rList)
if err != nil {
return nil, err
}
//fmt.Println("... ReportStatus, SetReportStatusListOK: ok! rList = ", rList)
return rList, nil
}

// GetReportStatusListOK store tx list
func GetReportStatusListOK() ([]*LevelDbReportStatusInfo, error) {
if StateStore == nil {
return nil, errors.New("please start btfs node, at first! ")
}

rList := make([]*LevelDbReportStatusInfo, 0)
err := StateStore.Get(keyReportStatusList, &rList)
if err != nil {
if err.Error() == "storage: not found" {
return nil, nil
} else {
return nil, err
}
}

return rList, nil
}

// GetLastOnline from leveldb
var keyLastOnline = "keyLastOnline"

type LastOnlineInfo struct {
LastSignedInfo onlinePb.SignedInfo
LastSignature string
LastTime time.Time
}

func GetLastOnline() (*LastOnlineInfo, error) {
if StateStore == nil {
return nil, errors.New("please start btfs node, at first! ")
}

var lastOnlineInfo LastOnlineInfo
err := StateStore.Get(keyLastOnline, &lastOnlineInfo)
if err != nil {
if err == storage.ErrNotFound {
return nil, nil
}
return nil, err
}
return &lastOnlineInfo, nil
}
func StoreOnline(lastOnlineInfo *LastOnlineInfo) error {
err := StateStore.Put(keyLastOnline, *lastOnlineInfo)
if err != nil {
fmt.Println("StoreOnline: init StoreChainId err: ", err)
return err
}

return nil
}
235 changes: 235 additions & 0 deletions core/commands/statuscontract.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
package commands

import (
"encoding/json"
"errors"
"fmt"
"github.com/bittorrent/go-btfs/core/commands/cmdenv"
"io"
"math/big"
"strconv"
"time"

cmds "github.com/bittorrent/go-btfs-cmds"
"github.com/bittorrent/go-btfs/chain"
)

var StatusContractCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "report status-contract cmd.",
ShortDescription: `
report status-contract cmd, total cmd and list cmd.`,
},
Subcommands: map[string]*cmds.Command{
"total": TotalCmd,
"reportlist": ReportListCmd,
"lastinfo": LastInfoCmd,
"config": StatusConfigCmd,
},
}

type TotalCmdRet struct {
PeerId string `json:"peer_id"`
StatusContract string `json:"status_contract"`
TotalCount int `json:"total_count"`
TotalGasSpend string `json:"total_gas_spend"`
}

var TotalCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "report status-contract total info, (total count, total gas spend, and contract address)",
},
RunTimeout: 5 * time.Minute,
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
n, err := cmdenv.GetNode(env)
if err != nil {
return err
}
peerId := n.Identity.Pretty()

list, err := chain.GetReportStatusListOK()
if err != nil {
return err
}
if list == nil {
return nil
}

// get list to cal spend, from string to big.int...
totalGasSpend := new(big.Int)
for _, r := range list {
n := new(big.Int)
if len(r.GasSpend) <= 0 {
//fmt.Println("r.GasSpend is zero. ")
continue
}
//fmt.Println("r.GasSpend = ", r.GasSpend)

n, ok := n.SetString(r.GasSpend, 10)
if !ok {
return errors.New("parse gas_spend is error. ")
}
totalGasSpend = totalGasSpend.Add(totalGasSpend, n)
}

return cmds.EmitOnce(res, &TotalCmdRet{
PeerId: peerId,
StatusContract: list[len(list)-1].StatusContract,
TotalCount: len(list),
TotalGasSpend: totalGasSpend.String(),
})
},
Type: TotalCmdRet{},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *TotalCmdRet) error {
marshaled, err := json.MarshalIndent(out, "", "\t")
if err != nil {
return err
}
marshaled = append(marshaled, byte('\n'))
fmt.Fprintln(w, string(marshaled))
return nil
}),
},
}

type ReportListCmdRet struct {
Records []*chain.LevelDbReportStatusInfo `json:"records"`
Total int `json:"total"`
PeerId string `json:"peer_id"`
}

var ReportListCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "report status-contract list, and input from and limit to get its.",
},
RunTimeout: 5 * time.Minute,
Arguments: []cmds.Argument{
cmds.StringArg("from", true, false, "page offset"),
cmds.StringArg("limit", true, false, "page limit."),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
n, err := cmdenv.GetNode(env)
if err != nil {
return err
}
peerId := n.Identity.Pretty()

from, err := strconv.Atoi(req.Arguments[0])
if err != nil {
return fmt.Errorf("parse from:%v failed", req.Arguments[0])
}
limit, err := strconv.Atoi(req.Arguments[1])
if err != nil {
return fmt.Errorf("parse limit:%v failed", req.Arguments[1])
}
if from < 0 {
return fmt.Errorf("invalid from: %d", from)
}
if limit < 0 {
return fmt.Errorf("invalid limit: %d", limit)
}

list, err := chain.GetReportStatusListOK()
if err != nil {
return err
}
if list == nil {
return nil
}
//
//from := 0
//limit := 10

From := len(list) - 1 - from - limit
if From <= 0 {
From = 0
}
To := len(list) - 1 - from
if To > len(list)-1 {
To = len(list) - 1
}
fmt.Println("From, To = ", From, To)

s := list[From:To]
l := len(s)
for i, j := 0, l-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}

return cmds.EmitOnce(res, &ReportListCmdRet{
Records: s,
Total: len(list),
PeerId: peerId,
})
},
Type: ReportListCmdRet{},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ReportListCmdRet) error {
marshaled, err := json.MarshalIndent(out, "", "\t")
if err != nil {
return err
}
marshaled = append(marshaled, byte('\n'))
fmt.Fprintln(w, string(marshaled))
return nil
}),
},
}

var LastInfoCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "get reporting status-contract last info",
},
RunTimeout: 5 * time.Minute,
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
last, err := chain.GetLastOnline()
if err != nil {
return err
}
if last == nil {
return errors.New("not found. ")
}

return cmds.EmitOnce(res, last)
},
Type: chain.LastOnlineInfo{},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *chain.LastOnlineInfo) error {
marshaled, err := json.MarshalIndent(out, "", "\t")
if err != nil {
return err
}
marshaled = append(marshaled, byte('\n'))
fmt.Fprintln(w, string(marshaled))
return nil
}),
},
}

var StatusConfigCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "get reporting status-contract config. ",
},
RunTimeout: 5 * time.Minute,
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
rs, err := chain.GetReportStatus()
if err != nil {
return err
}

return cmds.EmitOnce(res, rs)
},
Type: chain.ReportStatusInfo{},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *chain.ReportStatusInfo) error {
marshaled, err := json.MarshalIndent(out, "", "\t")
if err != nil {
return err
}
marshaled = append(marshaled, byte('\n'))
fmt.Fprintln(w, string(marshaled))
return nil
}),
},
}
Loading

0 comments on commit 71c8274

Please sign in to comment.