network

package
v0.0.0-...-b221635 Latest Latest
Warning

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

Go to latest
Published: May 25, 2019 License: ISC Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// apiClient represents an api client.
	APIClient = "api"

	// poolClient represents a pool client.
	PoolClient = "pool"
)
View Source
const (
	RequestType      = "request"
	ResponseType     = "response"
	NotificationType = "notification"
)

Message types.

View Source
const (
	Authorize     = "mining.authorize"
	Subscribe     = "mining.subscribe"
	SetDifficulty = "mining.set_difficulty"
	Notify        = "mining.notify"
	Submit        = "mining.submit"
)

Handler types.

View Source
const (
	Unknown            = 20
	StaleJob           = 21
	DuplicateShare     = 22
	LowDifficultyShare = 23
	UnauthorizedWorker = 24
	NotSubscribed      = 25
)

Error codes.

View Source
const (
	ExtraNonce2Size = 4
)

Stratum constants.

View Source
const (
	// MaxMessageSize represents the maximum size of a transmitted message
	// allowed, in bytes.
	MaxMessageSize = 250
)
View Source
const (
	// MaxReorgLimit is an estimated maximum chain reorganization limit.
	// That is, it is highly improbable for the the chain to reorg beyond six
	// blocks from the chain tip.
	MaxReorgLimit = 6
)

Variables

This section is empty.

Functions

func AcceptedWorkID

func AcceptedWorkID(blockHash string, blockHeight uint32) []byte

AcceptedWorkID generates a unique id for the work accepted by the network.

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func ErrWorkAlreadyExists

func ErrWorkAlreadyExists(id []byte) error

ErrWorkAlreadyExists is returned when an already existing work is found for the provided work id.

func ErrWorkNotFound

func ErrWorkNotFound(id []byte) error

ErrWorkNotFound is returned when no work is found for the provided work id.

func GenerateBlockHeader

func GenerateBlockHeader(blockVersionE string, prevBlockE string, genTx1E string, extraNonce1E string, genTx2E string) (*wire.BlockHeader, error)

GenerateBlockHeader creates a block header from a mining.notify message and the extraNonce1 of the client.

func GenerateJobID

func GenerateJobID(height uint32) (string, error)

GenerateJobID generates a unique job id of the provided block height.

func GenerateSolvedBlockHeader

func GenerateSolvedBlockHeader(headerE string, extraNonce1E string, extraNonce2E string, nTimeE string, nonceE string, miner string) (*wire.BlockHeader, error)

GenerateSolvedBlockHeader create a block header from a mining.submit message and its associated job.

func ParseAuthorizeRequest

func ParseAuthorizeRequest(req *Request) (string, error)

ParseAuthorizeRequest resolves an authorize request into its components.

func ParseSetDifficultyNotification

func ParseSetDifficultyNotification(req *Request) (uint64, error)

ParseSetDifficultyNotification resolves a set difficulty notification into its components.

func ParseSubmitWorkRequest

func ParseSubmitWorkRequest(req *Request, miner string) (string, string, string, string, string, error)

ParseSubmitWorkRequest resolves a submit work request into its components.

func ParseSubscribeRequest

func ParseSubscribeRequest(req *Request) (string, string, error)

ParseSubscribeRequest resolves a subscribe request into its components.

func ParseSubscribeResponse

func ParseSubscribeResponse(resp *Response) (string, string, string, uint64, error)

ParseSubscribeResponse resolves a subscribe response into its components.

func ParseWorkNotification

func ParseWorkNotification(req *Request) (string, string, string, string, string, string, string, bool, error)

ParseWorkNotification resolves a work notification message into its components.

func PruneAcceptedWork

func PruneAcceptedWork(db *bolt.DB, height uint32) error

PruneAcceptedWork removes all accepted work not confirmed as mined work with heights less than the provided height.

func PruneJobs

func PruneJobs(db *bolt.DB, height uint32) error

PruneJobs removes all jobs with heights less than the provided height.

func UseLogger

func UseLogger(logger slog.Logger)

UseLogger uses a specified Logger to output package logging info.

Types

type AcceptedWork

type AcceptedWork struct {
	UUID      string `json:"uuid"`
	BlockHash string `json:"blockhash"`
	PrevHash  string `json:"prevhash"`
	Height    uint32 `json:"height"`
	MinedBy   string `json:"minedby"`
	Miner     string `json:"miner"`
	CreatedOn int64  `json:"createdon"`

	// An accepted work becomes mined work once it is confirmed by an incoming
	// work as the parent block it was built on.
	Confirmed bool `json:"confirmed"`
}

AcceptedWork represents an accepted work submission to the network.

func FetchAcceptedWork

func FetchAcceptedWork(db *bolt.DB, id []byte) (*AcceptedWork, error)

FetchAcceptedWork fetches the accepted work referenced by the provided id.

func ListMinedWork

func ListMinedWork(db *bolt.DB, n uint) ([]*AcceptedWork, error)

ListMinedWork returns the N most recent work data associated with blocks mined by the pool. List is ordered, most recent comes first.

func ListMinedWorkByAccount

func ListMinedWorkByAccount(db *bolt.DB, accountID string, n uint) ([]*AcceptedWork, error)

ListMinedWorkByAccount returns the N most recent mined work data on blocks mined by the provided pool account id. List is ordered, most recent comes first.

func NewAcceptedWork

func NewAcceptedWork(blockHash string, prevHash string, height uint32, minedBy string, miner string) *AcceptedWork

NewAcceptedWork creates an accepted work instance.

func (*AcceptedWork) Create

func (work *AcceptedWork) Create(db *bolt.DB) error

Create persists the accepted work to the database.

func (*AcceptedWork) Delete

func (work *AcceptedWork) Delete(db *bolt.DB) error

Delete removes the associated accepted work from the database.

func (*AcceptedWork) Update

func (work *AcceptedWork) Update(db *bolt.DB) error

Update persists modifications to an existing work.

type Client

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

Client represents a client connection.

func NewClient

func NewClient(conn net.Conn, endpoint *Endpoint, ip string) *Client

NewClient creates client connection instance.

func (*Client) GenerateExtraNonce1

func (c *Client) GenerateExtraNonce1()

GenerateExtraNonce1 generates a random 4-byte extraNonce1 for the client.

type ClientInfo

type ClientInfo struct {
	Miner    string
	IP       string
	HashRate *big.Rat
}

type DifficultyData

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

DifficultyData captures the pool target difficulty and pool difficulty ratio of a mining client.

type Endpoint

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

Endpoint represents a stratum endpoint.

func NewEndpoint

func NewEndpoint(hub *Hub, port uint32, miner string) (*Endpoint, error)

NewEndpoint creates an endpoint instance.

func (*Endpoint) RemoveClient

func (e *Endpoint) RemoveClient(c *Client)

RemoveClient removes a disconnected pool client from its associated endpoint.

type Hub

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

Hub maintains the set of active clients and facilitates message broadcasting to all active clients.

func NewHub

func NewHub(ctx context.Context, cancel context.CancelFunc, db *bolt.DB, httpc *http.Client, hcfg *HubConfig, limiter *RateLimiter) (*Hub, error)

NewHub initializes a websocket hub.

func (*Hub) FetchClientInfo

func (h *Hub) FetchClientInfo() map[string][]*ClientInfo

FetchClientInfo returns information about all connected clients

func (*Hub) FetchMinedWorkByAddress

func (h *Hub) FetchMinedWorkByAddress(id string) ([]*AcceptedWork, error)

FetchMinedWorkByAddress returns a list of mined work by the provided address. List is ordered, most recent comes first.

func (*Hub) FetchPaymentsForAddress

func (h *Hub) FetchPaymentsForAddress(id string) ([]*dividend.Payment, error)

FetchPaymentsForAddress returns a list or payments made to the provided address. List is ordered, most recent comes first.

func (*Hub) FetchPoolStats

func (h *Hub) FetchPoolStats() (*PoolStats, error)

FetchPoolStats returns last height work was generated for.

func (*Hub) FetchWorkQuotas

func (h *Hub) FetchWorkQuotas() (*WorkQuotas, error)

FetchWorkQuotas returns the reward distribution to pool accounts based on work contributed per the peyment scheme used by the pool.

func (*Hub) GenerateBlake256Pad

func (h *Hub) GenerateBlake256Pad()

GenerateBlake256Pad generates the extra padding needed for work submission over the getwork RPC.

func (*Hub) GenerateDifficultyData

func (h *Hub) GenerateDifficultyData() error

GenerateDifficultyData generates difficulty data for all known miners.

func (*Hub) GetWork

func (h *Hub) GetWork() (string, string, error)

GetWork fetches available work from the consensus daemon.

func (*Hub) HasClients

func (h *Hub) HasClients() bool

HasClients asserts the mining pool has clients.

func (*Hub) ProcessPayments

func (h *Hub) ProcessPayments(height uint32) error

ProcessPayments fetches all eligible payments and publishes a transaction to the network paying dividends to participating accounts.

func (*Hub) PublishTransaction

func (h *Hub) PublishTransaction(payouts map[bitumutil.Address]bitumutil.Amount, targetAmt bitumutil.Amount) error

PublishTransaction creates a transaction paying pool accounts for work done.

func (*Hub) Run

func (h *Hub) Run(ctx context.Context)

run handles the process lifecycles of the pool hub.

func (*Hub) SubmitWork

func (h *Hub) SubmitWork(data *string) (bool, error)

SubmitWork sends solved block data to the consensus daemon for evaluation.

type HubConfig

type HubConfig struct {
	ActiveNet         *chaincfg.Params
	BitumdRPCCfg      *rpcclient.ConnConfig
	PoolFee           float64
	MaxTxFeeReserve   bitumutil.Amount
	MaxGenTime        *big.Int
	WalletRPCCertFile string
	WalletGRPCHost    string
	PaymentMethod     string
	LastNPeriod       uint32
	WalletPass        string
	MinPayment        bitumutil.Amount
	SoloPool          bool
	PoolFeeAddrs      []bitumutil.Address
	BackupPass        string
	Secret            string
}

HubConfig represents configuration details for the hub.

type Job

type Job struct {
	UUID   string `json:"uuid"`
	Height uint32 `json:"height"`
	Header string `json:"header"`
}

Job represents cached copies of work delivered to clients.

func FetchJob

func FetchJob(db *bolt.DB, id []byte) (*Job, error)

FetchJob fetches the job referenced by the provided id.

func NewJob

func NewJob(header string, height uint32) (*Job, error)

NewJob creates a job instance.

func (*Job) Create

func (job *Job) Create(db *bolt.DB) error

Create persists the job to the database.

func (*Job) Delete

func (job *Job) Delete(db *bolt.DB) error

Delete removes the associated job from the database.

func (*Job) Update

func (job *Job) Update(db *bolt.DB) error

Update persists the updated accepted work to the database.

type Message

type Message interface {
	MessageType() string
}

Message defines a message interface.

func IdentifyMessage

func IdentifyMessage(data []byte) (Message, string, error)

IdentifyMessage determines the received message type. It returns the message cast to the appropriate message type, the message type and an error type.

type PoolStats

type PoolStats struct {
	LastWorkHeight    uint32
	LastPaymentHeight uint32
	MinedWork         []*AcceptedWork
}

PoolStats details the pool's work and payment statistics.

type Quota

type Quota struct {
	AccountID  string
	Percentage *big.Rat
}

Quota details the portion of mining rewrds due an account for work contributed to the pool.

type RateLimiter

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

RateLimiter represents the rate limiting module of the mining pool. It identifies clients by their IP address and throttles incoming request if necessary when the allocated quota has been exceeded.

func NewRateLimiter

func NewRateLimiter() *RateLimiter

NewRateLimiter initializes a rate limiter.

func (*RateLimiter) AddRequestLimiter

func (r *RateLimiter) AddRequestLimiter(ip string, clientType string) *RequestLimiter

AddRequestLimiter adds a new client request limiter to the limiter set.

func (*RateLimiter) GetLimiter

func (r *RateLimiter) GetLimiter(ip string) *RequestLimiter

GetLimiter fetches the request limiter referenced by the provided IP address.

func (*RateLimiter) LimiterMiddleware

func (r *RateLimiter) LimiterMiddleware(next http.Handler) http.Handler

LimiterMiddleware wraps the the request limit logic as request middleware.

func (*RateLimiter) RemoveLimiter

func (r *RateLimiter) RemoveLimiter(ip string)

RemoveLimiter deletes the request limiter associated with the provided ip.

func (*RateLimiter) WithinLimit

func (r *RateLimiter) WithinLimit(ip string, clientType string) bool

WithinLimit asserts that the client referenced by the provided IP address is within the limits of the rate limiter, therefore can make further requests. If no request limiter is found for the provided IP address a new one is created.

type Request

type Request struct {
	ID     *uint64     `json:"id"`
	Method string      `json:"method"`
	Params interface{} `json:"params"`
}

Request defines a request message.

func AuthorizeRequest

func AuthorizeRequest(id *uint64, name string, address string) *Request

AuthorizeRequest creates an authorize request message.

func NewRequest

func NewRequest(id *uint64, method string, params interface{}) *Request

NewRequest creates a request instance.

func SetDifficultyNotification

func SetDifficultyNotification(difficulty *big.Int) *Request

SetDifficultyNotification creates a set difficulty notification message.

func SubmitWorkRequest

func SubmitWorkRequest(id *uint64, workerName string, jobID string, extraNonce2 string, nTime string, nonce string) *Request

SubmitWorkRequest creates a submit request message.

func SubscribeRequest

func SubscribeRequest(id *uint64, userAgent string, version string, notifyID string) *Request

SubscribeRequest creates a subscribe request message.

func WorkNotification

func WorkNotification(jobID string, prevBlock string, genTx1 string, genTx2 string, blockVersion string, nBits string, nTime string, cleanJob bool) *Request

WorkNotification creates a work notification message.

func (*Request) MessageType

func (req *Request) MessageType() string

MessageType returns the request message type.

type RequestLimiter

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

RequestLimiter represents a rate limiter for a connecting client. This identifies clients by their IP addresses.

type Response

type Response struct {
	ID     uint64        `json:"id"`
	Error  *StratumError `json:"error"`
	Result interface{}   `json:"result,omitempty"`
}

Response defines a response message.

func AuthorizeResponse

func AuthorizeResponse(id uint64, status bool, err *StratumError) *Response

AuthorizeResponse creates an authorize response.

func NewResponse

func NewResponse(id uint64, result interface{}, err *StratumError) *Response

NewResponse creates a response instance.

func SubmitWorkResponse

func SubmitWorkResponse(id uint64, status bool, err *StratumError) *Response

SubmitWorkResponse creates a submit response.

func SubscribeResponse

func SubscribeResponse(id uint64, notifyID string, extraNonce1 string, err *StratumError) *Response

SubscribeResponse creates a mining.subscribe response.

func (*Response) MessageType

func (req *Response) MessageType() string

MessageType returns the response message type.

type StratumError

type StratumError struct {
	Code      uint32  `json:"code"`
	Message   string  `json:"message"`
	Traceback *string `json:"traceback"`
}

StratumError represents a stratum error message.

func NewStratumError

func NewStratumError(code uint32, traceback *string) *StratumError

NewStratumError creates a stratum error instance.

func ParseAuthorizeResponse

func ParseAuthorizeResponse(resp *Response) (bool, *StratumError, error)

ParseAuthorizeResponse resolves an authorize response into its components.

func ParseSubmitWorkResponse

func ParseSubmitWorkResponse(resp *Response) (bool, *StratumError, error)

ParseSubmitWorkResponse resolves a submit response into its components.

type WorkQuotas

type WorkQuotas struct {
	PaymentScheme string
	Quotas        []Quota
}

WorkQuotas details the how mining rewards are to be distributed to participating accounts when a block is found, per the payment scheme.

Jump to

Keyboard shortcuts

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