stratum

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 15, 2022 License: ISC Imports: 42 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthorizeFn

func AuthorizeFn(ip net.Addr, port int, workerName string, password string) (authorized bool, options map[string]float64, err error)

AuthorizeFn validates worker name and rig name.

func BitsToStr

func BitsToStr(bits uint32) string

func InitClientCtxPool

func InitClientCtxPool()

Types

type API

type API struct {
	// contains filtered or unexported fields
}

func (*API) Run

func (api *API) Run()

type Activity

type Activity struct {
	Connected   int64
	Reconnected int64
}

Activity represents data to track worker (re)connects

type Client

type Client struct {
	SubscriptionId uint64
	Options        *settings.Configuration
	RemoteAddress  net.Addr

	Socket           net.Conn
	SocketBufIO      *bufio.ReadWriter
	SocketBufIOMutex sync.Mutex

	LastActivity time.Time
	Metrics      *Metrics

	IsAuthorized           bool
	SubscriptionBeforeAuth bool

	ExtraNonce1 uint32

	WorkerName string
	WorkerPass string

	// TODO: used by ManuallySetValues method. Delete?
	CurrentTarget  uint32
	PreviousTarget uint32

	PendingDifficulty  *big.Float
	CurrentDifficulty  *big.Float
	PreviousDifficulty *big.Float
	ClientTarget       *big.Int

	JobManager         *JobManager
	BanningManager     *bans.BanningManager
	SocketClosedEvent  chan struct{}
	SendMiningJobEvent chan Job
	// contains filtered or unexported fields
}

func NewStratumClient

func NewStratumClient(subscriptionId uint64, socket net.Conn, options *settings.Configuration, bm *bans.BanningManager, jm *JobManager, sendMiningJobEvent chan Job, stratumUpdateBlock chan events.StratumUpdateBlock) *Client

func (*Client) Authorize

func (sc *Client) Authorize() error

func (*Client) CalcHashRate

func (sc *Client) CalcHashRate() string

CalcHashRate returns human form of hash rate value

func (*Client) CleanupMetrics added in v0.2.1

func (sc *Client) CleanupMetrics()

CleanupMetrics cleans up some metrics on disconnect. Otherwise they will have most recent value and show incorrect values when observing in Grafana for example.

func (*Client) Disconnect added in v0.2.1

func (sc *Client) Disconnect()

func (*Client) GetLabel

func (sc *Client) GetLabel() string

func (*Client) HandleAuthorize

func (sc *Client) HandleAuthorize(message *types.RPCRequest, replyToSocket bool)

func (*Client) HandleConfigure

func (sc *Client) HandleConfigure(message *types.RPCRequest)

HandleConfigure handles mining.configure stratum method. Currently, only version-rolling extension is supported. min-bit-count field is considered obsolete and does not use in the code. Example of this request:

{
		"method": "mining.configure", "id": 1,
		"params": [
			["minimum-difficulty", "version-rolling"],
			{
				"minimum-difficulty.value":      2048,
				"version-rolling.mask":          "1fffe000",
				"version-rolling.min-bit-count": 2
			}
		]
}

func (*Client) HandleLogin

func (sc *Client) HandleLogin(message *types.RPCLoginMessage, replyToSocket bool)

func (*Client) HandleMessage

func (sc *Client) HandleMessage(message *types.RPCRequest)

func (*Client) HandleSubmit

func (sc *Client) HandleSubmit(message *types.RPCRequest)

func (*Client) HandleSubscribe

func (sc *Client) HandleSubscribe(message *types.RPCRequest)

func (*Client) HandleUpdateBlock

func (sc *Client) HandleUpdateBlock(message *types.RPCRequest)

func (*Client) Init

func (sc *Client) Init()

func (*Client) InitPoolDifficulty

func (sc *Client) InitPoolDifficulty()

InitPoolDifficulty calculates initial pool difficulty when new stratum client is connected and sends it to the client.

func (*Client) ManuallyAuthClient

func (sc *Client) ManuallyAuthClient(username, password string)

func (*Client) ManuallySetValues

func (sc *Client) ManuallySetValues(otherClient *Client)

func (*Client) SendDifficulty

func (sc *Client) SendDifficulty(diff *big.Float) bool

func (*Client) SendJSON

func (sc *Client) SendJSON(data interface{})

func (*Client) SendMiningJob

func (sc *Client) SendMiningJob(jobParams types.JobParams)

func (*Client) SetupSocket

func (sc *Client) SetupSocket()

func (*Client) ShouldBan

func (sc *Client) ShouldBan() bool

func (*Client) VarDiffStart

func (sc *Client) VarDiffStart()

VarDiffStart starts variable difficulty feature. Every RetargetTimeWindow represented in seconds it calculates next client difficulty. It stops when receive a data via stopChan channel.

func (*Client) VarDiffStop

func (sc *Client) VarDiffStop()

func (*Client) VarDiffUpdate

func (sc *Client) VarDiffUpdate(clientOptions map[string]float64)

VarDiffUpdate changes variable difficulty options for client connection on the fly.

type HashSortingIndexesRange

type HashSortingIndexesRange struct {
	SmallestIndex uint32
	BiggestIndex  uint32
}

type Job

type Job struct {
	MinerTask tasks.MinerTask
	// types.JobParams
	JobId                 string
	PrevHashReversed      string
	Submits               map[string]struct{}
	GenerationTransaction [][]byte
	Broadcasted           bool
	Bits                  uint32 // Bitcoin block bits
}

func NewJob

func NewJob(task *tasks.MinerTask) (job *Job)

func (*Job) RegisterSubmit

func (j *Job) RegisterSubmit(extraNonce1, extraNonce2, nTime, nonce string) bool

type JobCounter

type JobCounter struct {
	Counter *big.Int
}

type JobManager

type JobManager struct {
	Config                *settings.Configuration
	JobCounter            *JobCounter
	ExtraNoncePlaceholder []byte
	ExtraNonceSize        int // 4
	CurrentJob            Job
	ValidJobsCache        *cache.Cache
	CoinbaseHasher        func([]byte) chainhash.Hash // Not sure if this needed
	MinerResultChan       chan tasks.MinerResult
	// contains filtered or unexported fields
}

func NewJobManager

func NewJobManager(config *settings.Configuration, minerResultChan chan tasks.MinerResult) *JobManager

func (*JobManager) CheckSolution

func (jm *JobManager) CheckSolution(task tasks.MinerTask, nonce uint32, timestamp time.Time, versionBits, lastMask uint32, enableHashSorting bool, hashSortingSlotNumber uint32, clientTarget *big.Int) (tasks.MinerResult, bool)

func (*JobManager) GetJobParamsEx

func (jm *JobManager) GetJobParamsEx(job Job, forceUpdate bool) (types.JobParams, error)

func (*JobManager) ProcessSubmit

func (jm *JobManager) ProcessSubmit(jobId string,
	extraNonce1 uint32, hexExtraNonce2, hexNTime, hexNonce, hexVersionBits string,
	versionRolling types.VersionRolling, ipAddr net.Addr, workerName string, clientTarget *big.Int) (
	share *Share, minerResult tasks.MinerResult)

type Metrics

type Metrics struct {
	Shares          *Shares // Total shares submitted by worker
	SharesPerMinute *Shares // Shares per minute submitted by worker
	Activity        *Activity
}

type Server

type Server struct {
	utils.StoppableMixin

	Config              *settings.Configuration
	Listener            net.Listener
	VarDiff             *vardiff.VarDiff
	StratumClients      map[uint64]*Client
	StratumClientsMutex sync.Mutex
	SubscriptionCounter *SubscriptionCounter
	BanningManager      *bans.BanningManager
	JobManager          *JobManager
	// rebroadcastTicker     *time.Ticker
	ReceiveMiningJobEvent   chan Job
	APIServer               *API
	StratumUpdateBlockEvent chan events.StratumUpdateBlock
	// contains filtered or unexported fields
}

Server describes structure of the stratum server.

func NewStratumServer

func NewStratumServer(options *settings.Configuration) *Server

func (*Server) BroadcastCurrentMiningJob

func (ss *Server) BroadcastCurrentMiningJob(jobParams types.JobParams)

func (*Server) BroadcastJob added in v0.2.1

func (ss *Server) BroadcastJob()

BroadcastJob broadcasts new jobs to stratum clients.

func (*Server) HandleClientDisconnect added in v0.2.1

func (ss *Server) HandleClientDisconnect(client *Client)

HandleClientDisconnect handles stratum client disconnect.

func (*Server) HandleNewClient

func (ss *Server) HandleNewClient(socket net.Conn)

HandleNewClient converts the connection to an underlying client instance

func (*Server) HandleNewConnection added in v0.2.1

func (ss *Server) HandleNewConnection()

func (*Server) Init

func (ss *Server) Init(minerResultChan chan tasks.MinerResult, stratumUpdateBlockEvent chan events.StratumUpdateBlock)

func (*Server) PublishPeriodicMetrics added in v0.2.1

func (ss *Server) PublishPeriodicMetrics()

PublishPeriodicMetrics produces periodic metrics.

func (*Server) RemoveStratumClientBySubscriptionId

func (ss *Server) RemoveStratumClientBySubscriptionId(subscriptionId uint64)

func (*Server) Run

func (ss *Server) Run(c *state.Coordinator)

Run sends current mining task to miner.

func (*Server) RunAPI added in v0.2.1

func (ss *Server) RunAPI()

RunAPI runs internal API server within Stratum server

func (*Server) StopAPI added in v0.2.1

func (ss *Server) StopAPI()

StopAPI stops internal API server within Stratum server

type Share

type Share struct {
	JobId      string          `json:"jobId"`
	RemoteAddr net.Addr        `json:"remoteAddr"`
	Miner      string          `json:"miner"`
	Rig        string          `json:"rig"`
	ErrorCode  types.ErrorWrap `json:"errorCode"`
	DiffBigInt *big.Int        `json:"diffBigInt"`
	// TODO: not sure if fields below are needed
	BlockHeight int64   `json:"height"`
	BlockReward uint64  `json:"blockReward"`
	Diff        float64 `json:"shareDiff"`
	BlockHash   string  `json:"blockHash"`
	BlockHex    string  `json:"blockHex"`
	TxHash      string  `json:"txHash"`
}

type Shares

type Shares struct {
	Valid   uint64
	Invalid uint64
}

func (*Shares) BadPercent

func (s *Shares) BadPercent() float64

func (*Shares) GetInvalid

func (s *Shares) GetInvalid() uint64

func (*Shares) GetValid

func (s *Shares) GetValid() uint64

func (*Shares) IncrementInvalid

func (s *Shares) IncrementInvalid()

func (*Shares) IncrementValid

func (s *Shares) IncrementValid()

func (*Shares) Reset

func (s *Shares) Reset()

func (*Shares) TotalShares

func (s *Shares) TotalShares() uint64

type SubscriptionCounter

type SubscriptionCounter struct {
	Count   uint64
	Padding []byte
}

SubscriptionCounter describes number of currently connected stratum clients. Supports 18446744073709551615 max connections.

func NewSubscriptionCounter

func NewSubscriptionCounter() *SubscriptionCounter

func (*SubscriptionCounter) Next

func (sc *SubscriptionCounter) Next() uint64

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL