diff --git a/cmd/miner/config.go b/cmd/miner/config.go index dce13371..d8133a5d 100644 --- a/cmd/miner/config.go +++ b/cmd/miner/config.go @@ -349,7 +349,7 @@ func loadConfig() (*config, []string, error) { } // Create the home directory if it doesn't already exist. - funcName := "loadConfig" + const funcName = "loadConfig" err = os.MkdirAll(cfg.HomeDir, 0700) if err != nil { // Show a nicer error message if it's because a symlink is diff --git a/config.go b/config.go index 0bd178dc..66f9cea2 100644 --- a/config.go +++ b/config.go @@ -433,7 +433,7 @@ func loadConfig() (*config, []string, error) { } // Create the home directory if it doesn't already exist. - funcName := "loadConfig" + const funcName = "loadConfig" err = os.MkdirAll(cfg.HomeDir, 0700) if err != nil { // Show a nicer error message if it's because a symlink is diff --git a/pool/acceptedwork.go b/pool/acceptedwork.go index b35a6108..05e208d8 100644 --- a/pool/acceptedwork.go +++ b/pool/acceptedwork.go @@ -45,33 +45,18 @@ func bigEndianBytesToHeight(b []byte) uint32 { } // AcceptedWorkID generates a unique id for work accepted by the network. -func AcceptedWorkID(blockHash string, blockHeight uint32) ([]byte, error) { - funcName := "AcceptedWorkID" - buf := bytes.Buffer{} - _, err := buf.WriteString(hex.EncodeToString(heightToBigEndianBytes(blockHeight))) - if err != nil { - desc := fmt.Sprintf("%s: unable to write block height: %v", - funcName, err) - return nil, poolError(ErrID, desc) - } +func AcceptedWorkID(blockHash string, blockHeight uint32) []byte { + var buf bytes.Buffer + buf.WriteString(hex.EncodeToString(heightToBigEndianBytes(blockHeight))) buf.WriteString(blockHash) - if err != nil { - desc := fmt.Sprintf("%s: unable to write block hash: %v", - funcName, err) - return nil, poolError(ErrID, desc) - } - return buf.Bytes(), nil + return buf.Bytes() } // NewAcceptedWork creates an accepted work. func NewAcceptedWork(blockHash string, prevHash string, height uint32, minedBy string, miner string) (*AcceptedWork, error) { - id, err := AcceptedWorkID(blockHash, height) - if err != nil { - return nil, err - } return &AcceptedWork{ - UUID: string(id), + UUID: string(AcceptedWorkID(blockHash, height)), BlockHash: blockHash, PrevHash: prevHash, Height: height, @@ -83,7 +68,7 @@ func NewAcceptedWork(blockHash string, prevHash string, height uint32, // fetchWorkBucket is a helper function for getting the work bucket. func fetchWorkBucket(tx *bolt.Tx) (*bolt.Bucket, error) { - funcName := "fetchWorkBucket" + const funcName = "fetchWorkBucket" pbkt := tx.Bucket(poolBkt) if pbkt == nil { desc := fmt.Sprintf("%s: bucket %s not found", funcName, @@ -101,7 +86,7 @@ func fetchWorkBucket(tx *bolt.Tx) (*bolt.Bucket, error) { // FetchAcceptedWork fetches the accepted work referenced by the provided id. func FetchAcceptedWork(db *bolt.DB, id []byte) (*AcceptedWork, error) { - funcName := "FetchAcceptedWork" + const funcName = "FetchAcceptedWork" var work AcceptedWork err := db.View(func(tx *bolt.Tx) error { bkt, err := fetchWorkBucket(tx) @@ -130,7 +115,7 @@ func FetchAcceptedWork(db *bolt.DB, id []byte) (*AcceptedWork, error) { // Create persists the accepted work to the database. func (work *AcceptedWork) Create(db *bolt.DB) error { - funcName := "AcceptedWork.Create" + const funcName = "AcceptedWork.Create" return db.Update(func(tx *bolt.Tx) error { bkt, err := fetchWorkBucket(tx) if err != nil { @@ -143,7 +128,7 @@ func (work *AcceptedWork) Create(db *bolt.DB) error { if v != nil { desc := fmt.Sprintf("%s: work %s already exists", funcName, work.UUID) - return dbError(ErrWorkExists, desc) + return dbError(ErrValueFound, desc) } workBytes, err := json.Marshal(work) if err != nil { @@ -164,7 +149,7 @@ func (work *AcceptedWork) Create(db *bolt.DB) error { // Update persists modifications to an existing work. func (work *AcceptedWork) Update(db *bolt.DB) error { - funcName := "AcceptedWork.Update" + const funcName = "AcceptedWork.Update" return db.Update(func(tx *bolt.Tx) error { bkt, err := fetchWorkBucket(tx) if err != nil { @@ -204,7 +189,7 @@ func (work *AcceptedWork) Delete(db *bolt.DB) error { // // List is ordered, most recent comes first. func ListMinedWork(db *bolt.DB) ([]*AcceptedWork, error) { - funcName := "ListMinedWork" + const funcName = "ListMinedWork" minedWork := make([]*AcceptedWork, 0) err := db.View(func(tx *bolt.Tx) error { bkt, err := fetchWorkBucket(tx) diff --git a/pool/acceptedwork_test.go b/pool/acceptedwork_test.go index e983b050..09cbbe23 100644 --- a/pool/acceptedwork_test.go +++ b/pool/acceptedwork_test.go @@ -106,22 +106,14 @@ func testAcceptedWork(t *testing.T, db *bolt.DB) { } // Ensure fetching a non existent accepted work returns an error. - id, err := AcceptedWorkID(workC.BlockHash, workD.Height) - if err != nil { - t.Fatalf("unexpected work id error: %v", err) - } - + id := AcceptedWorkID(workC.BlockHash, workD.Height) _, err = FetchAcceptedWork(db, id) if err == nil { t.Fatalf("FetchAcceptedWork: expected a non-existent accepted work error") } // Fetch an accepted work with its id. - id, err = AcceptedWorkID(workC.BlockHash, workC.Height) - if err != nil { - t.Fatalf("unexpected work id error: %v", err) - } - + id = AcceptedWorkID(workC.BlockHash, workC.Height) fetchedWork, err := FetchAcceptedWork(db, id) if err != nil { t.Fatalf("FetchAcceptedWork error: %v", err) diff --git a/pool/account.go b/pool/account.go index df4c970c..a2b1913b 100644 --- a/pool/account.go +++ b/pool/account.go @@ -25,21 +25,16 @@ type Account struct { // AccountID generates a unique id using provided address of the account. func AccountID(address string, activeNet *chaincfg.Params) (string, error) { - funcName := "AcccountID" + const funcName = "AcccountID" _, err := dcrutil.DecodeAddress(address, activeNet) if err != nil { desc := fmt.Sprintf("%s: unable to decode address %s: %v", funcName, address, err) - return "", poolError(ErrID, desc) + return "", poolError(ErrDecode, desc) } hasher := blake256.New() - _, err = hasher.Write([]byte(address)) - if err != nil { - desc := fmt.Sprintf("%s: unable to write address: %v", funcName, err) - return "", poolError(ErrID, desc) - } - id := hex.EncodeToString(hasher.Sum(nil)) - return id, nil + _, _ = hasher.Write([]byte(address)) + return hex.EncodeToString(hasher.Sum(nil)), nil } // NewAccount creates a new account. @@ -60,7 +55,7 @@ func NewAccount(address string, activeNet *chaincfg.Params) (*Account, error) { // fetchAccountBucket is a helper function for getting the account bucket. func fetchAccountBucket(tx *bolt.Tx) (*bolt.Bucket, error) { - funcName := "fetchAccountBucket" + const funcName = "fetchAccountBucket" pbkt := tx.Bucket(poolBkt) if pbkt == nil { desc := fmt.Sprintf("%s: bucket %s not found", funcName, @@ -78,7 +73,7 @@ func fetchAccountBucket(tx *bolt.Tx) (*bolt.Bucket, error) { // FetchAccount fetches the account referenced by the provided id. func FetchAccount(db *bolt.DB, id []byte) (*Account, error) { - funcName := "FetchAccount" + const funcName = "FetchAccount" var account Account err := db.View(func(tx *bolt.Tx) error { bkt, err := fetchAccountBucket(tx) @@ -108,7 +103,7 @@ func FetchAccount(db *bolt.DB, id []byte) (*Account, error) { // Create persists the account to the database. func (acc *Account) Create(db *bolt.DB) error { - funcName := "Account.Create" + const funcName = "Account.Create" return db.Update(func(tx *bolt.Tx) error { bkt, err := fetchAccountBucket(tx) if err != nil { @@ -121,7 +116,7 @@ func (acc *Account) Create(db *bolt.DB) error { if v != nil { desc := fmt.Sprintf("%s: account %s already exists", funcName, acc.UUID) - return dbError(ErrAccountExists, desc) + return dbError(ErrValueFound, desc) } accBytes, err := json.Marshal(acc) if err != nil { @@ -139,13 +134,6 @@ func (acc *Account) Create(db *bolt.DB) error { }) } -// Update is not supported for accounts. -func (acc *Account) Update(db *bolt.DB) error { - funcName := "Account.Update" - desc := fmt.Sprintf("%s: not supported", funcName) - return dbError(ErrNotSupported, desc) -} - // Delete purges the referenced account from the database. func (acc *Account) Delete(db *bolt.DB) error { return deleteEntry(db, accountBkt, []byte(acc.UUID)) diff --git a/pool/account_test.go b/pool/account_test.go index 92740477..6fb87f94 100644 --- a/pool/account_test.go +++ b/pool/account_test.go @@ -49,12 +49,6 @@ func testAccount(t *testing.T, db *bolt.DB) { accountA.UUID, fetchedAccount.UUID) } - // Ensure accounts cannot be updated. - err = accountB.Update(db) - if err == nil { - t.Fatal("expected not supported error") - } - // Delete all accounts. err = accountA.Delete(db) if err != nil { diff --git a/pool/chainstate.go b/pool/chainstate.go index 37f0442c..26ad632d 100644 --- a/pool/chainstate.go +++ b/pool/chainstate.go @@ -349,13 +349,7 @@ func (cs *ChainState) handleChainUpdates(ctx context.Context) { // of the pool. parentHeight := header.Height - 1 parentHash := header.PrevBlock.String() - parentID, err := AcceptedWorkID(parentHash, parentHeight) - if err != nil { - log.Error(err) - close(msg.Done) - cs.cfg.Cancel() - continue - } + parentID := AcceptedWorkID(parentHash, parentHeight) work, err := FetchAcceptedWork(cs.cfg.DB, parentID) if err != nil { // If the parent of the connected block is not an accepted @@ -476,13 +470,7 @@ func (cs *ChainState) handleChainUpdates(ctx context.Context) { // does unconfirm it. parentHeight := header.Height - 1 parentHash := header.PrevBlock.String() - parentID, err := AcceptedWorkID(parentHash, parentHeight) - if err != nil { - log.Error(err) - close(msg.Done) - cs.cfg.Cancel() - continue - } + parentID := AcceptedWorkID(parentHash, parentHeight) confirmedWork, err := FetchAcceptedWork(cs.cfg.DB, parentID) if err != nil { // Errors generated, except for a value not found error, @@ -522,13 +510,7 @@ func (cs *ChainState) handleChainUpdates(ctx context.Context) { // If the disconnected block is an accepted work of the pool // ensure it is not confirmed mined. blockHash := header.BlockHash().String() - id, err := AcceptedWorkID(blockHash, header.Height) - if err != nil { - log.Error(err) - close(msg.Done) - cs.cfg.Cancel() - continue - } + id := AcceptedWorkID(blockHash, header.Height) work, err := FetchAcceptedWork(cs.cfg.DB, id) if err != nil { // If the disconnected block is not an accepted diff --git a/pool/chainstate_test.go b/pool/chainstate_test.go index f436943d..55a41a75 100644 --- a/pool/chainstate_test.go +++ b/pool/chainstate_test.go @@ -213,7 +213,7 @@ func testChainState(t *testing.T, db *bolt.DB) { t.Fatalf("prunePayments error: %v", err) } - aID, err := paymentID(paymentA.Height, paymentA.CreatedOn, paymentA.Account) + aID := paymentID(paymentA.Height, paymentA.CreatedOn, paymentA.Account) if err != nil { t.Fatalf("unexpected payment id err: %v", err) } @@ -222,7 +222,7 @@ func testChainState(t *testing.T, db *bolt.DB) { t.Fatalf("unexpected error fetching payment A: %v", err) } - bID, err := paymentID(paymentB.Height, paymentB.CreatedOn, paymentB.Account) + bID := paymentID(paymentB.Height, paymentB.CreatedOn, paymentB.Account) if err != nil { t.Fatalf("unexpected payment id err: %v", err) } @@ -284,10 +284,7 @@ func testChainState(t *testing.T, db *bolt.DB) { "0004fa83b20204e0000000000002a000000a50300004348fa5d00000000" + "00000000000000000000000000000000000000000000000000000000000" + "00000000000008000000100000000000005a0" - job, err := NewJob(workE, 42) - if err != nil { - t.Fatalf("unable to create job %v", err) - } + job := NewJob(workE, 42) err = job.Create(cs.cfg.DB) if err != nil { log.Errorf("failed to persist job %v", err) diff --git a/pool/client.go b/pool/client.go index 8e3df3cc..061d8be5 100644 --- a/pool/client.go +++ b/pool/client.go @@ -177,10 +177,7 @@ func (c *Client) claimWeightedShare() error { return poolError(ErrClaimShare, desc) } weight := ShareWeights[c.cfg.FetchMiner()] - share, err := NewShare(c.account, weight) - if err != nil { - return err - } + share := NewShare(c.account, weight) return share.Create(c.cfg.DB) } @@ -466,7 +463,7 @@ func (c *Client) handleSubmitWorkRequest(ctx context.Context, req *Request, allo if err != nil { // If the submitted accepted work already exists, ignore the // submission. - if errors.Is(err, ErrWorkExists) { + if errors.Is(err, ErrValueFound) { sErr := NewStratumError(DuplicateShare, err) resp := SubmitWorkResponse(*req.ID, false, sErr) c.ch <- resp @@ -563,7 +560,7 @@ func (c *Client) read() { // after client authentication and when the client is stalling on // current work. func (c *Client) updateWork() { - funcName := "updateWork" + const funcName = "updateWork" // Only timestamp-roll current work for authorized and subscribed clients. c.authorizedMtx.Lock() authorized := c.authorized @@ -584,24 +581,10 @@ func (c *Client) updateWork() { b := make([]byte, 4) binary.LittleEndian.PutUint32(b, now) timestampE := hex.EncodeToString(b) - buf := bytes.NewBufferString("") - _, err := buf.WriteString(currWorkE[:272]) - if err != nil { - log.Errorf("%s: unable to write first current work slice: %v", - funcName, err) - return - } - _, err = buf.WriteString(timestampE) - if err != nil { - log.Errorf("%s: unable to write timetamp: %v", funcName, err) - return - } - _, err = buf.WriteString(currWorkE[280:]) - if err != nil { - log.Errorf("%s: unable to write second current work slice: %v", - funcName, err) - return - } + var buf bytes.Buffer + buf.WriteString(currWorkE[:272]) + buf.WriteString(timestampE) + buf.WriteString(currWorkE[280:]) updatedWorkE := buf.String() blockVersion := updatedWorkE[:8] @@ -620,11 +603,7 @@ func (c *Client) updateWork() { height := binary.LittleEndian.Uint32(heightD) // Create a job for the timestamp-rolled current work. - job, err := NewJob(updatedWorkE, height) - if err != nil { - log.Error(err) - return - } + job := NewJob(updatedWorkE, height) err = job.Create(c.cfg.DB) if err != nil { log.Error(err) @@ -734,11 +713,11 @@ func reversePrevBlockWords(hashE string) string { // hexReversed reverses a hex string. func hexReversed(in string) (string, error) { - funcName := "hexReversed" + const funcName = "hexReversed" if len(in)%2 != 0 { desc := fmt.Sprintf("%s: expected even hex input length, got %d", funcName, len(in)) - return "", dbError(ErrHexLength, desc) + return "", poolError(ErrHexLength, desc) } buf := bytes.NewBufferString("") for i := len(in) - 1; i > -1; i -= 2 { diff --git a/pool/client_test.go b/pool/client_test.go index 3b0feb6a..7eb68d98 100644 --- a/pool/client_test.go +++ b/pool/client_test.go @@ -529,10 +529,7 @@ func testClient(t *testing.T, db *bolt.DB) { "000a6030000954cee5d00000000000000000000000000000000000" + "000000000000000000000000000000000000000000000800000010" + "0000000000005a0" - job, err := NewJob(workE, 41) - if err != nil { - t.Fatalf("unable to create job %v", err) - } + job := NewJob(workE, 41) err = job.Create(client.cfg.DB) if err != nil { t.Fatalf("failed to persist job %v", err) @@ -817,10 +814,7 @@ func testClient(t *testing.T, db *bolt.DB) { "0000002e0000003b0f000005ec705e0000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000800000010000000000" + "0005a0" - job, err = NewJob(workE, 46) - if err != nil { - t.Fatalf("[NewJob] unexpected error: %v", err) - } + job = NewJob(workE, 46) err = job.Create(client.cfg.DB) if err != nil { t.Fatalf("failed to persist job %v", err) diff --git a/pool/db.go b/pool/db.go index b1931afe..8507da08 100644 --- a/pool/db.go +++ b/pool/db.go @@ -59,7 +59,7 @@ var ( // openDB creates a connection to the provided bolt storage, the returned // connection storage should always be closed after use. func openDB(storage string) (*bolt.DB, error) { - funcName := "openDB" + const funcName = "openDB" db, err := bolt.Open(storage, 0600, &bolt.Options{Timeout: 1 * time.Second}) if err != nil { @@ -71,11 +71,11 @@ func openDB(storage string) (*bolt.DB, error) { // createNestedBucket creates a nested child bucket of the provided parent. func createNestedBucket(parent *bolt.Bucket, child []byte) error { - funcName := "createNestedBucket" + const funcName = "createNestedBucket" _, err := parent.CreateBucketIfNotExists(child) if err != nil { desc := fmt.Sprintf("%s: unable to create %s bucket: %v", - string(child), funcName, err) + funcName, string(child), err) return dbError(ErrBucketCreate, desc) } return nil @@ -83,7 +83,7 @@ func createNestedBucket(parent *bolt.Bucket, child []byte) error { // createBuckets creates all storage buckets of the mining pool. func createBuckets(db *bolt.DB) error { - funcName := "createBuckets" + const funcName = "createBuckets" err := db.Update(func(tx *bolt.Tx) error { var err error pbkt := tx.Bucket(poolBkt) @@ -91,7 +91,7 @@ func createBuckets(db *bolt.DB) error { pbkt, err = tx.CreateBucketIfNotExists(poolBkt) if err != nil { desc := fmt.Sprintf("%s: unable to create %s bucket: %v", - string(poolBkt), funcName, err) + funcName, string(poolBkt), err) return dbError(ErrBucketCreate, desc) } vbytes := make([]byte, 4) @@ -143,7 +143,7 @@ func backup(db *bolt.DB, file string) error { // purge removes all existing data and recreates the db. func purge(db *bolt.DB) error { - funcName := "purge" + const funcName = "purge" err := db.Update(func(tx *bolt.Tx) error { pbkt := tx.Bucket(poolBkt) if pbkt == nil { @@ -254,7 +254,7 @@ func InitDB(dbFile string, isSoloPool bool) (*bolt.DB, error) { // deleteEntry removes the specified key and its associated value from // the provided bucket. func deleteEntry(db *bolt.DB, bucket, key []byte) error { - funcName := "deleteEntry" + const funcName = "deleteEntry" return db.Update(func(tx *bolt.Tx) error { pbkt := tx.Bucket(poolBkt) if pbkt == nil { @@ -277,7 +277,7 @@ func deleteEntry(db *bolt.DB, bucket, key []byte) error { // emptyBucket deletes all k/v pairs in the provided bucket. func emptyBucket(db *bolt.DB, bucket []byte) error { - funcName := "emptyBucket" + const funcName = "emptyBucket" return db.Update(func(tx *bolt.Tx) error { pbkt := tx.Bucket(poolBkt) if pbkt == nil { diff --git a/pool/db_test.go b/pool/db_test.go index 4280b1b9..fc485b19 100644 --- a/pool/db_test.go +++ b/pool/db_test.go @@ -134,18 +134,17 @@ func testFetchBucketHelpers(t *testing.T) { if pbkt == nil { pbkt, err = tx.CreateBucketIfNotExists(poolBkt) if err != nil { - desc := fmt.Sprintf("unable to create %s bucket: %v", + return fmt.Errorf("unable to create %s bucket: %v", string(poolBkt), err) - return dbError(ErrBucketCreate, desc) + } vbytes := make([]byte, 4) binary.LittleEndian.PutUint32(vbytes, uint32(DBVersion)) err = pbkt.Put(versionK, vbytes) if err != nil { - return err + return fmt.Errorf("unable to persist version: %v", err) } } - return nil }) if err != nil { diff --git a/pool/difficulty.go b/pool/difficulty.go index 61b15d3b..37645ef3 100644 --- a/pool/difficulty.go +++ b/pool/difficulty.go @@ -118,7 +118,7 @@ func NewDifficultySet(net *chaincfg.Params, powLimit *big.Rat, maxGenTime time.D // fetchMinerDifficulty returns the difficulty data of the provided miner, // if it exists. func (d *DifficultySet) fetchMinerDifficulty(miner string) (*DifficultyInfo, error) { - funcName := "fetchMinerDifficulty" + const funcName = "fetchMinerDifficulty" d.mtx.Lock() diffData, ok := d.diffs[miner] d.mtx.Unlock() diff --git a/pool/error.go b/pool/error.go index d1342da5..683befb1 100644 --- a/pool/error.go +++ b/pool/error.go @@ -36,9 +36,6 @@ const ( // ErrDeleteEntry indicates a database entry delete error. ErrDeleteEntry = ErrorKind("ErrDeleteEntry") - // ErrNotSupported indicates unsupported functionality. - ErrNotSupported = ErrorKind("ErrNotSupported") - // ErrBackup indicates database backup error. ErrBackup = ErrorKind("ErrBackup") @@ -48,9 +45,6 @@ const ( // ErrDecode indicates a decoding error. ErrDecode = ErrorKind("ErrDecode") - // ErrID indicates an ID related error. - ErrID = ErrorKind("ErrID") - // ErrValueFound indicates a an unexpected value found. ErrValueFound = ErrorKind("ErrValueFound") @@ -64,9 +58,6 @@ const ( // ErrGetBlock indicates a block could not be fetched. ErrGetBlock = ErrorKind("ErrGetBlock") - // ErrWorkExists indicates the work being created already exists. - ErrWorkExists = ErrorKind("ErrWorkExists") - // ErrDisconnected indicates a disconnected resource. ErrDisconnected = ErrorKind("ErrDisconnected") @@ -103,9 +94,6 @@ const ( // ErrWorkRejected indicates the rejected submitted work. ErrWorkRejected = ErrorKind("ErrWorkRejected") - // ErrAccountExists indicates the account being created already exists. - ErrAccountExists = ErrorKind("ErrAccountExists") - // ErrPaymentSource indicates a payment source error. ErrPaymentSource = ErrorKind("ErrPaymentSource") ) @@ -133,17 +121,21 @@ func (e Error) Unwrap() error { return e.Err } -// poolError creates an Error given a set of arguments. +// poolError creates an Error given a set of arguments. This hould only be +// used when creating error related to the mining pool and its processes. func poolError(kind ErrorKind, desc string) Error { return Error{Err: kind, Description: desc} } -// dbError creates an Error given a set of arguments. +// dbError creates an Error given a set of arguments. This should only be +// used when creating errors related to the database. func dbError(kind ErrorKind, desc string) Error { return Error{Err: kind, Description: desc} } -// msgError creates a MesssageError given a set of arguments. +// msgError creates am Error given a set of arguments. This should only be +// used when creating errors related to sending, receiving and processing +// messages. func msgError(kind ErrorKind, desc string) Error { return Error{Err: kind, Description: desc} } diff --git a/pool/error_test.go b/pool/error_test.go index 4fb0a109..21ce5a72 100644 --- a/pool/error_test.go +++ b/pool/error_test.go @@ -22,16 +22,13 @@ func TestErrorKindStringer(t *testing.T) { {ErrDBUpgrade, "ErrDBUpgrade"}, {ErrPersistEntry, "ErrPersistEntry"}, {ErrDeleteEntry, "ErrDeleteEntry"}, - {ErrNotSupported, "ErrNotSupported"}, {ErrBackup, "ErrBackup"}, {ErrParse, "ErrParse"}, {ErrDecode, "ErrDecode"}, - {ErrID, "ErrID"}, {ErrValueFound, "ErrValueFound"}, {ErrGetWork, "ErrGetWork"}, {ErrGetBlock, "ErrGetBlock"}, - {ErrWorkExists, "ErrWorkExists"}, {ErrDisconnected, "ErrDisconnected"}, {ErrListener, "ErrListener"}, {ErrHeaderInvalid, "ErrHeaderInvalid"}, @@ -44,7 +41,6 @@ func TestErrorKindStringer(t *testing.T) { {ErrLimitExceeded, "ErrLimitExceeded"}, {ErrDifficulty, "ErrDifficulty"}, {ErrWorkRejected, "ErrWorkRejected"}, - {ErrAccountExists, "ErrAccountExists"}, {ErrPaymentSource, "ErrPaymentSource"}, } @@ -149,7 +145,7 @@ func TestErrorKindIsAs(t *testing.T) { continue } - // Ensure the underlying error kind can be unwrapped is and is the + // Ensure the underlying error kind can be unwrapped and is the // expected kind. var kind ErrorKind if !errors.As(test.err, &kind) { diff --git a/pool/hub.go b/pool/hub.go index 1a03e598..41a6e95b 100644 --- a/pool/hub.go +++ b/pool/hub.go @@ -420,11 +420,7 @@ func (h *Hub) processWork(headerE string) { nBits := headerE[232:240] nTime := headerE[272:280] genTx2 := headerE[352:360] - job, err := NewJob(headerE, height) - if err != nil { - log.Error(err) - return - } + job := NewJob(headerE, height) err = job.Create(h.db) if err != nil { log.Error(err) diff --git a/pool/job.go b/pool/job.go index 0f1e924d..5a4a5e03 100644 --- a/pool/job.go +++ b/pool/job.go @@ -31,40 +31,25 @@ func nanoToBigEndianBytes(nano int64) []byte { } // jobID generates a unique job id of the provided block height. -func jobID(height uint32) (string, error) { - funcName := "jobID" - buf := bytes.Buffer{} - _, err := buf.Write(heightToBigEndianBytes(height)) - if err != nil { - desc := fmt.Sprintf("(%s) unable to write block height: %v", - funcName, err) - return "", poolError(ErrID, desc) - } +func jobID(height uint32) string { + var buf bytes.Buffer + buf.Write(heightToBigEndianBytes(height)) buf.Write(nanoToBigEndianBytes(time.Now().UnixNano())) - if err != nil { - desc := fmt.Sprintf("(%s) unable to write current time: %v", - funcName, err) - return "", poolError(ErrID, desc) - } - return hex.EncodeToString(buf.Bytes()), nil + return hex.EncodeToString(buf.Bytes()) } // NewJob creates a job instance. -func NewJob(header string, height uint32) (*Job, error) { - id, err := jobID(height) - if err != nil { - return nil, err - } +func NewJob(header string, height uint32) *Job { return &Job{ - UUID: id, + UUID: jobID(height), Height: height, Header: header, - }, nil + } } // fetchJobBucket is a helper function for getting the job bucket. func fetchJobBucket(tx *bolt.Tx) (*bolt.Bucket, error) { - funcName := "fetchJobBucket" + const funcName = "fetchJobBucket" pbkt := tx.Bucket(poolBkt) if pbkt == nil { desc := fmt.Sprintf("%s: bucket %s not found", funcName, @@ -82,7 +67,7 @@ func fetchJobBucket(tx *bolt.Tx) (*bolt.Bucket, error) { // FetchJob fetches the job referenced by the provided id. func FetchJob(db *bolt.DB, id []byte) (*Job, error) { - funcName := "FetchJob" + const funcName = "FetchJob" var job Job err := db.View(func(tx *bolt.Tx) error { bkt, err := fetchJobBucket(tx) @@ -112,7 +97,7 @@ func FetchJob(db *bolt.DB, id []byte) (*Job, error) { // Create persists the job to the database. func (job *Job) Create(db *bolt.DB) error { - funcName := "Job.Create" + const funcName = "Job.Create" return db.Update(func(tx *bolt.Tx) error { bkt, err := fetchJobBucket(tx) if err != nil { @@ -135,13 +120,6 @@ func (job *Job) Create(db *bolt.DB) error { }) } -// Update is not supported for jobs. -func (job *Job) Update(db *bolt.DB) error { - funcName := "Job.Update" - desc := fmt.Sprintf("%s: not supported", funcName) - return dbError(ErrNotSupported, desc) -} - // Delete removes the associated job from the database. func (job *Job) Delete(db *bolt.DB) error { return deleteEntry(db, jobBkt, []byte(job.UUID)) diff --git a/pool/job_test.go b/pool/job_test.go index 1ccf7e1d..c2066d5c 100644 --- a/pool/job_test.go +++ b/pool/job_test.go @@ -8,11 +8,8 @@ import ( ) func persistJob(db *bolt.DB, header string, height uint32) (*Job, error) { - job, err := NewJob(header, height) - if err != nil { - return nil, fmt.Errorf("unable to create job: %v", err) - } - err = job.Create(db) + job := NewJob(header, height) + err := job.Create(db) if err != nil { return nil, fmt.Errorf("unable to persist job: %v", err) } @@ -60,13 +57,6 @@ func testJob(t *testing.T, db *bolt.DB) { t.Fatal("expected a non-nil job") } - // Ensure jobs cannot be updated. - jobB.Height = 60 - err = jobB.Update(db) - if err == nil { - t.Fatal("expected a not supported error") - } - // Delete jobs B and C. err = jobB.Delete(db) if err != nil { diff --git a/pool/message.go b/pool/message.go index b944a21e..b446e057 100644 --- a/pool/message.go +++ b/pool/message.go @@ -170,7 +170,7 @@ func AuthorizeRequest(id *uint64, name string, address string) *Request { // ParseAuthorizeRequest resolves an authorize request into its components. func ParseAuthorizeRequest(req *Request) (string, error) { - funcName := "ParseAuthorizeRequest" + const funcName = "ParseAuthorizeRequest" if req.Method != Authorize { desc := fmt.Sprintf("%s: request method is not authorize", funcName) return "", msgError(ErrParse, desc) @@ -185,7 +185,7 @@ func ParseAuthorizeRequest(req *Request) (string, error) { if len(auth) < 2 { desc := fmt.Sprintf("%s: expected 2 params for authorize request, "+ - "got %v", funcName, len(auth)) + "got %d", funcName, len(auth)) return "", msgError(ErrParse, desc) } @@ -210,7 +210,7 @@ func AuthorizeResponse(id uint64, status bool, err *StratumError) *Response { // ParseAuthorizeResponse resolves an authorize response into its components. func ParseAuthorizeResponse(resp *Response) (bool, *StratumError, error) { - funcName := "ParseAuthorizeResponse" + const funcName = "ParseAuthorizeResponse" status, ok := resp.Result.(bool) if !ok { desc := fmt.Sprintf("%s: unable to parse authorize response "+ @@ -238,7 +238,7 @@ func SubscribeRequest(id *uint64, userAgent string, version string, notifyID str // ParseSubscribeRequest resolves a subscribe request into its components. func ParseSubscribeRequest(req *Request) (string, string, error) { - funcName := "ParseSubscribeRequest" + const funcName = "ParseSubscribeRequest" if req.Method != Subscribe { desc := fmt.Sprintf("%s: request method is not subscribe", funcName) return "", "", msgError(ErrParse, desc) @@ -298,7 +298,7 @@ func SubscribeResponse(id uint64, notifyID string, extraNonce1 string, extraNonc // ParseSubscribeResponse resolves a subscribe response into its components. func ParseSubscribeResponse(resp *Response) (string, string, string, uint64, error) { - funcName := "ParseSubscribeResponse" + const funcName = "ParseSubscribeResponse" if resp.Error != nil { desc := fmt.Sprintf("%s: %d, %s, %s", funcName, resp.Error.Code, resp.Error.Message, resp.Error.Traceback) @@ -378,7 +378,7 @@ func SetDifficultyNotification(difficulty *big.Rat) *Request { // ParseSetDifficultyNotification resolves a set difficulty notification into // its components. func ParseSetDifficultyNotification(req *Request) (uint64, error) { - funcName := "ParseSetDifficultyNotification" + const funcName = "ParseSetDifficultyNotification" if req.Method != SetDifficulty { desc := fmt.Sprintf("%s: notification method is not set "+ "difficulty", funcName) @@ -406,7 +406,7 @@ func WorkNotification(jobID string, prevBlock string, genTx1 string, genTx2 stri // ParseWorkNotification resolves a work notification message into its components. func ParseWorkNotification(req *Request) (string, string, string, string, string, string, string, bool, error) { - funcName := "ParseWorkNotification" + const funcName = "ParseWorkNotification" if req.Method != Notify { desc := fmt.Sprintf("%s: notification method is not notify", funcName) return "", "", "", "", "", "", "", false, msgError(ErrParse, desc) @@ -447,6 +447,10 @@ func ParseWorkNotification(req *Request) (string, string, string, string, string return "", "", "", "", "", "", "", false, msgError(ErrParse, desc) } + // Note that param[4] which is the list of merkle branches is not + // applicable for decred, the final merkle root is already + // included in the block. + blockVersion, ok := params[5].(string) if !ok { desc := fmt.Sprintf("%s: unable to parse work notification "+ @@ -456,7 +460,7 @@ func ParseWorkNotification(req *Request) (string, string, string, string, string nBits, ok := params[6].(string) if !ok { - desc := fmt.Sprintf("%s: unable to parse workn notification "+ + desc := fmt.Sprintf("%s: unable to parse work notification "+ "nBits parameter", funcName) return "", "", "", "", "", "", "", false, msgError(ErrParse, desc) } @@ -483,7 +487,7 @@ func ParseWorkNotification(req *Request) (string, string, string, string, string // message and the extraNonce1 of the client. func GenerateBlockHeader(blockVersionE string, prevBlockE string, genTx1E string, extraNonce1E string, genTx2E string) (*wire.BlockHeader, error) { - funcName := "GenerateBlockHeader" + const funcName = "GenerateBlockHeader" buf := bytes.NewBufferString("") buf.WriteString(blockVersionE) buf.WriteString(prevBlockE) @@ -637,7 +641,7 @@ func SubmitWorkRequest(id *uint64, workerName string, jobID string, extraNonce2 // ParseSubmitWorkRequest resolves a submit work request into its components. func ParseSubmitWorkRequest(req *Request, miner string) (string, string, string, string, string, error) { - funcName := "ParseSubmitWorkRequest" + const funcName = "ParseSubmitWorkRequest" if req.Method != Submit { desc := fmt.Sprintf("%s: request method is not submit", funcName) return "", "", "", "", "", msgError(ErrParse, desc) @@ -702,7 +706,7 @@ func SubmitWorkResponse(id uint64, status bool, err *StratumError) *Response { // ParseSubmitWorkResponse resolves a submit response into its components. func ParseSubmitWorkResponse(resp *Response) (bool, *StratumError, error) { - funcName := "ParseSubmitWorkResponse" + const funcName = "ParseSubmitWorkResponse" status, ok := resp.Result.(bool) if !ok { desc := fmt.Sprintf("%s: unable to parse result parameter", funcName) diff --git a/pool/payment.go b/pool/payment.go index 27ee4bfe..7453c319 100644 --- a/pool/payment.go +++ b/pool/payment.go @@ -50,34 +50,17 @@ func NewPayment(account string, source *PaymentSource, amount dcrutil.Amount, } // paymentID generates a unique id using the provided payment details. -func paymentID(height uint32, createdOnNano int64, account string) ([]byte, error) { - funcName := "paymentID" - buf := bytes.Buffer{} - _, err := buf.WriteString(hex.EncodeToString( - heightToBigEndianBytes(height))) - if err != nil { - desc := fmt.Sprintf("%s: unable to write block height: %v", - funcName, err) - return nil, poolError(ErrID, desc) - } - _, err = buf.WriteString(hex.EncodeToString( - nanoToBigEndianBytes(createdOnNano))) - if err != nil { - desc := fmt.Sprintf("%s: unable to write created-on time: %v", - funcName, err) - return nil, poolError(ErrID, desc) - } - _, err = buf.WriteString(account) - if err != nil { - desc := fmt.Sprintf("%s: unable to write account: %v", funcName, err) - return nil, poolError(ErrID, desc) - } - return buf.Bytes(), nil +func paymentID(height uint32, createdOnNano int64, account string) []byte { + var buf bytes.Buffer + buf.WriteString(hex.EncodeToString(heightToBigEndianBytes(height))) + buf.WriteString(hex.EncodeToString(nanoToBigEndianBytes(createdOnNano))) + buf.WriteString(account) + return buf.Bytes() } // fetchPaymentBucket is a helper function for getting the payment bucket. func fetchPaymentBucket(tx *bolt.Tx) (*bolt.Bucket, error) { - funcName := "fetchPaymentBucket" + const funcName = "fetchPaymentBucket" pbkt := tx.Bucket(poolBkt) if pbkt == nil { desc := fmt.Sprintf("%s: bucket %s not found", funcName, @@ -96,7 +79,7 @@ func fetchPaymentBucket(tx *bolt.Tx) (*bolt.Bucket, error) { // fetchPaymentArchiveBucket is a helper function for getting the // payment archive bucket. func fetchPaymentArchiveBucket(tx *bolt.Tx) (*bolt.Bucket, error) { - funcName := "fetchPaymentArchiveBucket" + const funcName = "fetchPaymentArchiveBucket" pbkt := tx.Bucket(poolBkt) if pbkt == nil { desc := fmt.Sprintf("%s: bucket %s not found", funcName, @@ -114,7 +97,7 @@ func fetchPaymentArchiveBucket(tx *bolt.Tx) (*bolt.Bucket, error) { // FetchPayment fetches the payment referenced by the provided id. func FetchPayment(db *bolt.DB, id []byte) (*Payment, error) { - funcName := "FetchPayment" + const funcName = "FetchPayment" var payment Payment err := db.View(func(tx *bolt.Tx) error { bkt, err := fetchPaymentBucket(tx) @@ -143,7 +126,7 @@ func FetchPayment(db *bolt.DB, id []byte) (*Payment, error) { // Create persists a payment to the database. func (pmt *Payment) Create(db *bolt.DB) error { - funcName := "Payment.Create" + const funcName = "Payment.Create" return db.Update(func(tx *bolt.Tx) error { bkt, err := fetchPaymentBucket(tx) if err != nil { @@ -155,10 +138,7 @@ func (pmt *Payment) Create(db *bolt.DB) error { funcName, err) return dbError(ErrParse, desc) } - id, err := paymentID(pmt.Height, pmt.CreatedOn, pmt.Account) - if err != nil { - return err - } + id := paymentID(pmt.Height, pmt.CreatedOn, pmt.Account) err = bkt.Put(id, b) if err != nil { desc := fmt.Sprintf("%s: unable to persist payment bytes: %v", @@ -177,16 +157,13 @@ func (pmt *Payment) Update(db *bolt.DB) error { // Delete purges the referenced payment from the database. Note that // archived payments cannot be deleted. func (pmt *Payment) Delete(db *bolt.DB) error { - id, err := paymentID(pmt.Height, pmt.CreatedOn, pmt.Account) - if err != nil { - return err - } + id := paymentID(pmt.Height, pmt.CreatedOn, pmt.Account) return deleteEntry(db, paymentBkt, id) } // Archive removes the associated payment from active payments and archives it. func (pmt *Payment) Archive(db *bolt.DB) error { - funcName := "Payment.Archive" + const funcName = "Payment.Archive" return db.Update(func(tx *bolt.Tx) error { pbkt, err := fetchPaymentBucket(tx) if err != nil { @@ -198,10 +175,7 @@ func (pmt *Payment) Archive(db *bolt.DB) error { } // Remove the active payment record. - id, err := paymentID(pmt.Height, pmt.CreatedOn, pmt.Account) - if err != nil { - return err - } + id := paymentID(pmt.Height, pmt.CreatedOn, pmt.Account) err = pbkt.Delete(id) if err != nil { return err @@ -216,10 +190,7 @@ func (pmt *Payment) Archive(db *bolt.DB) error { return dbError(ErrParse, desc) } - id, err = paymentID(pmt.Height, pmt.CreatedOn, pmt.Account) - if err != nil { - return err - } + id = paymentID(pmt.Height, pmt.CreatedOn, pmt.Account) err = abkt.Put(id, pmtB) if err != nil { desc := fmt.Sprintf("%s: unable to archive payment entry: %v", diff --git a/pool/payment_test.go b/pool/payment_test.go index b01b7e85..579708bb 100644 --- a/pool/payment_test.go +++ b/pool/payment_test.go @@ -48,10 +48,7 @@ func testPayment(t *testing.T, db *bolt.DB) { } // Fetch a payment using its id. - id, err := paymentID(pmtA.Height, pmtA.CreatedOn, pmtA.Account) - if err != nil { - t.Fatalf("unexpected payment id error: %v", err) - } + id := paymentID(pmtA.Height, pmtA.CreatedOn, pmtA.Account) fetchedPayment, err := FetchPayment(db, id) if err != nil { t.Fatalf("FetchPayment err: %v", err) @@ -68,10 +65,7 @@ func testPayment(t *testing.T, db *bolt.DB) { t.Fatalf("payment update err: %v", err) } - id, err = paymentID(pmtB.Height, pmtB.CreatedOn, pmtB.Account) - if err != nil { - t.Fatalf("unexpected payment id error: %v", err) - } + id = paymentID(pmtB.Height, pmtB.CreatedOn, pmtB.Account) fetchedPayment, err = FetchPayment(db, id) if err != nil { t.Fatalf("FetchPayment err: %v", err) @@ -90,10 +84,7 @@ func testPayment(t *testing.T, db *bolt.DB) { } // Ensure the payment B was archived. - id, err = paymentID(pmtB.Height, pmtB.CreatedOn, pmtB.Account) - if err != nil { - t.Fatalf("unexpected payment id error: %v", err) - } + id = paymentID(pmtB.Height, pmtB.CreatedOn, pmtB.Account) _, err = FetchPayment(db, id) if err == nil { t.Fatalf("expected a value not found error: %v", err) @@ -106,10 +97,7 @@ func testPayment(t *testing.T, db *bolt.DB) { } // Ensure the payment C was deleted. - id, err = paymentID(pmtC.Height, pmtC.CreatedOn, pmtC.Account) - if err != nil { - t.Fatalf("unexpected payment id error: %v", err) - } + id = paymentID(pmtC.Height, pmtC.CreatedOn, pmtC.Account) fetchedPayment, err = FetchPayment(db, id) if err == nil { t.Fatalf("expected a value not found error: %v", err) diff --git a/pool/paymentmgr_test.go b/pool/paymentmgr_test.go index 43916347..3322c4db 100644 --- a/pool/paymentmgr_test.go +++ b/pool/paymentmgr_test.go @@ -25,8 +25,7 @@ func fetchShare(db *bolt.DB, id []byte) (*Share, error) { } v := bkt.Get(id) if v == nil { - desc := fmt.Sprintf("no share found for id %s", string(id)) - return dbError(ErrValueNotFound, desc) + return fmt.Errorf("no share found for id %s", string(id)) } err = json.Unmarshal(v, &share) return err @@ -37,12 +36,6 @@ func fetchShare(db *bolt.DB, id []byte) (*Share, error) { return &share, err } -// makeShare creates a new share, this is reserved for testing purposes. -func makeShare(account string, weight *big.Rat) *Share { - share, _ := NewShare(account, weight) - return share -} - func testPaymentMgr(t *testing.T, db *bolt.DB) { activeNet := chaincfg.SimNetParams() @@ -83,11 +76,11 @@ func testPaymentMgr(t *testing.T, db *bolt.DB) { }{ "equal shares": { input: []*Share{ - makeShare("a", new(big.Rat).SetInt64(5)), - makeShare("b", new(big.Rat).SetInt64(5)), - makeShare("c", new(big.Rat).SetInt64(5)), - makeShare("d", new(big.Rat).SetInt64(5)), - makeShare("e", new(big.Rat).SetInt64(5)), + NewShare("a", new(big.Rat).SetInt64(5)), + NewShare("b", new(big.Rat).SetInt64(5)), + NewShare("c", new(big.Rat).SetInt64(5)), + NewShare("d", new(big.Rat).SetInt64(5)), + NewShare("e", new(big.Rat).SetInt64(5)), }, output: map[string]*big.Rat{ "a": new(big.Rat).SetFrac64(5, 25), @@ -100,11 +93,11 @@ func testPaymentMgr(t *testing.T, db *bolt.DB) { }, "inequal shares": { input: []*Share{ - makeShare("a", new(big.Rat).SetInt64(5)), - makeShare("b", new(big.Rat).SetInt64(10)), - makeShare("c", new(big.Rat).SetInt64(15)), - makeShare("d", new(big.Rat).SetInt64(20.0)), - makeShare("e", new(big.Rat).SetInt64(25.0)), + NewShare("a", new(big.Rat).SetInt64(5)), + NewShare("b", new(big.Rat).SetInt64(10)), + NewShare("c", new(big.Rat).SetInt64(15)), + NewShare("d", new(big.Rat).SetInt64(20.0)), + NewShare("e", new(big.Rat).SetInt64(25.0)), }, output: map[string]*big.Rat{ "a": new(big.Rat).SetFrac64(5, 75), @@ -117,11 +110,11 @@ func testPaymentMgr(t *testing.T, db *bolt.DB) { }, "zero shares": { input: []*Share{ - makeShare("a", new(big.Rat)), - makeShare("b", new(big.Rat)), - makeShare("c", new(big.Rat)), - makeShare("d", new(big.Rat)), - makeShare("e", new(big.Rat)), + NewShare("a", new(big.Rat)), + NewShare("b", new(big.Rat)), + NewShare("c", new(big.Rat)), + NewShare("d", new(big.Rat)), + NewShare("e", new(big.Rat)), }, output: nil, err: poolError(ErrDivideByZero, "division by zero"), @@ -169,19 +162,13 @@ func testPaymentMgr(t *testing.T, db *bolt.DB) { } // Ensure share A got pruned with share B remaining. - shareAID, err := shareID(xID, eightyBefore) - if err != nil { - t.Fatalf("unexpected share creation error: %v", err) - } + shareAID := shareID(xID, eightyBefore) _, err = fetchShare(db, shareAID) if err == nil { t.Fatal("expected value not found error") } - shareBID, err := shareID(yID, thirtyBefore) - if err != nil { - t.Fatalf("unexpected share creation error: %v", err) - } + shareBID := shareID(yID, thirtyBefore) _, err = fetchShare(db, shareBID) if err != nil { t.Fatalf("unexpected error fetching share B: %v", err) diff --git a/pool/share.go b/pool/share.go index 8c579de4..bf2a71f8 100644 --- a/pool/share.go +++ b/pool/share.go @@ -30,23 +30,11 @@ var ShareWeights = map[string]*big.Rat{ // shareID generates a unique share id using the provided account and time // created. -func shareID(account string, createdOn int64) ([]byte, error) { - funcName := "shareID" - buf := bytes.Buffer{} - _, err := buf.WriteString(hex.EncodeToString( - nanoToBigEndianBytes(createdOn))) - if err != nil { - desc := fmt.Sprintf("%s: unable to write created-on time: %v", - funcName, err) - return nil, poolError(ErrID, desc) - } - _, err = buf.WriteString(account) - if err != nil { - desc := fmt.Sprintf("%s: unable to write account id: %v", - funcName, err) - return nil, poolError(ErrID, desc) - } - return buf.Bytes(), nil +func shareID(account string, createdOn int64) []byte { + var buf bytes.Buffer + buf.WriteString(hex.EncodeToString(nanoToBigEndianBytes(createdOn))) + buf.WriteString(account) + return buf.Bytes() } // Share represents verifiable work performed by a pool client. @@ -57,21 +45,17 @@ type Share struct { } // NewShare creates a share with the provided account and weight. -func NewShare(account string, weight *big.Rat) (*Share, error) { - id, err := shareID(account, time.Now().UnixNano()) - if err != nil { - return nil, err - } +func NewShare(account string, weight *big.Rat) *Share { return &Share{ - UUID: string(id), + UUID: string(shareID(account, time.Now().UnixNano())), Account: account, Weight: weight, - }, nil + } } // fetchShareBucket is a helper function for getting the share bucket. func fetchShareBucket(tx *bolt.Tx) (*bolt.Bucket, error) { - funcName := "fetchShareBucket" + const funcName = "fetchShareBucket" pbkt := tx.Bucket(poolBkt) if pbkt == nil { desc := fmt.Sprintf("%s: bucket %s not found", funcName, @@ -89,7 +73,7 @@ func fetchShareBucket(tx *bolt.Tx) (*bolt.Bucket, error) { // Create persists a share to the database. func (s *Share) Create(db *bolt.DB) error { - funcName := "Share.Create" + const funcName = "Share.Create" return db.Update(func(tx *bolt.Tx) error { bkt, err := fetchShareBucket(tx) if err != nil { @@ -99,28 +83,14 @@ func (s *Share) Create(db *bolt.DB) error { if err != nil { desc := fmt.Sprintf("%s: unable to marshal share bytes: %v", funcName, err) - return poolError(ErrParse, desc) + return dbError(ErrParse, desc) } err = bkt.Put([]byte(s.UUID), sBytes) if err != nil { desc := fmt.Sprintf("%s: unable to persist share entry: %v", funcName, err) - return poolError(ErrPersistEntry, desc) + return dbError(ErrPersistEntry, desc) } return nil }) } - -// Update is not supported for shares. -func (s *Share) Update(db *bolt.DB) error { - funcName := "Share.Update" - desc := fmt.Sprintf("%s: not supported", funcName) - return dbError(ErrNotSupported, desc) -} - -// Delete is not supported for shares. -func (s *Share) Delete(db *bolt.DB) error { - funcName := "Share.Delete" - desc := fmt.Sprintf("%s: not supported", funcName) - return dbError(ErrNotSupported, desc) -} diff --git a/pool/share_test.go b/pool/share_test.go index c395bb32..440a3ca3 100644 --- a/pool/share_test.go +++ b/pool/share_test.go @@ -15,16 +15,13 @@ import ( // persistShare creates a persisted share with the provided account and share // weight. func persistShare(db *bolt.DB, account string, weight *big.Rat, createdOnNano int64) error { - id, err := shareID(account, createdOnNano) - if err != nil { - return err - } + id := shareID(account, createdOnNano) share := &Share{ UUID: string(id), Account: account, Weight: weight, } - err = share.Create(db) + err := share.Create(db) if err != nil { return err } @@ -46,36 +43,20 @@ func testShares(t *testing.T, db *bolt.DB) { } // Fetch share A and B. - aID, err := shareID(xID, shareACreatedOn) - if err != nil { - t.Fatalf("unexpected share id creation error: %v", err) - } - shareA, err := fetchShare(db, aID) + aID := shareID(xID, shareACreatedOn) + _, err = fetchShare(db, aID) if err != nil { t.Fatalf("unexpected error fetching share A: %v", err) } - bID, err := shareID(yID, shareBCreatedOn) + bID := shareID(yID, shareBCreatedOn) if err != nil { t.Fatalf("unexpected share id creation error: %v", err) } - shareB, err := fetchShare(db, bID) + _, err = fetchShare(db, bID) if err != nil { t.Fatalf("unexpected error fetching share B: %v", err) } - // Ensure shares cannot be updated. - shareA.Weight = new(big.Rat).SetFloat64(100.0) - err = shareA.Update(db) - if err == nil { - t.Fatal("expected an unsupported functionality error") - } - - // Ensure shares cannot be deleted. - err = shareB.Delete(db) - if err == nil { - t.Fatal("expected an unsupported functionality error") - } - // Empty the share bucket. err = emptyBucket(db, shareBkt) if err != nil { diff --git a/pool/upgrades.go b/pool/upgrades.go index 0ab2a0cd..34c87d73 100644 --- a/pool/upgrades.go +++ b/pool/upgrades.go @@ -43,7 +43,7 @@ var upgrades = [...]func(tx *bolt.Tx) error{ } func fetchDBVersion(tx *bolt.Tx) (uint32, error) { - funcName := "fetchDBVersion" + const funcName = "fetchDBVersion" pbkt := tx.Bucket(poolBkt) if poolBkt == nil { desc := fmt.Sprintf("%s: bucket %s not found", funcName, @@ -60,7 +60,7 @@ func fetchDBVersion(tx *bolt.Tx) (uint32, error) { } func setDBVersion(tx *bolt.Tx, newVersion uint32) error { - funcName := "setDBVersion" + const funcName = "setDBVersion" pbkt := tx.Bucket(poolBkt) if poolBkt == nil { desc := fmt.Sprintf("%s: bucket %s not found", funcName, @@ -83,7 +83,7 @@ func transactionIDUpgrade(tx *bolt.Tx) error { const oldVersion = 0 const newVersion = 1 - funcName := "transactionIDUpgrade" + const funcName = "transactionIDUpgrade" dbVersion, err := fetchDBVersion(tx) if err != nil { @@ -135,7 +135,7 @@ func transactionIDUpgrade(tx *bolt.Tx) error { if err != nil { desc := fmt.Sprintf("%s: unable to persist payment: %v", funcName, err) - return dbError(ErrParse, desc) + return dbError(ErrPersistEntry, desc) } } @@ -167,7 +167,7 @@ func transactionIDUpgrade(tx *bolt.Tx) error { if err != nil { desc := fmt.Sprintf("%s: unable to persist payment: %v", funcName, err) - return dbError(ErrParse, desc) + return dbError(ErrPersistEntry, desc) } } @@ -178,7 +178,7 @@ func shareIDUpgrade(tx *bolt.Tx) error { const oldVersion = 1 const newVersion = 2 - funcName := "shareIDUpgrade" + const funcName = "shareIDUpgrade" dbVersion, err := fetchDBVersion(tx) if err != nil { @@ -216,10 +216,7 @@ func shareIDUpgrade(tx *bolt.Tx) error { } createdOn := bigEndianBytesToNano(k) - id, err := shareID(share.Account, int64(createdOn)) - if err != nil { - return err - } + id := shareID(share.Account, int64(createdOn)) share.UUID = string(id) sBytes, err := json.Marshal(share) @@ -233,7 +230,7 @@ func shareIDUpgrade(tx *bolt.Tx) error { if err != nil { desc := fmt.Sprintf("%s: unable to persist share: %v", funcName, err) - return dbError(ErrParse, desc) + return dbError(ErrPersistEntry, desc) } toDelete = append(toDelete, k) @@ -255,7 +252,7 @@ func paymentSourceUpgrade(tx *bolt.Tx) error { const oldVersion = 2 const newVersion = 3 - funcName := "paymentSourceUpgrade" + const funcName = "paymentSourceUpgrade" dbVersion, err := fetchDBVersion(tx) if err != nil { @@ -308,10 +305,7 @@ func paymentSourceUpgrade(tx *bolt.Tx) error { return dbError(ErrParse, desc) } - key, err := paymentID(payment.Height, payment.CreatedOn, payment.Account) - if err != nil { - return err - } + key := paymentID(payment.Height, payment.CreatedOn, payment.Account) err = pmtbkt.Put(key, pBytes) if err != nil { desc := fmt.Sprintf("%s: unable to persist payment: %v", @@ -357,10 +351,7 @@ func paymentSourceUpgrade(tx *bolt.Tx) error { return dbError(ErrParse, desc) } - key, err := paymentID(payment.Height, payment.CreatedOn, payment.Account) - if err != nil { - return err - } + key := paymentID(payment.Height, payment.CreatedOn, payment.Account) err = abkt.Put(key, pBytes) if err != nil { desc := fmt.Sprintf("%s: unable to persist payment: %v", @@ -387,7 +378,7 @@ func removeTxFeeReserveUpgrade(tx *bolt.Tx) error { const oldVersion = 3 const newVersion = 4 - funcName := "removeTxFeeReserveUpgrade" + const funcName = "removeTxFeeReserveUpgrade" dbVersion, err := fetchDBVersion(tx) if err != nil { @@ -410,7 +401,7 @@ func removeTxFeeReserveUpgrade(tx *bolt.Tx) error { if err != nil { desc := fmt.Sprintf("%s: unable to remove tx fee reserve entry", funcName) - return dbError(ErrDBUpgrade, desc) + return dbError(ErrDeleteEntry, desc) } return setDBVersion(tx, newVersion) diff --git a/pool/upgrades_test.go b/pool/upgrades_test.go index 9f1e948c..52a1c7f6 100644 --- a/pool/upgrades_test.go +++ b/pool/upgrades_test.go @@ -75,20 +75,18 @@ func TestUpgrades(t *testing.T) { } func verifyV2Upgrade(t *testing.T, db *bolt.DB) { - funcName := "verifyV2Upgrade" + const funcName = "verifyV2Upgrade" err := db.View(func(tx *bolt.Tx) error { pbkt := tx.Bucket(poolBkt) if pbkt == nil { - desc := fmt.Sprintf("%s: bucket %s not found", funcName, + return fmt.Errorf("%s: bucket %s not found", funcName, string(poolBkt)) - return dbError(ErrBucketNotFound, desc) } sbkt := pbkt.Bucket(shareBkt) if sbkt == nil { - desc := fmt.Sprintf("%s: bucket %s not found", funcName, + return fmt.Errorf("%s: bucket %s not found", funcName, string(shareBkt)) - return dbError(ErrBucketNotFound, desc) } c := sbkt.Cursor() @@ -96,15 +94,13 @@ func verifyV2Upgrade(t *testing.T, db *bolt.DB) { var share Share err := json.Unmarshal(v, &share) if err != nil { - desc := fmt.Sprintf("%s: unable to unmarshal share: %v", + return fmt.Errorf("%s: unable to unmarshal share: %v", funcName, err) - return dbError(ErrParse, desc) } if string(k) != share.UUID { - desc := fmt.Sprintf("expected share id (%s) to be the same as "+ - "its key (%x)", share.UUID, k) - return dbError(ErrID, desc) + return fmt.Errorf("%s: expected share id (%s) to be the same as "+ + "its key (%x)", funcName, share.UUID, k) } } return nil @@ -115,20 +111,18 @@ func verifyV2Upgrade(t *testing.T, db *bolt.DB) { } func verifyV3Upgrade(t *testing.T, db *bolt.DB) { - funcName := "verifyV3Upgrade" + const funcName = "verifyV3Upgrade" err := db.View(func(tx *bolt.Tx) error { pbkt := tx.Bucket(poolBkt) if pbkt == nil { - desc := fmt.Sprintf("%s: bucket %s not found", + return fmt.Errorf("%s: bucket %s not found", funcName, string(poolBkt)) - return dbError(ErrBucketNotFound, desc) } sbkt := pbkt.Bucket(paymentBkt) if sbkt == nil { - desc := fmt.Sprintf("%s: bucket %s not found", + return fmt.Errorf("%s: bucket %s not found", funcName, string(paymentBkt)) - return dbError(ErrBucketNotFound, desc) } c := sbkt.Cursor() @@ -136,34 +130,27 @@ func verifyV3Upgrade(t *testing.T, db *bolt.DB) { var payment Payment err := json.Unmarshal(v, &payment) if err != nil { - desc := fmt.Sprintf("%s: unable to unmarshal payment: %v", + return fmt.Errorf("%s: unable to unmarshal payment: %v", funcName, err) - return dbError(ErrParse, desc) } - id, err := paymentID(payment.Height, payment.CreatedOn, payment.Account) - if err != nil { - return err - } + id := paymentID(payment.Height, payment.CreatedOn, payment.Account) if !bytes.Equal(k, id) { - desc := fmt.Sprintf("%s: expected payment id (%x) to be "+ + return fmt.Errorf("%s: expected payment id (%x) to be "+ "the same as its key (%x)", funcName, id, k) - return dbError(ErrID, desc) } if payment.Source == nil { - desc := fmt.Sprintf("%s: expected a non-nil "+ + return fmt.Errorf("%s: expected a non-nil "+ "payment source: %v", funcName, err) - return poolError(ErrPaymentSource, desc) } } abkt := pbkt.Bucket(paymentArchiveBkt) if sbkt == nil { - desc := fmt.Sprintf("%s: bucket %s not found", + return fmt.Errorf("%s: bucket %s not found", funcName, string(paymentArchiveBkt)) - return dbError(ErrBucketNotFound, desc) } c = abkt.Cursor() @@ -171,23 +158,19 @@ func verifyV3Upgrade(t *testing.T, db *bolt.DB) { var payment Payment err := json.Unmarshal(v, &payment) if err != nil { - return err + return fmt.Errorf("%s: unable to unmarshal payment: %v", + funcName, err) } - id, err := paymentID(payment.Height, payment.CreatedOn, payment.Account) - if err != nil { - return err - } + id := paymentID(payment.Height, payment.CreatedOn, payment.Account) if !bytes.Equal(k, id) { - desc := fmt.Sprintf("%s: expected archived payment id "+ + return fmt.Errorf("%s: expected archived payment id "+ "(%x) to be the same as its key (%x)", funcName, id, k) - return poolError(ErrID, desc) } if payment.Source == nil { - desc := fmt.Sprintf("%s: expected a non-nil payment source", + return fmt.Errorf("%s: expected a non-nil payment source", funcName) - return poolError(ErrPaymentSource, desc) } } return nil @@ -198,19 +181,17 @@ func verifyV3Upgrade(t *testing.T, db *bolt.DB) { } func verifyV4Upgrade(t *testing.T, db *bolt.DB) { - funcName := "verifyV4Upgrade" + const funcName = "verifyV4Upgrade" err := db.View(func(tx *bolt.Tx) error { pbkt := tx.Bucket(poolBkt) if pbkt == nil { - desc := fmt.Sprintf("bucket %s not found", string(poolBkt)) - return dbError(ErrBucketNotFound, desc) + return fmt.Errorf("bucket %s not found", string(poolBkt)) } v := pbkt.Get([]byte("txfeereserve")) if v != nil { - desc := fmt.Sprintf("%s: unexpected value found for "+ + return fmt.Errorf("%s: unexpected value found for "+ "txfeereserve", funcName) - return poolError(ErrValueFound, desc) } return nil })