You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
367 lines
8.4 KiB
367 lines
8.4 KiB
10 years ago
|
package stratum
|
||
|
|
||
|
import (
|
||
|
"bufio"
|
||
|
"crypto/rand"
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"log"
|
||
|
"net"
|
||
|
"sync"
|
||
|
"sync/atomic"
|
||
|
"time"
|
||
|
|
||
7 years ago
|
"github.com/sammy007/monero-stratum/pool"
|
||
|
"github.com/sammy007/monero-stratum/rpc"
|
||
|
"github.com/sammy007/monero-stratum/util"
|
||
10 years ago
|
)
|
||
|
|
||
|
type StratumServer struct {
|
||
8 years ago
|
config *pool.Config
|
||
|
miners MinersMap
|
||
|
blockTemplate atomic.Value
|
||
8 years ago
|
upstream int32
|
||
|
upstreams []*rpc.RPCClient
|
||
8 years ago
|
timeout time.Duration
|
||
|
estimationWindow time.Duration
|
||
|
blocksMu sync.RWMutex
|
||
8 years ago
|
blockStats map[int64]blockEntry
|
||
8 years ago
|
luckWindow int64
|
||
|
luckLargeWindow int64
|
||
|
roundShares int64
|
||
8 years ago
|
sessionsMu sync.RWMutex
|
||
|
sessions map[*Session]struct{}
|
||
8 years ago
|
}
|
||
|
|
||
8 years ago
|
type blockEntry struct {
|
||
|
height int64
|
||
|
hash string
|
||
|
variance float64
|
||
|
}
|
||
|
|
||
8 years ago
|
type Endpoint struct {
|
||
8 years ago
|
config *pool.Port
|
||
|
instanceId []byte
|
||
|
extraNonce uint32
|
||
8 years ago
|
targetHex string
|
||
8 years ago
|
jobSequence uint64
|
||
10 years ago
|
}
|
||
|
|
||
|
type Session struct {
|
||
|
sync.Mutex
|
||
8 years ago
|
conn *net.TCPConn
|
||
|
enc *json.Encoder
|
||
|
ip string
|
||
|
endpoint *Endpoint
|
||
|
validJobs []*Job
|
||
|
lastBlockHeight int64
|
||
10 years ago
|
}
|
||
|
|
||
|
const (
|
||
|
MaxReqSize = 10 * 1024
|
||
|
)
|
||
|
|
||
8 years ago
|
func NewStratum(cfg *pool.Config) *StratumServer {
|
||
8 years ago
|
stratum := &StratumServer{config: cfg, blockStats: make(map[int64]blockEntry)}
|
||
8 years ago
|
|
||
|
stratum.upstreams = make([]*rpc.RPCClient, len(cfg.Upstream))
|
||
|
for i, v := range cfg.Upstream {
|
||
|
client, err := rpc.NewRPCClient(&v)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
} else {
|
||
|
stratum.upstreams[i] = client
|
||
|
log.Printf("Upstream: %s => %s", client.Name, client.Url)
|
||
|
}
|
||
|
}
|
||
|
log.Printf("Default upstream: %s => %s", stratum.rpc().Name, stratum.rpc().Url)
|
||
|
|
||
10 years ago
|
stratum.miners = NewMinersMap()
|
||
8 years ago
|
stratum.sessions = make(map[*Session]struct{})
|
||
10 years ago
|
|
||
|
timeout, _ := time.ParseDuration(cfg.Stratum.Timeout)
|
||
|
stratum.timeout = timeout
|
||
|
|
||
8 years ago
|
estimationWindow, _ := time.ParseDuration(cfg.EstimationWindow)
|
||
|
stratum.estimationWindow = estimationWindow
|
||
|
|
||
|
luckWindow, _ := time.ParseDuration(cfg.LuckWindow)
|
||
|
stratum.luckWindow = int64(luckWindow / time.Millisecond)
|
||
|
luckLargeWindow, _ := time.ParseDuration(cfg.LargeLuckWindow)
|
||
|
stratum.luckLargeWindow = int64(luckLargeWindow / time.Millisecond)
|
||
|
|
||
8 years ago
|
refreshIntv, _ := time.ParseDuration(cfg.BlockRefreshInterval)
|
||
10 years ago
|
refreshTimer := time.NewTimer(refreshIntv)
|
||
|
log.Printf("Set block refresh every %v", refreshIntv)
|
||
|
|
||
8 years ago
|
checkIntv, _ := time.ParseDuration(cfg.UpstreamCheckInterval)
|
||
|
checkTimer := time.NewTimer(checkIntv)
|
||
|
|
||
8 years ago
|
// Init block template
|
||
8 years ago
|
go stratum.refreshBlockTemplate(false)
|
||
8 years ago
|
|
||
10 years ago
|
go func() {
|
||
|
for {
|
||
|
select {
|
||
|
case <-refreshTimer.C:
|
||
|
stratum.refreshBlockTemplate(true)
|
||
|
refreshTimer.Reset(refreshIntv)
|
||
|
}
|
||
|
}
|
||
|
}()
|
||
8 years ago
|
|
||
|
go func() {
|
||
|
for {
|
||
|
select {
|
||
|
case <-checkTimer.C:
|
||
|
stratum.checkUpstreams()
|
||
|
checkTimer.Reset(checkIntv)
|
||
|
}
|
||
|
}
|
||
|
}()
|
||
|
|
||
10 years ago
|
return stratum
|
||
|
}
|
||
|
|
||
8 years ago
|
func NewEndpoint(cfg *pool.Port) *Endpoint {
|
||
|
e := &Endpoint{config: cfg}
|
||
|
e.instanceId = make([]byte, 4)
|
||
|
_, err := rand.Read(e.instanceId)
|
||
|
if err != nil {
|
||
|
log.Fatalf("Can't seed with random bytes: %v", err)
|
||
|
}
|
||
8 years ago
|
e.targetHex = util.GetTargetHex(e.config.Difficulty)
|
||
8 years ago
|
return e
|
||
|
}
|
||
|
|
||
10 years ago
|
func (s *StratumServer) Listen() {
|
||
8 years ago
|
quit := make(chan bool)
|
||
|
for _, port := range s.config.Stratum.Ports {
|
||
|
go func(cfg pool.Port) {
|
||
|
e := NewEndpoint(&cfg)
|
||
|
e.Listen(s)
|
||
|
}(port)
|
||
|
}
|
||
|
<-quit
|
||
|
}
|
||
|
|
||
|
func (e *Endpoint) Listen(s *StratumServer) {
|
||
|
bindAddr := fmt.Sprintf("%s:%d", e.config.Host, e.config.Port)
|
||
10 years ago
|
addr, err := net.ResolveTCPAddr("tcp", bindAddr)
|
||
8 years ago
|
if err != nil {
|
||
|
log.Fatalf("Error: %v", err)
|
||
|
}
|
||
10 years ago
|
server, err := net.ListenTCP("tcp", addr)
|
||
8 years ago
|
if err != nil {
|
||
|
log.Fatalf("Error: %v", err)
|
||
|
}
|
||
10 years ago
|
defer server.Close()
|
||
|
|
||
|
log.Printf("Stratum listening on %s", bindAddr)
|
||
8 years ago
|
accept := make(chan int, e.config.MaxConn)
|
||
10 years ago
|
n := 0
|
||
|
|
||
|
for {
|
||
|
conn, err := server.AcceptTCP()
|
||
8 years ago
|
if err != nil {
|
||
|
continue
|
||
|
}
|
||
10 years ago
|
conn.SetKeepAlive(true)
|
||
|
ip, _, _ := net.SplitHostPort(conn.RemoteAddr().String())
|
||
8 years ago
|
cs := &Session{conn: conn, ip: ip, enc: json.NewEncoder(conn), endpoint: e}
|
||
10 years ago
|
n += 1
|
||
|
|
||
|
accept <- n
|
||
|
go func() {
|
||
8 years ago
|
s.handleClient(cs, e)
|
||
10 years ago
|
<-accept
|
||
|
}()
|
||
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
func (s *StratumServer) handleClient(cs *Session, e *Endpoint) {
|
||
8 years ago
|
connbuff := bufio.NewReaderSize(cs.conn, MaxReqSize)
|
||
|
s.setDeadline(cs.conn)
|
||
10 years ago
|
|
||
|
for {
|
||
|
data, isPrefix, err := connbuff.ReadLine()
|
||
|
if isPrefix {
|
||
8 years ago
|
log.Println("Socket flood detected from", cs.ip)
|
||
|
break
|
||
10 years ago
|
} else if err == io.EOF {
|
||
8 years ago
|
log.Println("Client disconnected", cs.ip)
|
||
10 years ago
|
break
|
||
|
} else if err != nil {
|
||
8 years ago
|
log.Println("Error reading:", err)
|
||
|
break
|
||
10 years ago
|
}
|
||
|
|
||
|
// NOTICE: cpuminer-multi sends junk newlines, so we demand at least 1 byte for decode
|
||
|
// NOTICE: Ns*CNMiner.exe will send malformed JSON on very low diff, not sure we should handle this
|
||
|
if len(data) > 1 {
|
||
|
var req JSONRpcReq
|
||
|
err = json.Unmarshal(data, &req)
|
||
|
if err != nil {
|
||
8 years ago
|
log.Printf("Malformed request from %s: %v", cs.ip, err)
|
||
8 years ago
|
break
|
||
10 years ago
|
}
|
||
8 years ago
|
s.setDeadline(cs.conn)
|
||
8 years ago
|
err = cs.handleMessage(s, e, &req)
|
||
|
if err != nil {
|
||
|
break
|
||
|
}
|
||
10 years ago
|
}
|
||
|
}
|
||
8 years ago
|
s.removeSession(cs)
|
||
|
cs.conn.Close()
|
||
10 years ago
|
}
|
||
|
|
||
8 years ago
|
func (cs *Session) handleMessage(s *StratumServer, e *Endpoint, req *JSONRpcReq) error {
|
||
10 years ago
|
if req.Id == nil {
|
||
8 years ago
|
err := fmt.Errorf("Server disconnect request")
|
||
|
log.Println(err)
|
||
|
return err
|
||
10 years ago
|
} else if req.Params == nil {
|
||
8 years ago
|
err := fmt.Errorf("Server RPC request params")
|
||
|
log.Println(err)
|
||
|
return err
|
||
10 years ago
|
}
|
||
|
|
||
|
// Handle RPC methods
|
||
|
switch req.Method {
|
||
8 years ago
|
|
||
10 years ago
|
case "login":
|
||
|
var params LoginParams
|
||
8 years ago
|
err := json.Unmarshal(*req.Params, ¶ms)
|
||
10 years ago
|
if err != nil {
|
||
|
log.Println("Unable to parse params")
|
||
8 years ago
|
return err
|
||
10 years ago
|
}
|
||
8 years ago
|
reply, errReply := s.handleLoginRPC(cs, ¶ms)
|
||
10 years ago
|
if errReply != nil {
|
||
8 years ago
|
return cs.sendError(req.Id, errReply, true)
|
||
10 years ago
|
}
|
||
8 years ago
|
return cs.sendResult(req.Id, &reply)
|
||
10 years ago
|
case "getjob":
|
||
|
var params GetJobParams
|
||
8 years ago
|
err := json.Unmarshal(*req.Params, ¶ms)
|
||
10 years ago
|
if err != nil {
|
||
|
log.Println("Unable to parse params")
|
||
8 years ago
|
return err
|
||
10 years ago
|
}
|
||
8 years ago
|
reply, errReply := s.handleGetJobRPC(cs, ¶ms)
|
||
10 years ago
|
if errReply != nil {
|
||
8 years ago
|
return cs.sendError(req.Id, errReply, true)
|
||
10 years ago
|
}
|
||
8 years ago
|
return cs.sendResult(req.Id, &reply)
|
||
10 years ago
|
case "submit":
|
||
|
var params SubmitParams
|
||
|
err := json.Unmarshal(*req.Params, ¶ms)
|
||
|
if err != nil {
|
||
|
log.Println("Unable to parse params")
|
||
8 years ago
|
return err
|
||
10 years ago
|
}
|
||
8 years ago
|
reply, errReply := s.handleSubmitRPC(cs, ¶ms)
|
||
10 years ago
|
if errReply != nil {
|
||
8 years ago
|
return cs.sendError(req.Id, errReply, false)
|
||
10 years ago
|
}
|
||
8 years ago
|
return cs.sendResult(req.Id, &reply)
|
||
10 years ago
|
default:
|
||
8 years ago
|
errReply := s.handleUnknownRPC(req)
|
||
8 years ago
|
return cs.sendError(req.Id, errReply, true)
|
||
10 years ago
|
}
|
||
|
}
|
||
|
|
||
|
func (cs *Session) sendResult(id *json.RawMessage, result interface{}) error {
|
||
|
cs.Lock()
|
||
|
defer cs.Unlock()
|
||
|
message := JSONRpcResp{Id: id, Version: "2.0", Error: nil, Result: result}
|
||
|
return cs.enc.Encode(&message)
|
||
|
}
|
||
|
|
||
|
func (cs *Session) pushMessage(method string, params interface{}) error {
|
||
|
cs.Lock()
|
||
|
defer cs.Unlock()
|
||
|
message := JSONPushMessage{Version: "2.0", Method: method, Params: params}
|
||
|
return cs.enc.Encode(&message)
|
||
|
}
|
||
|
|
||
8 years ago
|
func (cs *Session) sendError(id *json.RawMessage, reply *ErrorReply, drop bool) error {
|
||
10 years ago
|
cs.Lock()
|
||
|
defer cs.Unlock()
|
||
|
message := JSONRpcResp{Id: id, Version: "2.0", Error: reply}
|
||
|
err := cs.enc.Encode(&message)
|
||
8 years ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
if drop {
|
||
|
return fmt.Errorf("Server disconnect request")
|
||
10 years ago
|
}
|
||
8 years ago
|
return nil
|
||
10 years ago
|
}
|
||
|
|
||
|
func (s *StratumServer) setDeadline(conn *net.TCPConn) {
|
||
|
conn.SetDeadline(time.Now().Add(s.timeout))
|
||
|
}
|
||
|
|
||
8 years ago
|
func (s *StratumServer) registerSession(cs *Session) {
|
||
|
s.sessionsMu.Lock()
|
||
|
defer s.sessionsMu.Unlock()
|
||
|
s.sessions[cs] = struct{}{}
|
||
|
}
|
||
|
|
||
|
func (s *StratumServer) removeSession(cs *Session) {
|
||
|
s.sessionsMu.Lock()
|
||
|
defer s.sessionsMu.Unlock()
|
||
|
delete(s.sessions, cs)
|
||
|
}
|
||
|
|
||
|
func (s *StratumServer) isActive(cs *Session) bool {
|
||
|
s.sessionsMu.RLock()
|
||
|
defer s.sessionsMu.RUnlock()
|
||
|
_, exist := s.sessions[cs]
|
||
|
return exist
|
||
|
}
|
||
|
|
||
10 years ago
|
func (s *StratumServer) registerMiner(miner *Miner) {
|
||
8 years ago
|
s.miners.Set(miner.id, miner)
|
||
10 years ago
|
}
|
||
|
|
||
|
func (s *StratumServer) removeMiner(id string) {
|
||
|
s.miners.Remove(id)
|
||
|
}
|
||
|
|
||
|
func (s *StratumServer) currentBlockTemplate() *BlockTemplate {
|
||
8 years ago
|
if t := s.blockTemplate.Load(); t != nil {
|
||
|
return t.(*BlockTemplate)
|
||
|
}
|
||
|
return nil
|
||
10 years ago
|
}
|
||
|
|
||
8 years ago
|
func (s *StratumServer) checkUpstreams() {
|
||
|
candidate := int32(0)
|
||
|
backup := false
|
||
|
|
||
|
for i, v := range s.upstreams {
|
||
|
ok, err := v.Check(8, s.config.Address)
|
||
|
if err != nil {
|
||
|
log.Printf("Upstream %v didn't pass check: %v", v.Name, err)
|
||
|
}
|
||
|
if ok && !backup {
|
||
|
candidate = int32(i)
|
||
|
backup = true
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if s.upstream != candidate {
|
||
|
log.Printf("Switching to %v upstream", s.upstreams[candidate].Name)
|
||
|
atomic.StoreInt32(&s.upstream, candidate)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (s *StratumServer) rpc() *rpc.RPCClient {
|
||
|
i := atomic.LoadInt32(&s.upstream)
|
||
|
return s.upstreams[i]
|
||
|
}
|