pool

package
v0.1.34 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package pool implements the open Bitcoin 09 remote-solo mining protocol.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnknownJob          = errors.New("unknown mining job")
	ErrExpiredJob          = errors.New("mining job expired")
	ErrStaleJob            = errors.New("mining job is stale")
	ErrDuplicateSubmission = errors.New("duplicate nonce submission")
	ErrLowDifficulty       = errors.New("nonce does not meet network target")
	ErrBlockRejected       = errors.New("mined block rejected")
)
View Source
var (
	ErrPPLNSAddressLimit   = errors.New("PPLNS payout-address limit reached")
	ErrPPLNSDuplicateShare = errors.New("PPLNS share was already accepted")
	ErrPPLNSStateLocked    = errors.New("PPLNS state is already locked by another process")
	ErrPPLNSClosed         = errors.New("PPLNS window is closed")
)
View Source
var (
	ErrLowShareDifficulty   = errors.New("nonce does not meet PPLNS share target")
	ErrPPLNSSubmissionLimit = errors.New("PPLNS job submission limit reached")
)

Functions

func NewHTTPHandler

func NewHTTPHandler(coordinator *Coordinator, config HTTPConfig) http.Handler

NewHTTPHandler returns the versioned nonce-only remote mining API.

func NewHTTPServer

func NewHTTPServer(address string, handler http.Handler) *http.Server

NewHTTPServer applies finite network timeouts suitable for a public API.

func NewMiningHTTPHandler added in v0.1.28

func NewMiningHTTPHandler(coordinator *Coordinator, pplns *PPLNSCoordinator, config HTTPConfig) http.Handler

NewMiningHTTPHandler serves v1 remote-solo and v2 PPLNS routes without changing the v1 protocol or accepting path aliases.

func ParsePoolWork added in v0.1.28

func ParsePoolWork(work PoolWork, params *core.Params) (core.Header, *big.Int, *big.Int, error)

ParsePoolWork validates and decodes a PPLNS job and its two targets.

func ParseWork

func ParseWork(work Work, params *core.Params) (core.Header, *big.Int, error)

ParseWork validates and decodes a coordinator-owned work item.

Types

type ClientEvent added in v0.1.25

type ClientEvent struct {
	Type          ClientEventType
	At            time.Time
	JobID         string
	Height        int64
	Hashes        uint64
	Hashrate      float64
	Elapsed       time.Duration
	Final         bool
	BlockID       string
	Status        string
	ShareHash     string
	ShareSequence uint64
	RetryIn       time.Duration
	Error         string
}

type ClientEventType added in v0.1.25

type ClientEventType string
const (
	ClientEventJob      ClientEventType = "job"
	ClientEventProgress ClientEventType = "progress"
	ClientEventAccepted ClientEventType = "accepted"
	ClientEventRetrying ClientEventType = "retrying"
)

type Coordinator

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

Coordinator owns canonical templates and accepts nonce-only submissions.

func NewCoordinator

func NewCoordinator(chain *core.Chain, config CoordinatorConfig) (*Coordinator, error)

func (*Coordinator) Issue

func (c *Coordinator) Issue(address, worker string) (Work, error)

Issue builds a short-lived canonical block template paying address.

func (*Coordinator) Submit

func (c *Coordinator) Submit(jobID string, nonce uint64) (SubmitResult, error)

Submit reconstructs a coordinator-owned job with nonce and accepts a valid network block through the normal chain-validation path.

type CoordinatorConfig

type CoordinatorConfig struct {
	JobTTL  time.Duration
	MaxJobs int
	Tag     string
	Now     func() time.Time
}

CoordinatorConfig bounds the in-memory remote-solo job service.

type HTTPConfig

type HTTPConfig struct {
	MaxBodyBytes                  int64
	WorkRequestsPerMinute         int
	SubmitsPerMinute              int
	PoolWorkRequestsPerMinute     int
	PoolSubmitsPerMinute          int
	PoolStatusRequestsPerMinute   int
	TrustProxyHeadersFromLoopback bool
	Now                           func() time.Time
}

HTTPConfig bounds requests to the public mining API.

type MineProgress added in v0.1.25

type MineProgress struct {
	Hashes   uint64
	Elapsed  time.Duration
	Hashrate float64
	Final    bool
	Found    bool
}

MineProgress is a low-frequency snapshot of one local nonce search. Hashrate is the session average for this work item, not an estimate from a single sample.

type MineResult

type MineResult struct {
	Found  bool
	Nonce  uint64
	Hashes uint64
	Hash   core.Hash32
}

MineResult records a locally discovered nonce and its proof-of-work hash.

func MinePoolShare added in v0.1.28

func MinePoolShare(ctx context.Context, work PoolWork, params *core.Params, workers int, startNonce uint64) (MineResult, error)

MinePoolShare searches from startNonce for one nonce meeting the advertised share target. A network-winning nonce also satisfies the share target.

func MinePoolShareWithProgress added in v0.1.28

func MinePoolShareWithProgress(
	ctx context.Context,
	work PoolWork,
	params *core.Params,
	workers int,
	startNonce uint64,
	interval time.Duration,
	callback func(MineProgress),
) (MineResult, error)

func MineWork

func MineWork(ctx context.Context, work Work, params *core.Params, workers int) (MineResult, error)

MineWork searches the nonce field of one coordinator-issued work item.

func MineWorkWithProgress added in v0.1.25

func MineWorkWithProgress(
	ctx context.Context,
	work Work,
	params *core.Params,
	workers int,
	interval time.Duration,
	callback func(MineProgress),
) (MineResult, error)

MineWorkWithProgress searches one coordinator-issued work item and reports snapshots outside the hashing goroutines. The callback is serialized and is never called from the nonce hot loop.

type PPLNSConfig added in v0.1.28

type PPLNSConfig struct {
	StatePath    string
	WindowShares int
	MaxAddresses int
}

PPLNSConfig fixes the bounded rolling window and its durable state path. Changing either bound requires an explicit state migration; existing state is never silently truncated or reinterpreted.

type PPLNSCoordinator added in v0.1.28

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

PPLNSCoordinator issues canonical direct-payout templates and accepts every verified share into a crash-durable rolling window.

func NewPPLNSCoordinator added in v0.1.28

func NewPPLNSCoordinator(chain *core.Chain, window *PPLNSWindow, config PPLNSCoordinatorConfig) (*PPLNSCoordinator, error)

func (*PPLNSCoordinator) Issue added in v0.1.28

func (c *PPLNSCoordinator) Issue(address, worker string) (PoolWork, error)

Issue builds a short-lived job. An empty window bootstraps to the requesting address; after the first share, the coinbase pays the frozen prior window.

func (*PPLNSCoordinator) Status added in v0.1.28

func (c *PPLNSCoordinator) Status() (PPLNSStatus, error)

func (*PPLNSCoordinator) Submit added in v0.1.28

func (c *PPLNSCoordinator) Submit(jobID string, nonce uint64) (PoolSubmitResult, error)

Submit verifies one nonce exactly once, persists qualifying work before acknowledging it, then submits network-winning work through consensus.

type PPLNSCoordinatorConfig added in v0.1.28

type PPLNSCoordinatorConfig struct {
	JobTTL                time.Duration
	MaxJobs               int
	MaxSubmissionsPerJob  int
	MaxReceipts           int
	ShareTargetMultiplier uint64
	Tag                   string
	Now                   func() time.Time
}

PPLNSCoordinatorConfig bounds the non-custodial pooled-mining service.

type PPLNSPayoutWeight added in v0.1.28

type PPLNSPayoutWeight struct {
	Address string `json:"address"`
	Shares  int    `json:"shares"`
	WorkHex string `json:"work_hex"`
}

type PPLNSRemoteClient added in v0.1.28

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

PPLNSRemoteClient verifies direct-payout jobs locally before mining them.

func NewPPLNSRemoteClient added in v0.1.28

func NewPPLNSRemoteClient(config RemoteClientConfig) (*PPLNSRemoteClient, error)

func (*PPLNSRemoteClient) RequestWork added in v0.1.28

func (c *PPLNSRemoteClient) RequestWork(ctx context.Context) (PoolWork, error)

func (*PPLNSRemoteClient) RunWithEvents added in v0.1.28

func (c *PPLNSRemoteClient) RunWithEvents(ctx context.Context, emit func(ClientEvent)) error

RunWithEvents continuously mines verified v2 jobs and reports every durable share receipt. A block receipt refreshes the template immediately.

func (*PPLNSRemoteClient) Status added in v0.1.28

func (*PPLNSRemoteClient) Submit added in v0.1.28

func (c *PPLNSRemoteClient) Submit(ctx context.Context, jobID string, nonce uint64) (PoolSubmitResult, error)

type PPLNSShare added in v0.1.28

type PPLNSShare struct {
	Sequence    uint64    `json:"sequence"`
	Address     string    `json:"address"`
	JobID       string    `json:"job_id"`
	Nonce       uint64    `json:"nonce"`
	ShareHash   string    `json:"share_hash"`
	ShareTarget string    `json:"share_target"`
	TipHash     string    `json:"tip_hash"`
	TipHeight   int64     `json:"tip_height"`
	AcceptedAt  time.Time `json:"accepted_at"`
}

PPLNSShare is one verified proof-of-work share. It deliberately excludes IP addresses and worker labels; those are not needed for payout accounting.

type PPLNSSnapshot added in v0.1.28

type PPLNSSnapshot struct {
	SchemaVersion int          `json:"schema_version"`
	Network       string       `json:"network"`
	WindowShares  int          `json:"window_shares"`
	MaxAddresses  int          `json:"max_addresses"`
	NextSequence  uint64       `json:"next_sequence"`
	Shares        []PPLNSShare `json:"shares"`
}

PPLNSSnapshot is a detached copy suitable for tests, status reporting, and deterministic payout construction.

type PPLNSStatus added in v0.1.28

type PPLNSStatus struct {
	SchemaVersion     int                 `json:"schema_version"`
	Network           string              `json:"network"`
	Mode              string              `json:"mode"`
	FeeBPS            int                 `json:"fee_bps"`
	TipHash           string              `json:"tip_hash"`
	TipHeight         int64               `json:"tip_height"`
	CoinbaseMaturity  int64               `json:"coinbase_maturity"`
	WindowShares      int                 `json:"window_shares"`
	MaxAddresses      int                 `json:"max_addresses"`
	CurrentShares     int                 `json:"current_shares"`
	DistinctAddresses int                 `json:"distinct_addresses"`
	NextSequence      uint64              `json:"next_sequence"`
	PPLNSStateHash    string              `json:"pplns_state_hash"`
	Weights           []PPLNSPayoutWeight `json:"weights"`
	Shares            []PPLNSShare        `json:"shares"`
}

PPLNSStatus exposes enough share data to independently reproduce the next direct-payout allocation. It contains no IP addresses or worker labels.

type PPLNSWindow added in v0.1.28

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

PPLNSWindow owns one process-exclusive, crash-durable rolling share window.

func NewPPLNSWindow added in v0.1.28

func NewPPLNSWindow(network string, config PPLNSConfig) (*PPLNSWindow, error)

func (*PPLNSWindow) Accept added in v0.1.28

func (w *PPLNSWindow) Accept(share PPLNSShare) (PPLNSShare, error)

Accept durably appends one verified share before acknowledging it. A failed write leaves the in-memory window byte-for-byte unchanged.

func (*PPLNSWindow) Close added in v0.1.28

func (w *PPLNSWindow) Close() error

func (*PPLNSWindow) Payouts added in v0.1.28

func (w *PPLNSWindow) Payouts(reward int64) ([]core.TxOut, error)

Payouts returns a canonical, exact-sum coinbase allocation. Each share is weighted by the expected work represented by its accepted target. Largest remainders receive indivisible leftover units with address bytes as the stable tie-breaker.

func (*PPLNSWindow) Snapshot added in v0.1.28

func (w *PPLNSWindow) Snapshot() PPLNSSnapshot

type PoolSubmitResult added in v0.1.28

type PoolSubmitResult struct {
	SchemaVersion int    `json:"schema_version"`
	Network       string `json:"network"`
	Status        string `json:"status"`
	ShareHash     string `json:"share_hash"`
	ShareSequence uint64 `json:"share_sequence"`
	BlockID       string `json:"block_id,omitempty"`
	Height        int64  `json:"height"`
}

PoolSubmitResult acknowledges either one durable share or a network block.

type PoolWork added in v0.1.28

type PoolWork struct {
	SchemaVersion        int                 `json:"schema_version"`
	Network              string              `json:"network"`
	Mode                 string              `json:"mode"`
	FeeBPS               int                 `json:"fee_bps"`
	JobID                string              `json:"job_id"`
	Height               int64               `json:"height"`
	HeaderHex            string              `json:"header_hex"`
	NetworkTargetHex     string              `json:"network_target_hex"`
	ShareTargetHex       string              `json:"share_target_hex"`
	ExpiresAt            time.Time           `json:"expires_at"`
	ArgonMemKiB          uint32              `json:"argon_mem_kib"`
	ArgonTime            uint32              `json:"argon_time"`
	WindowShares         int                 `json:"window_shares"`
	CurrentShares        int                 `json:"current_shares"`
	PPLNSStateHash       string              `json:"pplns_state_hash"`
	Window               PPLNSSnapshot       `json:"window"`
	PayoutBasis          string              `json:"payout_basis"`
	PayoutWeights        []PPLNSPayoutWeight `json:"payout_weights"`
	CoinbaseHex          string              `json:"coinbase_hex"`
	CoinbaseMerkleBranch []string            `json:"coinbase_merkle_branch"`
}

PoolWork is a PPLNS mining job. The share target is easier than or equal to the network target; both commit to the same coordinator-owned block header.

type RemoteAPIError

type RemoteAPIError struct {
	StatusCode int
	Code       string
}

func (*RemoteAPIError) Error

func (e *RemoteAPIError) Error() string

type RemoteClient

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

RemoteClient mines coordinator-owned jobs while keeping the payout address under the miner's control.

func NewRemoteClient

func NewRemoteClient(config RemoteClientConfig) (*RemoteClient, error)

func (*RemoteClient) MineOnce

MineOnce requests one job, searches it until solved or expired, and submits only a network-winning nonce.

func (*RemoteClient) RequestWork

func (c *RemoteClient) RequestWork(ctx context.Context) (Work, error)

func (*RemoteClient) Run

func (c *RemoteClient) Run(ctx context.Context, accepted func(MineResult, SubmitResult)) error

Run continuously refreshes jobs. Stale and expired jobs are normal and are replaced without terminating the miner.

func (*RemoteClient) RunWithEvents added in v0.1.25

func (c *RemoteClient) RunWithEvents(ctx context.Context, emit func(ClientEvent)) error

RunWithEvents continuously mines and emits observable state for interactive clients. Temporary transport and server failures are retried with bounded backoff; protocol and permanent client errors stop the session.

func (*RemoteClient) Submit

func (c *RemoteClient) Submit(ctx context.Context, jobID string, nonce uint64) (SubmitResult, error)

type RemoteClientConfig

type RemoteClientConfig struct {
	PoolURL           string
	Address           string
	Worker            string
	Params            *core.Params
	Workers           int
	AllowInsecureHTTP bool
	HTTPClient        *http.Client
	ProgressInterval  time.Duration
}

type SubmitResult

type SubmitResult struct {
	SchemaVersion int    `json:"schema_version"`
	Network       string `json:"network"`
	Status        string `json:"status"`
	BlockID       string `json:"block_id"`
	Height        int64  `json:"height"`
}

SubmitResult describes one accepted network block.

type Work

type Work struct {
	SchemaVersion int       `json:"schema_version"`
	Network       string    `json:"network"`
	JobID         string    `json:"job_id"`
	Height        int64     `json:"height"`
	HeaderHex     string    `json:"header_hex"`
	TargetHex     string    `json:"target_hex"`
	ExpiresAt     time.Time `json:"expires_at"`
	ArgonMemKiB   uint32    `json:"argon_mem_kib"`
	ArgonTime     uint32    `json:"argon_time"`
}

Work is a canonical remote-solo mining job. The client may change only the nonce in the final eight bytes of HeaderHex.

Jump to

Keyboard shortcuts

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