pool

package
v0.0.0-...-e04ab8b Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2020 License: ISC Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Supported mining clients
	CPU           = "cpu"
	InnosiliconD9 = "innosilicond9"
	AntminerDR3   = "antminerdr3"
	AntminerDR5   = "antminerdr5"
	WhatsminerD1  = "whatsminerd1"
)
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

	NewParent = "newparent"
	NewVotes  = "newvotes"
	NewTxns   = "newtxns"
)
View Source
const (
	APIClient = iota
	PoolClient
)

Client types.

View Source
const (
	UnknownMessage = iota
	RequestMessage
	ResponseMessage
	NotificationMessage
)

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 (

	// DBVersion is the latest version of the database that is understood by the
	// program. Databases with recorded versions higher than this will fail to
	// open (meaning any upgrades prevent reverting to older software).
	DBVersion = transactionIDVersion
)
View Source
const (
	ExtraNonce2Size = 4
)

Stratum constants.

View Source
const (
	// MaxMessageSize represents the maximum size of a transmitted message
	// allowed, in bytes.
	MaxMessageSize = 250
)

Variables

View Source
var (
	// ZeroInt is the default value for a big.Int.
	ZeroInt = new(big.Int).SetInt64(0)

	// ZeroRat is the default value for a big.Rat.
	ZeroRat = new(big.Rat).SetInt64(0)
)
View Source
var (
	// PPS represents the pay per share payment method.
	PPS = "pps"

	// PPLNS represents the pay per last n shares payment method.
	PPLNS = "pplns"
)
View Source
var ShareWeights = map[string]*big.Rat{
	CPU: new(big.Rat).SetFloat64(1.0),

	InnosiliconD9: new(big.Rat).SetFloat64(2.182),
	AntminerDR3:   new(big.Rat).SetFloat64(7.091),
	AntminerDR5:   new(big.Rat).SetFloat64(31.181),
	WhatsminerD1:  new(big.Rat).SetFloat64(43.636),
}

ShareWeights reprsents the associated weights for each known DCR miner. With the share weight of the lowest hash DCR miner (LHM) being 1, the rest were calculated as :

(Hash of Miner X * Weight of LHM)/ Hash of LHM

Functions

func AcceptedWorkID

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

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

func AccountID

func AccountID(address string, activeNet *chaincfg.Params) (string, error)

AccountID generates a unique id using provided address of the account.

func DifficultyToTarget

func DifficultyToTarget(net *chaincfg.Params, difficulty *big.Rat) (*big.Rat, error)

DifficultyToTarget converts the provided difficulty to a target based on the active network.

func DisableLog

func DisableLog()

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

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 GeneratePaymentID

func GeneratePaymentID(createdOnNano int64, height uint32, account string) []byte

GeneratePaymentID generates a unique id using the provided account and the created on nano time.

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 InitDB

func InitDB(dbFile string, isSoloPool bool) (*bolt.DB, error)

InitDB handles the creation, upgrading and backup of the pool database.

func IsError

func IsError(err error, code ErrorCode) bool

IsError returns whether err is an Error with a matching error code.

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 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 int) ([]*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 NewAcceptedWork

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

NewAcceptedWork creates an accepted work.

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 Account

type Account struct {
	UUID      string `json:"uuid"`
	Address   string `json:"address"`
	CreatedOn uint64 `json:"createdon"`
}

Account represents a mining pool account.

func FetchAccount

func FetchAccount(db *bolt.DB, id []byte) (*Account, error)

FetchAccount fetches the account referenced by the provided id.

func NewAccount

func NewAccount(address string, activeNet *chaincfg.Params) (*Account, error)

NewAccount creates a new account.

func (*Account) Create

func (acc *Account) Create(db *bolt.DB) error

Create persists the account to the database.

func (*Account) Delete

func (acc *Account) Delete(db *bolt.DB) error

Delete purges the referenced account from the database.

func (*Account) Update

func (acc *Account) Update(db *bolt.DB) error

Update is not supported for accounts.

type ChainState

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

ChainState represents the current state of the chain.

func NewChainState

func NewChainState(sCfg *ChainStateConfig) *ChainState

NewChainState creates a a chain state.

type ChainStateConfig

type ChainStateConfig struct {
	// DB represents the pool database.
	DB *bolt.DB
	// SoloPool represents the solo pool mining mode.
	SoloPool bool
	// PayDividends pays mature mining rewards to participating accounts.
	PayDividends func(uint32) error
	// GeneratePayments creates payments for participating accounts in pool
	// mining mode based on the configured payment scheme.
	GeneratePayments func(uint32, dcrutil.Amount) error
	// GetBlock fetches the block associated with the provided block hash.
	GetBlock func(*chainhash.Hash) (*wire.MsgBlock, error)
	// Cancel represents the pool's context cancellation function.
	Cancel context.CancelFunc
	// HubWg represents the hub's waitgroup.
	HubWg *sync.WaitGroup
}

type Client

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

Client represents a client connection.

func NewClient

func NewClient(conn net.Conn, addr *net.TCPAddr, cCfg *ClientConfig) (*Client, error)

NewClient creates client connection instance.

type ClientConfig

type ClientConfig struct {
	// ActiveNet represents the active network being mined on.
	ActiveNet *chaincfg.Params
	// DB represents the pool database.
	DB *bolt.DB
	// SoloPool represents the solo pool mining mode.
	SoloPool bool
	// Blake256Pad represents the extra padding needed for work
	// submissions over the getwork RPC.
	Blake256Pad []byte
	// NonceIterations returns the possible header nonce iterations.
	NonceIterations float64
	// Miner returns the endpoint miner type.
	FetchMiner func() string
	// DifficultyInfo represents the difficulty info for the client.
	DifficultyInfo *DifficultyInfo
	// EndpointWg is the waitgroup of the client's endpoint.
	EndpointWg *sync.WaitGroup
	// RemoveClient removes the client from the pool.
	RemoveClient func(*Client)
	// SubmitWork sends solved block data to the consensus daemon.
	SubmitWork func(*string) (bool, error)
	// FetchCurrentWork returns the current work of the pool.
	FetchCurrentWork func() string
	// WithinLimit returns if the client is still within its request limits.
	WithinLimit func(string, int) bool
	// HashCalcThreshold represents the minimum operating time in seconds
	// before a client's hash rate is calculated.
	HashCalcThreshold uint32
}

type ClientInfo

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

ClientInfo represents client miner information.

type DifficultyInfo

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

DifficultyInfo represents the difficulty related info for a mining client.

type DifficultySet

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

DifficultySet represents generated pool difficulties for supported miners.

func NewDifficultySet

func NewDifficultySet(net *chaincfg.Params, powLimit *big.Rat, maxGenTime *big.Int) (*DifficultySet, error)

NewDifficultySet generates difficulty data for all supported mining clients.

type Endpoint

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

Endpoint represents a stratum endpoint.

func NewEndpoint

func NewEndpoint(eCfg *EndpointConfig, diffInfo *DifficultyInfo, port uint32, miner string) (*Endpoint, error)

NewEndpoint creates an new miner endpoint.

type EndpointConfig

type EndpointConfig struct {
	// ActiveNet represents the active network being mined on.
	ActiveNet *chaincfg.Params
	// DB represents the pool database.
	DB *bolt.DB
	// SoloPool represents the solo pool mining mode.
	SoloPool bool
	// Blake256Pad represents the extra padding needed for work
	// submissions over the getwork RPC.
	Blake256Pad []byte
	// NonceIterations returns the possible header nonce iterations.
	NonceIterations float64
	// MaxConnectionsPerHost represents the maximum number of connections
	// allowed per host.
	MaxConnectionsPerHost uint32
	// HubWg represents the hub's waitgroup.
	HubWg *sync.WaitGroup
	// SubmitWork sends solved block data to the consensus daemon.
	SubmitWork func(*string) (bool, error)
	// FetchCurrentWork returns the current work of the pool.
	FetchCurrentWork func() string
	// WithinLimit returns if a client is within its request limits.
	WithinLimit func(string, int) bool
	// AddConnection records a new client connection.
	AddConnection func(string)
	// RemoveConnection removes a client connection.
	RemoveConnection func(string)
	// FetchHostConnections returns the host connection for the provided host.
	FetchHostConnections func(string) uint32
}

type Error

type Error struct {
	ErrorCode   ErrorCode
	Description string
	Err         error
}

Error extends the base error type by adding an error description and an error code.

The caller can use type assertions to determine if an error is an Error and access the ErrorCode field to ascertain the specific reason for the failure.

func MakeError

func MakeError(c ErrorCode, desc string, err error) Error

MakeError creates an Error given a set of arguments.

func (Error) Error

func (e Error) Error() string

Error satisfies the error interface and prints human-readable errors.

type ErrorCode

type ErrorCode int

ErrorCode identifies a kind of error.

const (
	// ErrValueNotFound indicates a key does not map to any value.
	ErrValueNotFound ErrorCode = iota

	// ErrValueNotFound indicates a bucket key does not map to a bucket.
	ErrBucketNotFound

	// ErrBucketCreate indicates bucket creation failed.
	ErrBucketCreate

	// ErrDBOpen indicates database open error.
	ErrDBOpen

	// ErrWorkExists indicates an already existing work.
	ErrWorkExists

	// ErrWorkNotFound indicates non-existent work.
	ErrWorkNotFound

	// ErrWrongInputLength indicates an incorrect input size.
	ErrWrongInputLength

	// ErrDifficultyNotFound indicates a non-existent miner pool difficulty.
	ErrDifficultyNotFound

	// ErrCalcPoolTarget indicates a pool target calculation error.
	ErrCalcPoolTarget

	// ErrParse indicates a message parsing error.
	ErrParse

	// ErrDecode indicates a decode error.
	ErrDecode

	// ErrNotSupported indicates not supported functionality.
	ErrNotSupported

	// ErrDivideByZero indicates a division by zero error.
	ErrDivideByZero

	// ErrDBUpgrade indicates a database upgrade error.
	ErrDBUpgrade

	// ErrOther indicates a miscellenious error.
	ErrOther
)

These constants are used to identify a specific error.

func (ErrorCode) String

func (e ErrorCode) String() string

String returns the ErrorCode as a human-readable name.

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(cancel context.CancelFunc, hcfg *HubConfig) (*Hub, error)

NewHub initializes the mining pool hub.

func (*Hub) AccountExists

func (h *Hub) AccountExists(accountID string) bool

AccountExists checks if the provided account id references a pool account.

func (*Hub) AddPaymentRequest

func (h *Hub) AddPaymentRequest(addr string) error

AddPaymentRequest creates a payment request for the provided address.

func (*Hub) BackupDB

func (h *Hub) BackupDB(w http.ResponseWriter) error

BackupDB streams a backup of the database over an http response.

func (*Hub) CSRFSecret

func (h *Hub) CSRFSecret() ([]byte, error)

CSRFSecret fetches a persisted secret or generates a new one.

func (*Hub) CloseListeners

func (h *Hub) CloseListeners()

CloseListeners terminates listeners created by endpoints of the hub. This should only be used in the pool's shutdown process the hub is not running.

func (*Hub) Connect

func (h *Hub) Connect() error

Connect establishes connections with the consensus daemon and the wallet.

func (*Hub) FetchAccountClientInfo

func (h *Hub) FetchAccountClientInfo(accountID string) []*ClientInfo

FetchAccountClientInfo returns all clients belonging to the provided account id.

func (*Hub) FetchClientInfo

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

FetchClientInfo returns connection details about all pool clients.

func (*Hub) FetchLastPaymentHeight

func (h *Hub) FetchLastPaymentHeight() uint32

FetchLastPaymentheight returns the last payment height of the pool.

func (*Hub) FetchLastWorkHeight

func (h *Hub) FetchLastWorkHeight() uint32

FetchLastWorkHeight returns the last work height of the pool.

func (*Hub) FetchMinedWork

func (h *Hub) FetchMinedWork() ([]*AcceptedWork, error)

FetchMinedWork returns the last ten mined blocks by the pool.

func (*Hub) FetchMinedWorkByAccount

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

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

func (*Hub) FetchPaymentsForAccount

func (h *Hub) FetchPaymentsForAccount(id string) ([]*Payment, error)

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

func (*Hub) FetchPoolHashRate

func (h *Hub) FetchPoolHashRate() (*big.Rat, map[string][]*ClientInfo)

FetchPoolHashRate returns the hash rate of the pool.

func (*Hub) FetchWorkQuotas

func (h *Hub) FetchWorkQuotas() ([]*Quota, error)

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

func (*Hub) HasClients

func (h *Hub) HasClients() bool

HasClients asserts the mining pool has clients.

func (*Hub) Listen

func (h *Hub) Listen() error

Listen creates listeners for all supported pool clients.

func (*Hub) PublishTransaction

func (h *Hub) PublishTransaction(payouts map[dcrutil.Address]dcrutil.Amount, targetAmt dcrutil.Amount) (string, 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) WithinLimit

func (h *Hub) WithinLimit(ip string, clientType int) bool

WithinLimit returns if a client is within its request limits.

type HubConfig

type HubConfig struct {
	ActiveNet             *chaincfg.Params
	DB                    *bolt.DB
	DcrdRPCCfg            *rpcclient.ConnConfig
	PoolFee               float64
	MaxTxFeeReserve       dcrutil.Amount
	MaxGenTime            uint64
	WalletRPCCertFile     string
	WalletGRPCHost        string
	PaymentMethod         string
	LastNPeriod           uint32
	WalletPass            string
	MinPayment            dcrutil.Amount
	SoloPool              bool
	PoolFeeAddrs          []dcrutil.Address
	BackupPass            string
	Secret                string
	NonceIterations       float64
	MinerPorts            map[string]uint32
	MaxConnectionsPerHost uint32
}

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 is not supported for jobs.

type Message

type Message interface {
	MessageType() int
}

Message defines a message interface.

func IdentifyMessage

func IdentifyMessage(data []byte) (Message, int, 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 Payment

type Payment struct {
	Account           string         `json:"account"`
	EstimatedMaturity uint32         `json:"estimatedmaturity"`
	Height            uint32         `json:"height"`
	Amount            dcrutil.Amount `json:"amount"`
	CreatedOn         int64          `json:"createdon"`
	PaidOnHeight      uint32         `json:"paidonheight"`
	TransactionID     string         `json:"transactionid"`
}

Payment represents an outstanding payment for a pool account.

func CalculatePayments

func CalculatePayments(percentages map[string]*big.Rat, total dcrutil.Amount,
	poolFee float64, height uint32, estMaturity uint32) ([]*Payment, error)

CalculatePayments calculates the payments due participating accounts.

func GetPayment

func GetPayment(db *bolt.DB, id []byte) (*Payment, error)

GetPayment fetches the payment referenced by the provided id.

func NewPayment

func NewPayment(account string, amount dcrutil.Amount, height uint32, estMaturity uint32) *Payment

NewPayment creates a payment instance.

func (*Payment) Create

func (pmt *Payment) Create(db *bolt.DB) error

Create persists a payment to the database.

func (*Payment) Delete

func (pmt *Payment) Delete(db *bolt.DB) error

Delete purges the referenced pending payment from the database.

func (*Payment) Update

func (pmt *Payment) Update(db *bolt.DB) error

Update persists the updated payment to the database.

type PaymentBundle

type PaymentBundle struct {
	Account  string
	Payments []*Payment
}

PaymentBundle is a convenience type for grouping payments for an account.

func (*PaymentBundle) ArchivePayments

func (bundle *PaymentBundle) ArchivePayments(db *bolt.DB) error

ArchivePayments removes all payments included in the payment bundle from the payment bucket and archives them.

func (*PaymentBundle) Total

func (bundle *PaymentBundle) Total() dcrutil.Amount

Total returns the sum of all payments amount for the account.

func (*PaymentBundle) UpdateAsPaid

func (bundle *PaymentBundle) UpdateAsPaid(db *bolt.DB, height uint32, txid string)

UpdateAsPaid updates all associated payments referenced by a payment bundle as paid.

type PaymentMgr

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

PaymentMgr handles generating shares and paying out dividends to participating accounts.

func NewPaymentMgr

func NewPaymentMgr(pCfg *PaymentMgrConfig) (*PaymentMgr, error)

NewPaymentMgr creates a new payment manager.

func (*PaymentMgr) PPLNSSharePercentages

func (pm *PaymentMgr) PPLNSSharePercentages() (map[string]*big.Rat, error)

PPLNSSharePercentages calculates the current mining reward percentages due pool accounts based on work performed measured by the PPLNS payment scheme.

func (*PaymentMgr) PPSSharePercentages

func (pm *PaymentMgr) PPSSharePercentages() (map[string]*big.Rat, error)

PPLNSSharePercentages calculates the current mining reward percentages due participating pool accounts based on work performed measured by the PPS payment scheme.

type PaymentMgrConfig

type PaymentMgrConfig struct {
	// DB represents the pool database.
	DB *bolt.DB
	// ActiveNet represents the network being mined on.
	ActiveNet *chaincfg.Params
	// PoolFee represents the fee charged to participating accounts of the pool.
	PoolFee float64
	// LastNPeriod represents the period, in seconds, to source shares from
	// with the PPLNS payment scheme.
	LastNPeriod uint32
	// SoloPool represents the solo pool mining mode.
	SoloPool bool
	// PaymentMethod represents the payment scheme of the pool.
	PaymentMethod string
	// MinPayment represents the minimum payment eligible for processing by the
	// pool.
	MinPayment dcrutil.Amount
	// PoolFeeAddrs represents the pool fee addresses of the pool.
	PoolFeeAddrs []dcrutil.Address
	// MaxTxFeeReserve represents the maximum value the tx free reserve can be.
	MaxTxFeeReserve dcrutil.Amount
	// PublishTransaction generates a transaction from the provided payouts
	// and publishes it.
	PublishTransaction func(map[dcrutil.Address]dcrutil.Amount, dcrutil.Amount) (string, error)
}

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 keeps connected clients within their allocated request rates.

func NewRateLimiter

func NewRateLimiter() *RateLimiter

NewRateLimiter initializes a rate limiter.

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.Rat) *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() int

MessageType returns the request message type.

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, extraNonce2Size int, err *StratumError) *Response

SubscribeResponse creates a mining.subscribe response.

func (*Response) MessageType

func (req *Response) MessageType() int

MessageType returns the response message type.

type Share

type Share struct {
	Account   string   `json:"account"`
	Weight    *big.Rat `json:"weight"`
	CreatedOn int64    `json:"createdOn"`
}

Share represents verifiable work performed by a pool client.

func NewShare

func NewShare(account string, weight *big.Rat) *Share

NewShare creates a share with the provided account and weight.

func PPLNSEligibleShares

func PPLNSEligibleShares(db *bolt.DB, min []byte) ([]*Share, error)

PPLNSEligibleShares fetches all shares keyed greater than the provided minimum.

func PPSEligibleShares

func PPSEligibleShares(db *bolt.DB, min []byte, max []byte) ([]*Share, error)

PPSEligibleShares fetches all shares within the provided inclusive bounds.

func (*Share) Create

func (s *Share) Create(db *bolt.DB) error

Create persists a share to the database.

func (*Share) Delete

func (s *Share) Delete(db *bolt.DB) error

Delete is not supported for shares.

func (*Share) Update

func (s *Share) Update(db *bolt.DB) error

Update is not supported for shares.

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.

Jump to

Keyboard shortcuts

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