pool

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2021 License: ISC Imports: 45 Imported by: 1

Documentation

Index

Constants

View Source
const (
	CPU               = "cpu"
	InnosiliconD9     = "innosilicond9"
	AntminerDR3       = "antminerdr3"
	AntminerDR5       = "antminerdr5"
	WhatsminerD1      = "whatsminerd1"
	ObeliskDCR1       = "obeliskdcr1"
	NiceHashValidator = "nicehash"
)

Supported mining clients.

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 is the reason given when a work notification is generated
	// because there is a new chain tip.
	NewParent = "newparent"
	// NewVotes is the reason given when a work notification is generated
	// because new votes were received.
	NewVotes = "newvotes"
	// NewTxns is the reason given when a work notification is generated
	// because new transactions were received.
	NewTxns = "newtxns"
)
View Source
const (
	GUIClient = iota
	PoolClient
)

Client types.

View Source
const (
	UnknownMessage = iota
	RequestMessage
	ResponseMessage
	NotificationMessage
)

Message types.

View Source
const (
	Authorize           = "mining.authorize"
	Subscribe           = "mining.subscribe"
	ExtraNonceSubscribe = "mining.extranonce.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 (
	// PPS represents the pay per share payment method.
	PPS = "pps"

	// PPLNS represents the pay per last n shares payment method.
	PPLNS = "pplns"
)
View Source
const (

	// BoltDBVersion is the latest version of the bolt 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).
	BoltDBVersion = paymentUUIDVersion
)
View Source
const (
	ExtraNonce2Size = 4
)

Stratum constants.

Variables

View Source
var (

	// PoolFeesK is the key used to track pool fee payouts.
	PoolFeesK = "fees"
	// BoltBackupFile is the database backup file name.
	BoltBackupFile = "backup.kv"
)
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 ShareWeights = map[string]*big.Rat{
	CPU:           new(big.Rat).SetFloat64(1.0),
	ObeliskDCR1:   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) string

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

func AccountID

func AccountID(address string) string

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

func DifficultyToTarget

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

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 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 ParseExtraNonceSubscribeRequest

func ParseExtraNonceSubscribeRequest(req *Request) error

ParseExtraNonceSubscribeRequest ensures the provided extranonce subscribe request is valid.

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, 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 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 NewAcceptedWork

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

NewAcceptedWork creates an accepted 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 NewAccount

func NewAccount(address string) *Account

NewAccount creates a new account.

type BoltDB

type BoltDB struct {
	DB *bolt.DB
}

BoltDB is a wrapper around bolt.DB which implements the Database interface.

func InitBoltDB

func InitBoltDB(dbFile string) (*BoltDB, error)

InitBoltDB handles the creation and upgrading of a bolt database.

func (*BoltDB) ArchivePayment

func (db *BoltDB) ArchivePayment(pmt *Payment) error

ArchivePayment removes the associated payment from active payments and archives it.

func (*BoltDB) Backup

func (db *BoltDB) Backup(backupFileName string) error

Backup saves a copy of the db to file. The file will be saved in the same directory as the current db file.

func (*BoltDB) Close

func (db *BoltDB) Close() error

Close closes the Bolt database.

func (*BoltDB) PersistPayment

func (db *BoltDB) PersistPayment(pmt *Payment) error

PersistPayment saves a payment to the database.

func (*BoltDB) PersistShare

func (db *BoltDB) PersistShare(s *Share) error

PersistShare saves a share to the database.

type CacheUpdateEvent

type CacheUpdateEvent int

CacheUpdateEvent represents the a cache update event message.

const (
	// Confirmed indicates an accepted work has been updated as
	// confirmed mined.
	Confirmed CacheUpdateEvent = iota

	// Unconfirmed indicates a previously confimed mined work has been
	// updated to unconfirmed due to a reorg.
	Unconfirmed

	// ClaimedShare indicates work quotas for participating clients have
	// been updated.
	ClaimedShare

	// DividendsPaid indicates dividends due participating miners have been
	// paid.
	DividendsPaid
)

Constants for the type of template regeneration event messages.

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 {

	// SoloPool represents the solo pool mining mode.
	SoloPool bool
	// ProcessPayments relays payment signals for processing.
	ProcessPayments func(msg *paymentMsg)
	// GeneratePayments creates payments for participating accounts in pool
	// mining mode based on the configured payment scheme.
	GeneratePayments func(uint32, *PaymentSource, dcrutil.Amount, int64) error
	// GetBlock fetches the block associated with the provided block hash.
	GetBlock func(context.Context, *chainhash.Hash) (*wire.MsgBlock, error)
	// GetBlockConfirmations fetches the block confirmations with the provided
	// block hash.
	GetBlockConfirmations func(context.Context, *chainhash.Hash) (int64, error)
	// Cancel represents the pool's context cancellation function.
	Cancel context.CancelFunc
	// SignalCache sends the provided cache update event to the gui cache.
	SignalCache func(event CacheUpdateEvent)
	// HubWg represents the hub's waitgroup.
	HubWg *sync.WaitGroup
	// contains filtered or unexported fields
}

ChainStateConfig contains all of the configuration values which should be provided when creating a new instance of ChainState.

type Client

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

Client represents a client connection.

func NewClient

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

NewClient creates client connection instance.

func (*Client) FetchAccountID

func (c *Client) FetchAccountID() string

FetchAccountID gets the client's account ID.

func (*Client) FetchHashRate

func (c *Client) FetchHashRate() *big.Rat

FetchHashRate gets the client's hash rate.

func (*Client) FetchIPAddr

func (c *Client) FetchIPAddr() string

FetchIPAddr gets the client's IP address.

func (*Client) FetchMinerType

func (c *Client) FetchMinerType() string

FetchMinerType gets the client's miner type.

type ClientConfig

type ClientConfig struct {
	// ActiveNet represents the active network being mined on.
	ActiveNet *chaincfg.Params

	// 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
	// FetchMinerDifficulty returns the difficulty information for the
	// provided miner, if it exists.
	FetchMinerDifficulty func(string) (*DifficultyInfo, error)
	// Disconnect relays a disconnection signal to the client endpoint.
	Disconnect func()
	// RemoveClient removes the client from the pool.
	RemoveClient func(*Client)
	// SubmitWork sends solved block data to the consensus daemon.
	SubmitWork func(context.Context, *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 before a
	// client's hash rate is calculated.
	HashCalcThreshold time.Duration
	// MaxGenTime represents the share creation target time for the pool.
	MaxGenTime time.Duration
	// ClientTimeout represents the connection read/write timeout.
	ClientTimeout time.Duration
	// SignalCache sends the provided cache update event to the gui cache.
	SignalCache func(event CacheUpdateEvent)
	// MonitorCycle represents the time monitoring a mining client to access
	// possible upgrades if needed.
	MonitorCycle time.Duration
	// MaxUpgradeTries represents the maximum number of consecutive miner
	// monitoring and upgrade tries.
	MaxUpgradeTries uint32
	// RollWorkCycle represents the tick interval for asserting the need for
	// timestamp-rolled work.
	RollWorkCycle time.Duration
	// contains filtered or unexported fields
}

ClientConfig contains all of the configuration values which should be provided when creating a new instance of Client.

type Database

type Database interface {
	Backup(fileName string) error
	Close() error

	PersistPayment(payment *Payment) error

	ArchivePayment(payment *Payment) error

	// Share
	PersistShare(share *Share) error
	// contains filtered or unexported methods
}

Database describes all of the functionality needed by a dcrpool database implementation.

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 time.Duration) *DifficultySet

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, listenAddr 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

	// 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
	// MaxGenTime represents the share creation target time for the pool.
	MaxGenTime time.Duration
	// HubWg represents the hub's waitgroup.
	HubWg *sync.WaitGroup
	// FetchMinerDifficulty returns the difficulty information for the
	// provided miner if it exists.
	FetchMinerDifficulty func(string) (*DifficultyInfo, error)
	// SubmitWork sends solved block data to the consensus daemon.
	SubmitWork func(context.Context, *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
	// SignalCache sends the provided cache update event to the gui cache.
	SignalCache func(event CacheUpdateEvent)
	// MonitorCycle represents the time monitoring a mining client to access
	// possible upgrades if needed.
	MonitorCycle time.Duration
	// MaxUpgradeTries represents the maximum number of consecutive miner
	// monitoring and upgrade tries.
	MaxUpgradeTries uint32
	// ClientTimeout represents the read/write timeout for the client.
	ClientTimeout time.Duration
	// contains filtered or unexported fields
}

EndpointConfig contains all of the configuration values which should be provided when creating a new instance of Endpoint.

type HashData

type HashData struct {
	UUID      string   `json:"uuid"`
	AccountID string   `json:"accountid"`
	Miner     string   `json:"miner"`
	IP        string   `json:"ip"`
	HashRate  *big.Rat `json:"hashrate"`
	UpdatedOn int64    `json:"updatedon"`
}

HashData represents client identification and hashrate information for a mining client.

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) CSRFSecret

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

CSRFSecret fetches a persisted secret or generates a new one.

func (*Hub) Connect

func (h *Hub) Connect(ctx context.Context) error

Connect establishes a connection to the mining node and a wallet connection if the pool is a publicly avialable one.

func (*Hub) FetchArchivedPayments

func (h *Hub) FetchArchivedPayments() ([]*Payment, error)

FetchArchivedPayments fetches all paid payments.

func (*Hub) FetchCacheChannel

func (h *Hub) FetchCacheChannel() chan CacheUpdateEvent

FetchCacheChannel returns the gui cache signal chanel.

func (*Hub) FetchHashData

func (h *Hub) FetchHashData() (map[string][]*HashData, error)

FetchHashData returns all hash data from connected pool clients which have been updated in the last five minutes.

func (*Hub) FetchLastPaymentInfo

func (h *Hub) FetchLastPaymentInfo() (uint32, int64, int64, error)

FetchLastPaymentInfo returns the height, paid on time, and created on time, for the last payment made by 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 work data associated with all blocks mined by the pool regardless of whether they are confirmed or not.

List is ordered, most recent comes first.

func (*Hub) FetchPendingPayments

func (h *Hub) FetchPendingPayments() ([]*Payment, error)

FetchPendingPayments fetches all unpaid payments.

func (*Hub) FetchWork

func (h *Hub) FetchWork(ctx context.Context) error

FetchWork queries the mining node for work. This should be called immediately the pool starts to avoid waiting for a work notification.

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) HTTPBackupDB

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

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

func (*Hub) HasClients

func (h *Hub) HasClients() bool

HasClients asserts the mining pool has clients.

func (*Hub) Run

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

Run handles the process lifecycles of the pool hub.

func (*Hub) SignalCache

func (h *Hub) SignalCache(event CacheUpdateEvent)

SignalCache sends the provided cache update event to the gui cache.

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 represents the active network being mined on.
	ActiveNet *chaincfg.Params
	// DB represents the pool database.
	DB Database
	// NodeRPCConfig represents the mining node's RPC configuration details.
	NodeRPCConfig *rpcclient.ConnConfig
	// WalletRPCCert represents the wallet's RPC certificate.
	WalletRPCCert string
	// WalletTLSCert represents the wallet client's TLS certificate.
	WalletTLSCert string
	// WalletTLSKey represents the wallet client's TLS key file.
	WalletTLSKey string
	// WalletGRPCHost represents the ip:port establish a GRPC connection for
	// the wallet.
	WalletGRPCHost string
	// PoolFee represents the fee charged to participating accounts of the pool.
	PoolFee float64
	// MaxGenTime represents the share creation target time for the pool.
	MaxGenTime time.Duration
	// PaymentMethod represents the payment scheme of the pool.
	PaymentMethod string
	// LastNPeriod represents the period to source shares from when using the
	// PPLNS payment scheme.
	LastNPeriod time.Duration
	// WalletPass represents the passphrase to unlock the wallet with.
	WalletPass string
	// SoloPool represents the solo pool mining mode.
	SoloPool bool
	// PoolFeeAddrs represents the pool fee addresses of the pool.
	PoolFeeAddrs []dcrutil.Address
	// AdminPass represents the admin password.
	AdminPass string
	// NonceIterations returns the possible header nonce iterations.
	NonceIterations float64
	// MinerListen represents the listening address for miner connections.
	MinerListen string
	// MaxConnectionsPerHost represents the maximum number of connections
	// allowed per host.
	MaxConnectionsPerHost uint32
	// WalletAccount represents the wallet account to process payments from.
	WalletAccount uint32
	// CoinbaseConfTimeout is the duration to wait for coinbase confirmations
	// when generating a payout transaction.
	CoinbaseConfTimeout time.Duration
	// MonitorCycle represents the time monitoring a mining client to access
	// possible upgrades if needed.
	MonitorCycle time.Duration
	// MaxUpgradeTries represents the maximum number of consecutive miner
	// monitoring and upgrade tries.
	MaxUpgradeTries uint32
	// ClientTimeout represents the read/write timeout for the client.
	ClientTimeout time.Duration
}

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 NewJob

func NewJob(header string, height uint32) *Job

NewJob creates a job instance.

type Message

type Message interface {
	MessageType() int
	String() string
}

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 NodeConnection

type NodeConnection interface {
	GetTxOut(context.Context, *chainhash.Hash, uint32, bool) (*chainjson.GetTxOutResult, error)
	CreateRawTransaction(context.Context, []chainjson.TransactionInput, map[dcrutil.Address]dcrutil.Amount, *int64, *int64) (*wire.MsgTx, error)
	GetWorkSubmit(context.Context, string) (bool, error)
	GetWork(context.Context) (*chainjson.GetWorkResult, error)
	GetBlockVerbose(context.Context, *chainhash.Hash, bool) (*chainjson.GetBlockVerboseResult, error)
	GetBlock(context.Context, *chainhash.Hash) (*wire.MsgBlock, error)
	NotifyWork(context.Context) error
	NotifyBlocks(context.Context) error
	Shutdown()
}

NodeConnection defines the functionality needed by a mining node connection for the pool.

type Payment

type Payment struct {
	UUID              string         `json:"uuid"`
	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"`

	// The source could be empty if the payment was
	// created before the version 3 db upgrade.
	Source *PaymentSource `json:"source"`
}

Payment represents value paid to a pool account or collected fees.

func NewPayment

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

NewPayment creates a payment instance.

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(workCreatedOn int64) (map[string]*big.Rat, error)

PPSSharePercentages 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 {

	// 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 to source shares from when using the
	// PPLNS payment scheme.
	LastNPeriod time.Duration
	// SoloPool represents the solo pool mining mode.
	SoloPool bool
	// PaymentMethod represents the payment scheme of the pool.
	PaymentMethod string
	// PoolFeeAddrs represents the pool fee addresses of the pool.
	PoolFeeAddrs []dcrutil.Address
	// WalletAccount represents the wallet account to process payments from.
	WalletAccount uint32
	// WalletPass represents the passphrase to unlock the wallet with.
	WalletPass string
	// GetBlockConfirmations returns the number of block confirmations for the
	// provided block hash.
	GetBlockConfirmations func(context.Context, *chainhash.Hash) (int64, error)
	// FetchTxCreator returns a transaction creator that allows coinbase lookups
	// and payment transaction creation.
	FetchTxCreator func() TxCreator
	// FetchTxBroadcaster returns a transaction broadcaster that allows signing
	// and publishing of transactions.
	FetchTxBroadcaster func() TxBroadcaster
	// CoinbaseConfTimeout is the duration to wait for coinbase confirmations
	// when generating a payout transaction.
	CoinbaseConfTimeout time.Duration
	// SignalCache sends the provided cache update event to the gui cache.
	SignalCache func(event CacheUpdateEvent)
	// HubWg represents the hub's waitgroup.
	HubWg *sync.WaitGroup
	// contains filtered or unexported fields
}

PaymentMgrConfig contains all of the configuration values which should be provided when creating a new instance of PaymentMgr.

type PaymentSource

type PaymentSource struct {
	BlockHash string `json:"blockhash"`
	Coinbase  string `json:"coinbase"`
}

PaymentSource represents the payment's source of funds.

type PostgresDB

type PostgresDB struct {
	DB *sql.DB
}

PostgresDB is a wrapper around sql.DB which implements the Database interface.

func InitPostgresDB

func InitPostgresDB(host string, port uint32, user, pass, dbName string, purgeDB bool) (*PostgresDB, error)

InitPostgresDB connects to the specified database and creates all tables required by dcrpool.

func (*PostgresDB) ArchivePayment

func (db *PostgresDB) ArchivePayment(p *Payment) error

ArchivePayment removes the associated payment from active payments and archives it.

func (*PostgresDB) Backup

func (db *PostgresDB) Backup(fileName string) error

Backup is not implemented for postgres database.

func (*PostgresDB) Close

func (db *PostgresDB) Close() error

Close closes the postgres database connection.

func (*PostgresDB) PersistPayment

func (db *PostgresDB) PersistPayment(p *Payment) error

PersistPayment saves a payment to the database.

func (*PostgresDB) PersistShare

func (db *PostgresDB) PersistShare(share *Share) error

PersistShare saves a share to the database. Returns an error if a share already exists with the same ID.

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, 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.

func (*Request) String

func (req *Request) String() string

String returns the string representation of 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 ExtraNonceSubscribeResponse

func ExtraNonceSubscribeResponse(id uint64) *Response

ExtraNonceSubscribeResponse creates a mining.extranonce.subscribe 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.

func (*Response) String

func (req *Response) String() string

String returns the string representation of the response message type.

type Share

type Share struct {
	UUID      string   `json:"uuid"`
	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.

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, err error) *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.

func (*StratumError) MarshalJSON

func (s *StratumError) MarshalJSON() ([]byte, error)

MarshalJSON marshals the stratum error into valid JSON.

func (*StratumError) String

func (s *StratumError) String() string

String returns a stringified representation of the stratum error.

func (*StratumError) UnmarshalJSON

func (s *StratumError) UnmarshalJSON(p []byte) error

UnmarshalJSON unmarshals the provided JSON bytes into a stratum error.

type TxBroadcaster

type TxBroadcaster interface {
	// SignTransaction signs transaction inputs, unlocking them for use.
	SignTransaction(context.Context, *walletrpc.SignTransactionRequest, ...grpc.CallOption) (*walletrpc.SignTransactionResponse, error)
	// PublishTransaction broadcasts the transaction unto the network.
	PublishTransaction(context.Context, *walletrpc.PublishTransactionRequest, ...grpc.CallOption) (*walletrpc.PublishTransactionResponse, error)
	// GetTransaction fetches transaction details for the provided transaction.
	GetTransaction(context.Context, *walletrpc.GetTransactionRequest, ...grpc.CallOption) (*walletrpc.GetTransactionResponse, error)
	// Rescan requests a wallet utxo rescan.
	Rescan(ctx context.Context, in *walletrpc.RescanRequest, opts ...grpc.CallOption) (walletrpc.WalletService_RescanClient, error)
}

TxBroadcaster defines the functionality needed by a transaction broadcaster for the pool.

type TxCreator

type TxCreator interface {
	// GetTxOut fetches the output referenced by the provided txHash and index.
	GetTxOut(context.Context, *chainhash.Hash, uint32, bool) (*chainjson.GetTxOutResult, error)
	// CreateRawTransaction generates a transaction from the provided
	// inputs and payouts.
	CreateRawTransaction(context.Context, []chainjson.TransactionInput, map[dcrutil.Address]dcrutil.Amount, *int64, *int64) (*wire.MsgTx, error)
	// GetBlock fetches the block associated with the provided block hash.
	GetBlock(ctx context.Context, blockHash *chainhash.Hash) (*wire.MsgBlock, error)
}

TxCreator defines the functionality needed by a transaction creator for the pool.

type WalletConnection

WalletConnection defines the functionality needed by a wallet grpc connection for the pool.

Jump to

Keyboard shortcuts

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