diff --git a/api/auth/auth.go b/api/auth/auth.go index 1c092c52..c65971fb 100644 --- a/api/auth/auth.go +++ b/api/auth/auth.go @@ -8,6 +8,7 @@ import ( "bytes" "crypto/rand" "crypto/sha256" + "errors" "fmt" "io" @@ -54,13 +55,13 @@ func MustNewAuthenticateMessage(message string) *AuthenticateMessage { func NewAuthenticateFromBytes(b []byte) (*AuthenticateMessage, error) { if len(b) < nonceLength { - return nil, fmt.Errorf("authenicate message too short") + return nil, errors.New("authenicate message too short") } am := &AuthenticateMessage{} copy(am.Nonce[0:], b[:nonceLength]) am.Message = string(b[nonceLength:]) if bytes.Equal(am.Nonce[:], zeroNonce[:]) { - return nil, fmt.Errorf("invalid nonce") + return nil, errors.New("invalid nonce") } return am, nil } diff --git a/api/auth/secp256k1.go b/api/auth/secp256k1.go index 2715857f..6cf87912 100644 --- a/api/auth/secp256k1.go +++ b/api/auth/secp256k1.go @@ -7,6 +7,7 @@ package auth import ( "context" "encoding/hex" + "errors" "fmt" "reflect" @@ -215,7 +216,7 @@ func (s *Secp256k1Auth) HandshakeServer(ctx context.Context, conn protocol.APICo return fmt.Errorf("hello challenge accepted unexpected state: %v", state) } if am == nil { - return fmt.Errorf("hello challenge accepted message not set") + return errors.New("hello challenge accepted message not set") } derived, err := handleSecp256k1HelloChallengeAccepted(am, c) @@ -225,7 +226,7 @@ func (s *Secp256k1Auth) HandshakeServer(ctx context.Context, conn protocol.APICo // Exit state machine if !derived.IsEqual(s.pubKey) { - return fmt.Errorf("handleSecp256k1HelloChallengeAccepted: not the same signer") + return errors.New("handleSecp256k1HelloChallengeAccepted: not the same signer") } s.remotePubKey = derived log.Tracef("HandshakeServer complete: %x", diff --git a/api/protocol/protocol.go b/api/protocol/protocol.go index 21331dd7..6eb63da5 100644 --- a/api/protocol/protocol.go +++ b/api/protocol/protocol.go @@ -412,7 +412,7 @@ func (ac *Conn) Connect(ctx context.Context) error { log.Tracef("Connect: dialing %v", ac.serverURL) conn, _, err := websocket.Dial(connectCtx, ac.serverURL, nil) if err != nil { - return fmt.Errorf("failed to dial server: %w", err) + return fmt.Errorf("dial server: %w", err) } conn.SetReadLimit(512 * 1024) // XXX - default is 32KB defer func() { diff --git a/bitcoin/bitcoin.go b/bitcoin/bitcoin.go index ad8dd2bb..755e5c13 100644 --- a/bitcoin/bitcoin.go +++ b/bitcoin/bitcoin.go @@ -28,7 +28,7 @@ func (bh *BlockHeader) String() string { func RawBlockHeaderFromSlice(s []byte) (*BlockHeader, error) { if len(s) != 80 { - return nil, fmt.Errorf("invalid blockheader size") + return nil, errors.New("invalid blockheader size") } var bh BlockHeader copy(bh[:], s) @@ -117,14 +117,14 @@ func SignTx(btx *wire.MsgTx, payToScript []byte, privateKey *dcrsecp256k1.Privat txscript.SigHashAll, btx, 0, ) if err != nil { - return fmt.Errorf("failed to calculate signature hash: %w", err) + return fmt.Errorf("calculate signature hash: %w", err) } pubKeyBytes := publicKey.SerializeCompressed() sig := dcrecdsa.Sign(privateKey, sigHash) sigBytes := append(sig.Serialize(), byte(txscript.SigHashAll)) sb := txscript.NewScriptBuilder().AddData(sigBytes).AddData(pubKeyBytes) if btx.TxIn[0].SignatureScript, err = sb.Script(); err != nil { - return fmt.Errorf("failed to build signature script: %w", err) + return fmt.Errorf("build signature script: %w", err) } return nil } @@ -157,7 +157,7 @@ func KeysAndAddressFromHexString(s string, chainParams *chaincfg.Params) (*dcrse btcAddress, err := btcutil.NewAddressPubKey(pubKeyBytes, chainParams) if err != nil { return nil, nil, nil, - fmt.Errorf("failed to create BTC address from public key: %w", err) + fmt.Errorf("create BTC address from public key: %w", err) } return privKey, privKey.PubKey(), btcAddress.AddressPubKeyHash(), nil diff --git a/cmd/bfgd/bfgd.go b/cmd/bfgd/bfgd.go index f480eb0a..d00bf779 100644 --- a/cmd/bfgd/bfgd.go +++ b/cmd/bfgd/bfgd.go @@ -125,10 +125,10 @@ func _main() error { server, err := bfg.NewServer(cfg) if err != nil { - return fmt.Errorf("failed to create BFG server: %w", err) + return fmt.Errorf("create BFG server: %w", err) } if err = server.Run(ctx); !errors.Is(err, context.Canceled) { - return fmt.Errorf("BFG server terminated: %w", err) + return fmt.Errorf("bfg server terminated: %w", err) } return nil diff --git a/cmd/bssd/bssd.go b/cmd/bssd/bssd.go index af061e70..5a5cad19 100644 --- a/cmd/bssd/bssd.go +++ b/cmd/bssd/bssd.go @@ -100,10 +100,10 @@ func _main() error { server, err := bss.NewServer(cfg) if err != nil { - return fmt.Errorf("failed to create BSS server: %w", err) + return fmt.Errorf("create BSS server: %w", err) } if err := server.Run(ctx); !errors.Is(err, context.Canceled) { - return fmt.Errorf("BSS server terminated with error: %w", err) + return fmt.Errorf("bss server terminated: %w", err) } return nil diff --git a/cmd/btctool/bdf/bdf.go b/cmd/btctool/bdf/bdf.go index 4bc92af3..23f0e84b 100644 --- a/cmd/btctool/bdf/bdf.go +++ b/cmd/btctool/bdf/bdf.go @@ -131,12 +131,12 @@ func Header2Hex(wbh *wire.BlockHeader) (string, error) { func Hex2Header(header string) (*wire.BlockHeader, error) { blockHeader, err := hex.DecodeString(header) if err != nil { - return nil, fmt.Errorf("DecodeString: %v", err) + return nil, fmt.Errorf("decode string: %w", err) } var bh wire.BlockHeader err = bh.Deserialize(bytes.NewReader(blockHeader)) if err != nil { - return nil, fmt.Errorf("Deserialize: %v", err) + return nil, fmt.Errorf("deserialize block header: %w", err) } return &bh, nil } @@ -155,14 +155,14 @@ func writeHeight(height int, hash, dir string) error { // do nothing defer f.Close() } else { - return fmt.Errorf("Open: %v", err) + return fmt.Errorf("open file: %w", err) } } else { defer f.Close() d := json.NewDecoder(f) err = d.Decode(&lh) if err != nil { - return fmt.Errorf("%v corrupt: %v", filename, err) + return fmt.Errorf("%v corrupt: %w", filename, err) } } if lh.Height > height { @@ -171,14 +171,14 @@ func writeHeight(height int, hash, dir string) error { } fw, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { - return fmt.Errorf("OpenFile: %v", err) + return fmt.Errorf("open file: %w", err) } e := json.NewEncoder(fw) lh.Height = height lh.Hash = hash err = e.Encode(lh) if err != nil { - return fmt.Errorf("Encode: %v", err) + return fmt.Errorf("encode: %w", err) } return fw.Close() } @@ -195,7 +195,7 @@ func writeHeader(height int, hash, header, dir string) error { } f, err := os.Create(filename) if err != nil { - return fmt.Errorf("Create: %v", err) + return fmt.Errorf("create file: %w", err) } e := json.NewEncoder(f) err = e.Encode(Header{ @@ -204,7 +204,7 @@ func writeHeader(height int, hash, header, dir string) error { }) if err != nil { f.Close() - return fmt.Errorf("Encode: %v", err) + return fmt.Errorf("encode json: %w", err) } return f.Close() @@ -213,7 +213,7 @@ func writeHeader(height int, hash, header, dir string) error { func WriteHeader(height int, header, dir string) error { bh, err := Hex2Header(header) if err != nil { - return fmt.Errorf("Hex2Header: %v", err) + return fmt.Errorf("convert hex to header: %w", err) } dfm.Lock() @@ -221,11 +221,11 @@ func WriteHeader(height int, header, dir string) error { err = writeHeader(height, bh.BlockHash().String(), header, dir) if err != nil { - return fmt.Errorf("writeHeader: %v", err) + return fmt.Errorf("write header: %w", err) } err = writeHeight(height, bh.BlockHash().String(), dir) if err != nil { - return fmt.Errorf("writeHeight: %v", err) + return fmt.Errorf("write height: %w", err) } return nil } diff --git a/cmd/btctool/blockstream/blockstream.go b/cmd/btctool/blockstream/blockstream.go index 839d1e8b..7328b10a 100644 --- a/cmd/btctool/blockstream/blockstream.go +++ b/cmd/btctool/blockstream/blockstream.go @@ -38,11 +38,11 @@ type TBlock struct { func Tip(ctx context.Context) (int, error) { b, err := httpclient.Request(ctx, "GET", bsURL+"/blocks/tip/height", nil) if err != nil { - return 0, fmt.Errorf("request: %v", err) + return 0, fmt.Errorf("request: %w", err) } height, err := strconv.ParseInt(string(b), 10, 64) if err != nil { - return 0, fmt.Errorf("ParseUint: %v", err) + return 0, fmt.Errorf("parse uint: %w", err) } return int(height), nil @@ -51,11 +51,11 @@ func Tip(ctx context.Context) (int, error) { func BlockHeader(ctx context.Context, hash string) (string, error) { bh, err := httpclient.Request(ctx, "GET", bsURL+"/block/"+hash+"/header", nil) if err != nil { - return "", fmt.Errorf("request: %v", err) + return "", fmt.Errorf("request: %w", err) } _, err = hex.DecodeString(string(bh)) if err != nil { - return "", fmt.Errorf("DecodeString: %v", err) + return "", fmt.Errorf("decode hex: %w", err) } return string(bh), nil } @@ -63,11 +63,11 @@ func BlockHeader(ctx context.Context, hash string) (string, error) { func BlockHeightHash(ctx context.Context, height string) (string, error) { bh, err := httpclient.Request(ctx, "GET", bsURL+"/block-height/"+height, nil) if err != nil { - return "", fmt.Errorf("request: %v", err) + return "", fmt.Errorf("request: %w", err) } _, err = hex.DecodeString(string(bh)) if err != nil { - return "", fmt.Errorf("DecodeString: %v", err) + return "", fmt.Errorf("decode hex: %w", err) } return string(bh), nil } @@ -79,7 +79,7 @@ func Block(ctx context.Context, hash string, raw bool) (string, error) { } b, err := httpclient.Request(ctx, "GET", bsURL+"/block/"+hash+suffix, nil) if err != nil { - return "", fmt.Errorf("request: %v", err) + return "", fmt.Errorf("request: %w", err) } if raw { return hex.EncodeToString(b), nil @@ -91,7 +91,7 @@ func BlockBytes(ctx context.Context, hash string) ([]byte, error) { suffix := "/raw" b, err := httpclient.Request(ctx, "GET", bsURL+"/block/"+hash+suffix, nil) if err != nil { - return nil, fmt.Errorf("request: %v", err) + return nil, fmt.Errorf("request: %w", err) } return b, nil } diff --git a/cmd/btctool/btctool.go b/cmd/btctool/btctool.go index 27155357..67257fa8 100644 --- a/cmd/btctool/btctool.go +++ b/cmd/btctool/btctool.go @@ -8,6 +8,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "flag" "fmt" "math/rand" @@ -94,7 +95,7 @@ func (p *peer) connect(ctx context.Context) error { p.mtx.Lock() if p.conn != nil { p.mtx.Unlock() - return fmt.Errorf("already open") + return errors.New("already open") } p.mtx.Unlock() // XXX this races @@ -117,7 +118,7 @@ func (p *peer) close() error { if p.conn != nil { return p.conn.Close() } - return fmt.Errorf("already closed") + return errors.New("already closed") } func (p *peer) write(msg wire.Message) error { @@ -144,17 +145,17 @@ func (p *peer) handshake(ctx context.Context) error { msg := wire.NewMsgVersion(us, them, uint64(rand.Int63()), 0) err := p.write(msg) if err != nil { - return fmt.Errorf("could not write version message: %v", err) + return fmt.Errorf("could not write version message: %w", err) } // 2. receive version rmsg, err := p.read() if err != nil { - return fmt.Errorf("could not read version message: %v", err) + return fmt.Errorf("could not read version message: %w", err) } v, ok := rmsg.(*wire.MsgVersion) if !ok { - return fmt.Errorf("expected version message") + return errors.New("expected version message") } p.remoteVersion = v @@ -162,19 +163,19 @@ func (p *peer) handshake(ctx context.Context) error { if v.ProtocolVersion >= 70016 { err = p.write(wire.NewMsgSendAddrV2()) if err != nil { - return fmt.Errorf("could not send sendaddrv2: %v", err) + return fmt.Errorf("could not send sendaddrv2: %w", err) } } // 4. send verack err = p.write(wire.NewMsgVerAck()) if err != nil { - return fmt.Errorf("could not send verack: %v", err) + return fmt.Errorf("could not send verack: %w", err) } for count := 0; count < 3; count++ { msg, err := p.read() - if err == wire.ErrUnknownMessage { + if errors.Is(err, wire.ErrUnknownMessage) { continue } else if err != nil { return err @@ -191,7 +192,7 @@ func (p *peer) handshake(ctx context.Context) error { } } - return fmt.Errorf("handshake failed") + return errors.New("handshake failed") } func handlePing(p *peer, msg *wire.MsgPing) { @@ -216,7 +217,7 @@ func downloadBlock(p *peer, height int, hash chainhash.Hash) error { }) err := p.write(getData) if err != nil { - return fmt.Errorf("could not write get block message: %v", err) + return fmt.Errorf("could not write get block message: %w", err) } fmt.Printf("wrote get block %v\n", hash) @@ -246,10 +247,10 @@ func handleBlock(p *peer, msg *wire.MsgBlock) { } func btcConnect(ctx context.Context, btcNet string) error { - //ips, err := net.LookupIP("seed.bitcoin.sipa.be") - //if err != nil { + // ips, err := net.LookupIP("seed.bitcoin.sipa.be") + // if err != nil { // return err - //} + // } mainnetPort := "8333" testnetPort := "18333" @@ -273,17 +274,17 @@ func btcConnect(ctx context.Context, btcNet string) error { p, err := NewPeer(wireNet, "140.238.169.133"+port) if err != nil { - return fmt.Errorf("new peer: %v", err) + return fmt.Errorf("new peer: %w", err) } err = p.connect(ctx) if err != nil { - return fmt.Errorf("connect: %v", err) + return fmt.Errorf("connect: %w", err) } err = p.handshake(ctx) if err != nil { - return fmt.Errorf("connect: %v", err) + return fmt.Errorf("connect: %w", err) } fmt.Printf("handshake complete with: %v\n", p.address) @@ -306,7 +307,7 @@ func btcConnect(ctx context.Context, btcNet string) error { } msg, err := p.read() - if err == wire.ErrUnknownMessage { + if errors.Is(err, wire.ErrUnknownMessage) { // skip unknown continue } else if err != nil { @@ -332,18 +333,18 @@ func btcConnect(ctx context.Context, btcNet string) error { } } - //fmt.Printf("waiting for exit\n") - //<-ctx.Done() - //return nil + // fmt.Printf("waiting for exit\n") + // <-ctx.Done() + // return nil - //peers := make(map[string]*peer, len(ips)) - //ips = []net.IP{ + // peers := make(map[string]*peer, len(ips)) + // ips = []net.IP{ // net.ParseIP("140.238.169.133"), // // net.ParseIP("84.250.91.34"), // // net.ParseIP("3.14.15.90"), // // net.ParseIP("104.182.210.230"), - //} - //for _, ip := range ips { + // } + // for _, ip := range ips { // address := ip.To4() // if address == nil { // continue @@ -440,9 +441,9 @@ func btcConnect(ctx context.Context, btcNet string) error { // } // } // }(p) - //} + // } - //<-ctx.Done() + // <-ctx.Done() // return nil } @@ -462,7 +463,7 @@ func StoreBlockHeaders(ctx context.Context, endHeight, blockCount int, dir strin func parseArgs(args []string) (string, map[string]string, error) { if len(args) < 1 { flag.Usage() - return "", nil, fmt.Errorf("action required") + return "", nil, errors.New("action required") } action := args[0] @@ -503,18 +504,18 @@ func _main() error { fmt.Fprintf(f, " tip - retrieve tip height\n") } - //var ( + // var ( // endHeight, blockCount int // downloadDir string - //) - //flag.IntVar(&endHeight, "startblock", -1, "Height to start downloading, negative means start at current max height") - //flag.IntVar(&blockCount, "count", -1024, "number of blocks to download, negative goes backwards from height") - //flag.StringVar(&downloadDir, "downloaddir", "", "Directory to download block header and data to. Leave empty to dump to stdout.") + // ) + // flag.IntVar(&endHeight, "startblock", -1, "Height to start downloading, negative means start at current max height") + // flag.IntVar(&blockCount, "count", -1024, "number of blocks to download, negative goes backwards from height") + // flag.StringVar(&downloadDir, "downloaddir", "", "Directory to download block header and data to. Leave empty to dump to stdout.") flag.Parse() err := loggo.ConfigureLoggers("info") // XXX make flag if err != nil { - return fmt.Errorf("ConfigureLoggers: %v", err) + return fmt.Errorf("configure loggers: %w", err) } ctx, cancel := context.WithCancel(context.Background()) @@ -529,7 +530,7 @@ func _main() error { case "standardscript": address := args["address"] if address == "" { - return fmt.Errorf("address: must be set") + return errors.New("address: must be set") } var ( a btcutil.Address @@ -556,22 +557,22 @@ func _main() error { if jsonSet == "1" || strings.ToLower(jsonSet) == "true" { raw = false if wireSpew { - return fmt.Errorf("wire and json may not be both set") + return errors.New("wire and json may not be both set") } } hash := args["hash"] if hash == "" { - return fmt.Errorf("hash: must be set") + return errors.New("hash: must be set") } var b string b, err = blockstream.Block(ctx, hash, raw) if err == nil { if wireSpew { - //eb, err := hex.DecodeString(strings.Trim(b, "\n")) - //if err != nil { + // eb, err := hex.DecodeString(strings.Trim(b, "\n")) + // if err != nil { // return err - //} - //fmt.Printf("%v", spew.Sdump(eb)) + // } + // fmt.Printf("%v", spew.Sdump(eb)) blk, err := parseBlockFromHex(b) if err != nil { @@ -585,7 +586,7 @@ func _main() error { case "blockheader": hash := args["hash"] if hash == "" { - return fmt.Errorf("hash: must be set") + return errors.New("hash: must be set") } var bh string bh, err = blockstream.BlockHeader(ctx, hash) @@ -595,7 +596,7 @@ func _main() error { case "blockheighthash": height := args["height"] if height == "" { - return fmt.Errorf("height: must be set") + return errors.New("height: must be set") } var bh string bh, err = blockstream.BlockHeightHash(ctx, height) @@ -615,7 +616,7 @@ func _main() error { case "parseblock": filename := args["filename"] if filename == "" { - return fmt.Errorf("filename: must be set") + return errors.New("filename: must be set") } var block *btcutil.Block block, err = parseBlock(ctx, filename) @@ -628,12 +629,12 @@ func _main() error { downloadDir := filepath.Join("~/.mocksicle", bdf.DefaultDataDir) downloadDir, err = homedir.Expand(downloadDir) if err != nil { - return fmt.Errorf("invalid directory: %v", err) + return fmt.Errorf("invalid directory: %w", err) } err = os.MkdirAll(downloadDir, 0o700) if err != nil { - return fmt.Errorf("MkdirAll: %v", err) + return fmt.Errorf("mkdir: %w", err) } blockCount := int(1024) @@ -641,7 +642,7 @@ func _main() error { if count != "" { bc, err := strconv.ParseInt(count, 10, 64) if err != nil { - return fmt.Errorf("count: %v", err) + return fmt.Errorf("count: %w", err) } if bc < 0 { return fmt.Errorf("count must not be negative: %v", bc) @@ -655,17 +656,17 @@ func _main() error { if end == "" { endHeight, err = blockstream.Tip(ctx) if err != nil { - return fmt.Errorf("tip: %v", err) + return fmt.Errorf("tip: %w", err) } } else { e, err := strconv.ParseInt(end, 10, 64) if err != nil { - return fmt.Errorf("end: %v", err) + return fmt.Errorf("end: %w", err) } if e < 0 { bh, err := blockstream.Tip(ctx) if err != nil { - return fmt.Errorf("tip: %v", err) + return fmt.Errorf("tip: %w", err) } e = int64(bh) + e if e < 0 { diff --git a/cmd/btctool/btctool/btctool.go b/cmd/btctool/btctool/btctool.go index 24caf5ce..3bea68a3 100644 --- a/cmd/btctool/btctool/btctool.go +++ b/cmd/btctool/btctool/btctool.go @@ -19,18 +19,18 @@ var log = loggo.GetLogger("btctool") func GetAndStoreBlockHeader(ctx context.Context, height int, dir string) (string, error) { hash, err := blockstream.BlockHeightHash(ctx, fmt.Sprintf("%v", height)) if err != nil { - return "", fmt.Errorf("BlockHeightHash %v: %v", height, err) + return "", fmt.Errorf("retrieve block by hash %v: %w", height, err) } header, err := blockstream.BlockHeader(ctx, hash) if err != nil { - return "", fmt.Errorf("BlockHeader %v: %v", hash, err) + return "", fmt.Errorf("retrieve block header %v: %w", hash, err) } // Write header err = bdf.WriteHeader(height, header, dir) if err != nil { - return "", fmt.Errorf("WriteHeight: %v", err) + return "", fmt.Errorf("write header: %w", err) } return hash, nil diff --git a/cmd/btctool/httpclient/httpclient.go b/cmd/btctool/httpclient/httpclient.go index 5e4b6d0b..5d4f52f9 100644 --- a/cmd/btctool/httpclient/httpclient.go +++ b/cmd/btctool/httpclient/httpclient.go @@ -19,7 +19,7 @@ func Request(ctx context.Context, method, url string, body any) ([]byte, error) if body != nil { b, err := json.Marshal(body) if err != nil { - return nil, fmt.Errorf("marshal body: %v", err) + return nil, fmt.Errorf("marshal body: %w", err) } r = bytes.NewReader(b) } @@ -27,11 +27,11 @@ func Request(ctx context.Context, method, url string, body any) ([]byte, error) for retry := 1; ; retry++ { req, err := http.NewRequestWithContext(ctx, method, url, r) if err != nil { - return nil, fmt.Errorf("NewRequestWithContext: %v", err) + return nil, fmt.Errorf("create request: %w", err) } resp, err := c.Do(req) if err != nil { - return nil, fmt.Errorf("Do: %v", err) + return nil, fmt.Errorf("request: %w", err) } defer resp.Body.Close() diff --git a/cmd/hemictl/hemictl.go b/cmd/hemictl/hemictl.go index 8006c671..84e6eadf 100644 --- a/cmd/hemictl/hemictl.go +++ b/cmd/hemictl/hemictl.go @@ -166,7 +166,7 @@ func bfgdb() error { func parseArgs(args []string) (string, map[string]string, error) { if len(args) < 1 { flag.Usage() - return "", nil, fmt.Errorf("action required") + return "", nil, errors.New("action required") } action := args[0] @@ -196,10 +196,10 @@ func tbcdb() error { } // special commands - //switch action { - //case "crossreference": + // switch action { + // case "crossreference": // return crossReference(ctx) - //} + // } // create fake service to call crawler cfg := tbc.NewDefaultConfig() @@ -227,7 +227,7 @@ func tbcdb() error { case "blockheaderbyhash": hash := args["hash"] if hash == "" { - return fmt.Errorf("hash: must be set") + return errors.New("hash: must be set") } ch, err := chainhash.NewHashFromStr(hash) if err != nil { @@ -253,7 +253,7 @@ func tbcdb() error { case "blockheadersbyheight": height := args["height"] if height == "" { - return fmt.Errorf("height: must be set") + return errors.New("height: must be set") } h, err := strconv.ParseUint(height, 10, 64) if err != nil { @@ -287,7 +287,7 @@ func tbcdb() error { case "blockbyhash": hash := args["hash"] if hash == "" { - return fmt.Errorf("hash: must be set") + return errors.New("hash: must be set") } ch, err := chainhash.NewHashFromStr(hash) if err != nil { @@ -302,7 +302,7 @@ func tbcdb() error { case "deletemetadata": key := args["key"] if key == "" { - return fmt.Errorf("key: must be set") + return errors.New("key: must be set") } s.DBClose() @@ -351,9 +351,9 @@ func tbcdb() error { defer db.Close() prefix := args["prefix"] if len(prefix) > 1 { - return fmt.Errorf("prefix must be one byte") + return errors.New("prefix must be one byte") } else if len(prefix) == 1 && !(prefix[0] == 'h' || prefix[0] == 'u') { - return fmt.Errorf("prefix must be h or u") + return errors.New("prefix must be h or u") } pool := db.DB() outsDB := pool[ldb.OutputsDB] @@ -366,7 +366,7 @@ func tbcdb() error { case "feesbyheight": height := args["height"] if height == "" { - return fmt.Errorf("height: must be set") + return errors.New("height: must be set") } h, err := strconv.ParseInt(height, 10, 64) if err != nil { @@ -478,7 +478,7 @@ func tbcdb() error { case "blocksbytxid": txid := args["txid"] if txid == "" { - return fmt.Errorf("txid: must be set") + return errors.New("txid: must be set") } chtxid, err := chainhash.NewHashFromStr(txid) if err != nil { @@ -498,7 +498,7 @@ func tbcdb() error { case "spendoutputsbytxid": txid := args["txid"] if txid == "" { - return fmt.Errorf("txid: must be set") + return errors.New("txid: must be set") } chtxid, err := chainhash.NewHashFromStr(txid) if err != nil { @@ -518,7 +518,7 @@ func tbcdb() error { case "scripthashbyoutpoint": txid := args["txid"] if txid == "" { - return fmt.Errorf("txid: must be set") + return errors.New("txid: must be set") } chtxid, err := chainhash.NewHashFromStr(txid) if err != nil { @@ -529,7 +529,7 @@ func tbcdb() error { index := args["index"] if index == "" { - return fmt.Errorf("index: must be set") + return errors.New("index: must be set") } idx, err := strconv.ParseUint(index, 10, 32) if err != nil { @@ -546,9 +546,9 @@ func tbcdb() error { address := args["address"] hash := args["hash"] if address == "" && hash == "" { - return fmt.Errorf("hash or address: must be set") + return errors.New("hash or address: must be set") } else if address != "" && hash != "" { - return fmt.Errorf("hash or address: both set") + return errors.New("hash or address: both set") } var hh [32]byte @@ -586,9 +586,9 @@ func tbcdb() error { start := args["start"] if address == "" && hash == "" { - return fmt.Errorf("hash or address: must be set") + return errors.New("hash or address: must be set") } else if address != "" && hash != "" { - return fmt.Errorf("hash or address: both set") + return errors.New("hash or address: both set") } if count == "" { @@ -875,7 +875,7 @@ func printJSON(where io.Writer, indent string, payload any) error { func _main() error { if len(os.Args) < 2 { usage() - return fmt.Errorf("not enough parameters") + return errors.New("not enough parameters") } if err := config.Parse(cm); err != nil { diff --git a/cmd/keygen/keygen.go b/cmd/keygen/keygen.go index 57321273..0975eeee 100644 --- a/cmd/keygen/keygen.go +++ b/cmd/keygen/keygen.go @@ -7,6 +7,7 @@ package main import ( "encoding/hex" "encoding/json" + "errors" "flag" "fmt" "os" @@ -48,12 +49,12 @@ func _main() error { case *secp256k1KeyPair: privKey, err := dcrsecpk256k1.GeneratePrivateKey() if err != nil { - return fmt.Errorf("failed to generate secp256k1 private key: %w", err) + return fmt.Errorf("generate secp256k1 private key: %w", err) } btcAddress, err := btcutil.NewAddressPubKey(privKey.PubKey().SerializeCompressed(), btcChainParams) if err != nil { - return fmt.Errorf("failed to create BTC address from public key: %v", + return fmt.Errorf("create BTC address from public key: %v", err) } hash := btcAddress.AddressPubKeyHash().String() @@ -89,7 +90,7 @@ func _main() error { default: usage() - return fmt.Errorf("invalid flag") + return errors.New("invalid flag") } return nil diff --git a/cmd/popmd/popmd.go b/cmd/popmd/popmd.go index e38c50c7..3917f0f8 100644 --- a/cmd/popmd/popmd.go +++ b/cmd/popmd/popmd.go @@ -110,10 +110,10 @@ func _main() error { miner, err := popm.NewMiner(cfg) if err != nil { - return fmt.Errorf("failed to create POP miner: %w", err) + return fmt.Errorf("create POP miner: %w", err) } if err := miner.Run(ctx); !errors.Is(err, context.Canceled) { - return fmt.Errorf("POP miner terminated: %w", err) + return fmt.Errorf("pop miner terminated: %w", err) } return nil diff --git a/cmd/tbcd/tbcd.go b/cmd/tbcd/tbcd.go index ceb58506..0f8c5477 100644 --- a/cmd/tbcd/tbcd.go +++ b/cmd/tbcd/tbcd.go @@ -6,6 +6,7 @@ package main import ( "context" + "errors" "fmt" "os" "os/signal" @@ -124,7 +125,7 @@ func _main() error { server, err := tbc.NewServer(cfg) if err != nil { - return fmt.Errorf("Failed to create tbc server: %v", err) + return fmt.Errorf("create tbc server: %w", err) } // XXX remove, this is an illustration of calling the direct API of server // go func() { @@ -153,9 +154,9 @@ func _main() error { // } // log.Infof("height %v headers %v", height, spew.Sdump(bhbh)) // } - //}() - if err := server.Run(ctx); err != context.Canceled { - return fmt.Errorf("tbc server terminated: %v", err) + // }() + if err := server.Run(ctx); !errors.Is(err, context.Canceled) { + return fmt.Errorf("tbc server terminated: %w", err) } return nil diff --git a/config/config.go b/config/config.go index d4012c6b..04c2dcdd 100644 --- a/config/config.go +++ b/config/config.go @@ -5,6 +5,7 @@ package config import ( + "errors" "fmt" "io" "os" @@ -37,7 +38,7 @@ func Parse(c CfgMap) error { for k, v := range c { // Make sure v.Value is a pointer if reflect.TypeOf(v.Value).Kind() != reflect.Pointer { - return fmt.Errorf("value must be a pointer") + return errors.New("value must be a pointer") } // Make sure we are pointing to the same type if reflect.TypeOf(v.Value).Elem() != reflect.TypeOf(v.DefaultValue) { diff --git a/database/bfgd/postgres/postgres.go b/database/bfgd/postgres/postgres.go index 043d062f..91552b71 100644 --- a/database/bfgd/postgres/postgres.go +++ b/database/bfgd/postgres/postgres.go @@ -151,27 +151,28 @@ func (p *pgdb) L2KeystonesInsert(ctx context.Context, l2ks []bfgd.L2Keystone) er v.L1BlockNumber, v.L2BlockNumber, v.ParentEPHash, v.PrevKeystoneEPHash, v.StateRoot, v.EPHash, v.Version) if err != nil { - if err, ok := err.(*pq.Error); ok && err.Code.Class().Name() == "integrity_constraint_violation" { - switch err.Constraint { + var pgErr *pq.Error + if errors.As(err, &pgErr) && pgErr.Code.Class().Name() == "integrity_constraint_violation" { + switch pgErr.Constraint { case "l2_keystone_abrev_hash_length", "state_root_length", "parent_ep_hash_length", "prev_keystone_ep_hash_length", "ep_hash_length": - return database.ValidationError(err.Error()) + return database.ValidationError(pgErr.Error()) } - log.Errorf("integrity violation occurred: %s", err.Constraint) - return database.DuplicateError(fmt.Sprintf("constraint error: %s", err)) + log.Errorf("integrity violation occurred: %s", pgErr.Constraint) + return database.DuplicateError(fmt.Sprintf("constraint error: %s", pgErr)) } - return fmt.Errorf("failed to insert l2 keystone: %w", err) + return fmt.Errorf("insert l2 keystone: %w", err) } rows, err := result.RowsAffected() if err != nil { - return fmt.Errorf("failed to insert l2 keystone rows affected: %w", err) + return fmt.Errorf("insert l2 keystone rows affected: %w", err) } if rows < 1 { - return fmt.Errorf("failed to insert l2 keystone rows: %v", rows) + return fmt.Errorf("insert l2 keystone rows: %v", rows) } } @@ -283,17 +284,18 @@ func (p *pgdb) BtcBlockInsert(ctx context.Context, bb *bfgd.BtcBlock) error { result, err := p.db.ExecContext(ctx, qBtcBlockInsert, bb.Hash, bb.Header, bb.Height) if err != nil { - if err, ok := err.(*pq.Error); ok && err.Code.Class().Name() == "integrity_constraint_violation" { - return database.DuplicateError(fmt.Sprintf("duplicate btc block entry: %s", err)) + var pgErr *pq.Error + if errors.As(err, &pgErr) && pgErr.Code.Class().Name() == "integrity_constraint_violation" { + return database.DuplicateError(fmt.Sprintf("duplicate btc block entry: %s", pgErr)) } - return fmt.Errorf("failed to insert btc block: %w", err) + return fmt.Errorf("insert btc block: %w", err) } rows, err := result.RowsAffected() if err != nil { - return fmt.Errorf("failed to insert btc block rows affected: %w", err) + return fmt.Errorf("insert btc block rows affected: %w", err) } if rows < 1 { - return fmt.Errorf("failed to insert btc block rows: %v", rows) + return fmt.Errorf("insert btc block rows: %v", rows) } return nil @@ -357,22 +359,23 @@ func (p *pgdb) PopBasisInsertPopMFields(ctx context.Context, pb *bfgd.PopBasis) result, err := p.db.ExecContext(ctx, qPopBlockInsert, pb.BtcTxId, pb.BtcRawTx, pb.L2KeystoneAbrevHash, pb.PopMinerPublicKey) if err != nil { - if err, ok := err.(*pq.Error); ok && err.Code.Class().Name() == "integrity_constraint_violation" { - switch err.Constraint { + var pgErr *pq.Error + if errors.As(err, &pgErr) && pgErr.Code.Class().Name() == "integrity_constraint_violation" { + switch pgErr.Constraint { case "btc_txid_length": return database.ValidationError("BtcTxId must be length 32") default: - return database.DuplicateError(fmt.Sprintf("duplicate pop block entry: %s", err.Error())) + return database.DuplicateError(fmt.Sprintf("duplicate pop block entry: %s", pgErr.Error())) } } - return fmt.Errorf("failed to insert pop block: %w", err) + return fmt.Errorf("insert pop block: %w", err) } rows, err := result.RowsAffected() if err != nil { - return fmt.Errorf("failed to insert pop block rows affected: %w", err) + return fmt.Errorf("insert pop block rows affected: %w", err) } if rows < 1 { - return fmt.Errorf("failed to insert pop block rows: %v", rows) + return fmt.Errorf("insert pop block rows: %v", rows) } return nil @@ -409,20 +412,21 @@ func (p *pgdb) PopBasisUpdateBTCFields(ctx context.Context, pb *bfgd.PopBasis) ( pb.BtcTxIndex, pb.BtcTxId, ) if err != nil { - if err, ok := err.(*pq.Error); ok && err.Code.Class().Name() == "integrity_constraint_violation" { - switch err.Constraint { + var pgErr *pq.Error + if errors.As(err, &pgErr) && pgErr.Code.Class().Name() == "integrity_constraint_violation" { + switch pgErr.Constraint { case "pop_txid_length": return 0, database.ValidationError("PopTxId must be length 32") default: - return 0, database.DuplicateError(fmt.Sprintf("duplicate pop block entry: %s", err.Error())) + return 0, database.DuplicateError(fmt.Sprintf("duplicate pop block entry: %s", pgErr.Error())) } } - return 0, fmt.Errorf("failed to insert pop block: %w", err) + return 0, fmt.Errorf("insert pop block: %w", err) } rows, err := result.RowsAffected() if err != nil { - return 0, fmt.Errorf("failed to insert pop block rows affected: %w", err) + return 0, fmt.Errorf("insert pop block rows affected: %w", err) } return rows, nil @@ -455,24 +459,25 @@ func (p *pgdb) PopBasisInsertFull(ctx context.Context, pb *bfgd.PopBasis) error pb.BtcHeaderHash, pb.BtcTxIndex, string(b), pb.PopTxId, pb.L2KeystoneAbrevHash, pb.PopMinerPublicKey) if err != nil { - if err, ok := err.(*pq.Error); ok && err.Code.Class().Name() == "integrity_constraint_violation" { - switch err.Constraint { + var pgErr *pq.Error + if errors.As(err, &pgErr) && pgErr.Code.Class().Name() == "integrity_constraint_violation" { + switch pgErr.Constraint { case "btc_txid_length": return database.ValidationError("BtcTxId must be length 32") case "pop_txid_length": return database.ValidationError("PopTxId must be length 32") default: - return database.DuplicateError(fmt.Sprintf("duplicate pop block entry: %s", err.Error())) + return database.DuplicateError(fmt.Sprintf("duplicate pop block entry: %s", pgErr.Error())) } } - return fmt.Errorf("failed to insert pop block: %w", err) + return fmt.Errorf("insert pop block: %w", err) } rows, err := result.RowsAffected() if err != nil { - return fmt.Errorf("failed to insert pop block rows affected: %w", err) + return fmt.Errorf("insert pop block rows affected: %w", err) } if rows < 1 { - return fmt.Errorf("failed to insert pop block rows: %v", rows) + return fmt.Errorf("insert pop block rows: %v", rows) } return nil @@ -926,8 +931,8 @@ func (p *pgdb) AccessPublicKeyInsert(ctx context.Context, publicKey *bfgd.Access _, err := p.db.ExecContext(ctx, sql, publicKey.PublicKey) if err != nil { - pqErr := err.(*pq.Error) - if pqErr.Constraint == "access_public_keys_pkey" { + var pqErr *pq.Error + if errors.As(err, &pqErr) && pqErr.Constraint == "access_public_keys_pkey" { return database.DuplicateError("public key already exists") } diff --git a/database/database.go b/database/database.go index a77df1f1..173ccfc2 100644 --- a/database/database.go +++ b/database/database.go @@ -200,7 +200,7 @@ func (bi *BigInt) Scan(value interface{}) error { } nbi := new(big.Int) if _, ok := nbi.SetString(string(b), 10); !ok { - return fmt.Errorf("failed to convert %q to BigInt", string(b)) + return fmt.Errorf("convert %q to BigInt", string(b)) } bi.Int = nbi return nil diff --git a/database/level/level.go b/database/level/level.go index f226b2a7..38207b67 100644 --- a/database/level/level.go +++ b/database/level/level.go @@ -90,14 +90,14 @@ func (l *Database) RegisterNotification(ctx context.Context, n database.Notifica log.Tracef("RegisterNotification") defer log.Tracef("RegisterNotification exit") - return fmt.Errorf("RegisterNotification") + return errors.New("unsupported") } func (l *Database) UnregisterNotification(n database.NotificationName) error { log.Tracef("UnregisterNotification") defer log.Tracef("UnregisterNotification exit") - return fmt.Errorf("UnregisterNotification") + return errors.New("unsupported") } func (l *Database) openDB(name string, options *opt.Options) error { diff --git a/database/tbcd/database.go b/database/tbcd/database.go index 5375e20b..adb053f6 100644 --- a/database/tbcd/database.go +++ b/database/tbcd/database.go @@ -9,6 +9,7 @@ import ( "context" "encoding/binary" "encoding/hex" + "errors" "fmt" "time" @@ -277,7 +278,7 @@ func NewTxId(x [32]byte) (txId TxId) { func NewTxIdFromBytes(x []byte) (txId TxId, err error) { if len(x) != 32 { - err = fmt.Errorf("invalid transaction hash length") + err = errors.New("invalid transaction hash length") return } copy(txId[:], x[:]) @@ -303,7 +304,7 @@ func NewBlockHash(x [32]byte) (blockHash BlockHash) { func NewBlockHashFromBytes(x []byte) (blockHash BlockHash, err error) { if len(x) != 32 { - err = fmt.Errorf("invalid block hash length") + err = errors.New("invalid block hash length") return } copy(blockHash[:], x[:]) @@ -325,7 +326,7 @@ func NewScriptHash(x [32]byte) (scriptHash ScriptHash) { func NewScriptHashFromBytes(x []byte) (scriptHash ScriptHash, err error) { if len(x) != 32 { - err = fmt.Errorf("invalid script hash length") + err = errors.New("invalid script hash length") return } copy(scriptHash[:], x[:]) diff --git a/database/tbcd/level/level.go b/database/tbcd/level/level.go index b25fc531..6fec489b 100644 --- a/database/tbcd/level/level.go +++ b/database/tbcd/level/level.go @@ -129,7 +129,7 @@ func (l *ldb) MetadataGet(ctx context.Context, key []byte) ([]byte, error) { mdDB := l.pool[level.MetadataDB] v, err := mdDB.Get(key, nil) - if err == leveldb.ErrNotFound { + if errors.Is(err, leveldb.ErrNotFound) { return nil, database.NotFoundError(fmt.Sprintf("key not found: %v", string(key))) } @@ -155,7 +155,7 @@ func (l *ldb) BlockHeaderByHash(ctx context.Context, hash []byte) (*tbcd.BlockHe bhsDB := l.pool[level.BlockHeadersDB] ebh, err := bhsDB.Get(hash, nil) if err != nil { - if err == leveldb.ErrNotFound { + if errors.Is(err, leveldb.ErrNotFound) { return nil, database.NotFoundError(fmt.Sprintf("block header not found: %x", hash)) } return nil, fmt.Errorf("block header get: %w", err) @@ -184,7 +184,7 @@ func (l *ldb) BlockHeadersByHeight(ctx context.Context, height uint64) ([]tbcd.B } bh, err := l.BlockHeaderByHash(ctx, hash) if err != nil { - return nil, fmt.Errorf("headers by height: %v", err) + return nil, fmt.Errorf("headers by height: %w", err) } bhs = append(bhs, *bh) } @@ -208,7 +208,7 @@ func (l *ldb) BlockHeadersBest(ctx context.Context) ([]tbcd.BlockHeader, error) // Get last record ebh, err := bhsDB.Get([]byte(bhsLastKey), nil) if err != nil { - if err == leveldb.ErrNotFound { + if errors.Is(err, leveldb.ErrNotFound) { return []tbcd.BlockHeader{}, nil } return nil, fmt.Errorf("block headers best: %w", err) @@ -271,7 +271,7 @@ func (l *ldb) BlockHeadersInsert(ctx context.Context, bhs []tbcd.BlockHeader) er defer log.Tracef("BlockHeadersInsert exit") if len(bhs) == 0 { - return fmt.Errorf("block headers insert: no block headers to insert") + return errors.New("block headers insert: no block headers to insert") } // block headers @@ -284,7 +284,7 @@ func (l *ldb) BlockHeadersInsert(ctx context.Context, bhs []tbcd.BlockHeader) er // Make sure we are not inserting the same blocks has, err := bhsTx.Has(bhs[0].Hash, nil) if err != nil { - return fmt.Errorf("block headers insert has: %v", err) + return fmt.Errorf("block headers insert has: %w", err) } if has { return database.DuplicateError("block headers insert duplicate") @@ -460,7 +460,7 @@ func (l *ldb) BlockInsert(ctx context.Context, b *tbcd.Block) (int64, error) { bhsDB := l.pool[level.BlockHeadersDB] ebh, err := bhsDB.Get(b.Hash, nil) if err != nil { - if err == leveldb.ErrNotFound { + if errors.Is(err, leveldb.ErrNotFound) { return -1, database.NotFoundError(fmt.Sprintf( "block insert block header not found: %v", b.Hash)) @@ -481,13 +481,13 @@ func (l *ldb) BlockInsert(ctx context.Context, b *tbcd.Block) (int64, error) { bDB := l.pool[level.BlocksDB] has, err := bDB.Has(b.Hash, nil) if err != nil { - return -1, fmt.Errorf("block insert has: %v", err) + return -1, fmt.Errorf("block insert has: %w", err) } if !has { // Insert block since we do not have it yet err = bDB.Put(b.Hash, b.Block, nil) if err != nil { - return -1, fmt.Errorf("blocks insert put: %v", err) + return -1, fmt.Errorf("blocks insert put: %w", err) } } @@ -501,10 +501,10 @@ func (l *ldb) BlockInsert(ctx context.Context, b *tbcd.Block) (int64, error) { err = bmDB.Delete(key, nil) if err != nil { // Ignore not found - if err == leveldb.ErrNotFound { + if errors.Is(err, leveldb.ErrNotFound) { log.Errorf("block insert delete from missing: %v", err) } else { - return -1, fmt.Errorf("block insert delete from missing: %v", err) + return -1, fmt.Errorf("block insert delete from missing: %w", err) } } // XXX think about Height type; why are we forced to mix types? @@ -518,7 +518,7 @@ func (l *ldb) BlockByHash(ctx context.Context, hash []byte) (*tbcd.Block, error) bDB := l.pool[level.BlocksDB] eb, err := bDB.Get(hash, nil) if err != nil { - if err == leveldb.ErrNotFound { + if errors.Is(err, leveldb.ErrNotFound) { ch, _ := chainhash.NewHash(hash) return nil, database.NotFoundError(fmt.Sprintf("block not found: %v", ch)) } diff --git a/database/tbcd/level/level_test.go b/database/tbcd/level/level_test.go index 2058ed75..219afb9c 100644 --- a/database/tbcd/level/level_test.go +++ b/database/tbcd/level/level_test.go @@ -30,7 +30,7 @@ func bytes2Block(block []byte) (*wire.MsgBlock, error) { var b wire.MsgBlock err := b.Deserialize(bytes.NewReader(block)) if err != nil { - return nil, fmt.Errorf("Deserialize: %v", err) + return nil, fmt.Errorf("deserialize msg block: %w", err) } return &b, nil } @@ -39,7 +39,7 @@ func bytes2Header(header []byte) (*wire.BlockHeader, error) { var bh wire.BlockHeader err := bh.Deserialize(bytes.NewReader(header)) if err != nil { - return nil, fmt.Errorf("Deserialize: %v", err) + return nil, fmt.Errorf("deserialize block header: %w", err) } return &bh, nil } @@ -285,7 +285,7 @@ func TestLevelDB(t *testing.T) { } } -//func TestBitcoinBits(t *testing.T) { +// func TestBitcoinBits(t *testing.T) { // // Decode block // block381 := `01000000c5b9489065fa7e1ac4facc51a5a0ccc2111911609f43386ebe7ca1d200000000a0db3bbb22a2a8441d84dbe335c24959ea3d3d6e91bf67e66bbcb0d7e0a9c4836a834a4dffff001d041813660201000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0e046a834a4d017e062f503253482fffffffff0100f2052a01000000232103dac3fb8de40965f42fb4afb3baa07d3304bc2aa28cfc25f12b52f1523681451dac00000000010000001518b50db063333a3261b9b41e887b4aa5b69becdc9967550507c120e22a764967000000004a493046022100e49de3c89180769db346145cdda48323ddecc2af0041293432528767b18407650221009f7878deb054e4f9c0e6aecbe6de15f5d829041c11f7952d33e96c76ada1258b01ffffffff322948a4806acfeca2b32248d0e183c8eb09d5e5ef48adf33777307635414cc0000000004a493046022100ba88d34e4d4fd85ab5e4d77cb74f71c87a24235bcbe39cf4334633f70ff27233022100b5aa1b96bab59457d3d837473de1e4f9f89ba3ee39964463952271c5b4140fa001ffffffffcf330295467623ec1378dc6fa312103ad8a210b3e1351f2f4b6a57ac43fcd472000000004a493046022100b21560dfda52352c4416c1e48496659ea3d29e4e25706a991986864210bc759e0221009c1e45af6e2eba0883a862442d85a2b48c3395e35a4276f535cd70d45a971c7401ffffffffeeed0f4d975db8f66788f809ecf8c351d19ff5805276ef31983bc5682548342d0000000049483045022100e02cc0b4bf8a126807b1577819944c1bb13e8f4028cf7df0a0729013d511b071022010a1bcdefca334588939f9fe40e0d8607588191684fce0f46180a139305b8b4001ffffffffc8ac0a2fb1c01e0e0a5339d296eb072b2b9f9cb1d410a1fdd69a2c797094dda50000000049483045022016ba8f50d7f30be7e4a68c3d50368d577e2ef6c8b60842725ae636b2985776fc022100bb39d47d1955ffca47920d743bcd6f05b31ea2bf3dc7ede225eb4c901126b48901fffffffff1b03cf0680b9ef33fd311f6bbc6db3f1c164f9341f48a02df1905cec4ce241b000000004948304502201dbbfabc47f6da84ceedbc92b792d4a8ef632f0bddf7ebfad5ca21f3731f450502210098751ccf37fd97ff82446486d4c1d62860c2080a1128ea5ddb0d30bfde3cd7a801ffffffff1fe6898ac074a680fe7458ff87a03956db73a880d2ace6539efcc43002bd97ed000000004a493046022100f8a83fadb06af9c0cc730f17ae47fe7a09cada9eae623b8dd86bf365ef0e20480221009a10b073b2a8b313d975f801213efdf12b94141d7b6a8e98de3b0c67ee1cef4c01ffffffff6fd85c0213cfe9863573596a4d5f1509ac41a91b572e6c1bdafe46d9249a5fa4000000004a493046022100f3e98f3e76cc0f533b0e1cccd82650b704e31e3e7e62bf81bb474cf2add58ebf022100f77003eec814a3336cc305b8461cf3ccb19b1f18f06f66208ed31c3e468466ed01ffffffff9e93a056a6515e7916fc049578708d188c2146d3c12638acac92e0b72e076edd000000004a4930460221008ee8d7348aed82a8d074753ab4c8dbdd28a668da821269c4cd0c5c253738cab7022100b06a0208d60af1be6303dd883fd05f964a42f7de317761641ec1158944f52b6b01ffffffff0ecc7b73d8cd5d377d74d836bb6e3473478554a923154286ddaf6985948fd9d300000000494830450221008159ed783bc717ff5a6502cd87a8d8144fae74c6fc6943a5a38da7170203cb3802207e31577a576bc01510cb2280f918a371f63eee44cd2b4490c0994d261787916e01ffffffff78966e9f0a2d4452ab2418249fa6fb1a325a04f039d015899141a82aa5a6c05c000000004847304402206655b13198e413ac8f1aa8926d4617560758cf8b5045afdfc9116da0873ed89802205db55cf3f398467bfc6997f68c881e5f2a7225293ebbd2af40d15df6de4ef87701ffffffff69f2096bbede7015fee2fb307f7d7dd084641b7f4af5c3074dc7b2b6df03277c000000004a493046022100c9199296673a1beae598a6d2348ef13ad1b9f15eebaa825d2282adf017cbb5f0022100b54934e40ff0194a53dcaa9d017c36a93dbb53aa45fe21ab93b07fbb58570d5501ffffffff3c11b146d43fd62ec36b733942a52ba0c352c95a3f078808a38d080898cb83300000000048473044022004c64773b9e6a17cfca7ff583be650104c0538940289b2da8f8bebbd32e486b302200174d8f0938a0f9eeab4c4b137581e032f06d4740e3b0ad9d0423a0a8de65af101ffffffff59ac3c37adfa89b9a907ef9d485c57262e9283e1eb96069c2de04369ef1b3c7600000000494830450220306f3ac72de9dbeb1ec139e4e89cc3b3b9bcb63747bf0e165fcfc773f3669832022100c00a16800f16bf1c71ac6c2989b42d974b0ec2f3e3671325fb2cae52a1c569d801ffffffffb4bbecee818dd986e5ab82f36dbd5ccc29ab134614e304c0a397e14082fe7bb7000000004a493046022100ed68e0303052b41ffd80c1e905cee5547e92422d43b73e473a615e4a47146bb5022100ecab3f92c62477350753b4efea19d608fcce15b1b2c38fbe905e9d1f9ad7631f01ffffffff7546bbac9ae1c8980da6e8c154b368eb4df305b6f3f27ff38f195a13c9ee0484000000004948304502202288566af2b68b6982d1244e293ea3d7c156a425329b7f61b272e4deec317bea022100d9739976b442d35c32830cb2c105e0d7275f7efaa99eaeea4b24a553267a31fc01ffffffffd15854d1e5ba349daf72089f470b24557a2be25105b7831a3f18a62fb8bab677000000004948304502206e3a23075e0248ea8cabc7c875b4cfd9f036c1c4f358a00ec152fc96d1cb6cf8022100d34c018815f63c65f5364061369382b31d579cd6d8a4afe9ec1f03ba66d7717801ffffffffdf686a7f31c2c1de6a608553b26d6336434719fa45428eb3df59bbef75ce9e7e000000004948304502200a22a24a8f817a2f24d3f8c2670f3cb25cd389ce25e0d45eeb0aea08563c5c9802210081ff14edb230a44e5b52e35f573676096a937fc27cc830b153b229b92cac75c101ffffffffd226fea91b99c5a31a034d340f647b722e50950c96a876eb96569efaeaf3b227000000004a4930460221009684e60a7fd61362d0dad79858044aa4a7b878b3f0bd432e384fe4c7e6c90bde0221009883e4f739cffe574bac5bed0a4e69708433973a2490d9415d303614fc31be4701fffffffff640c60ea438dc020048599869836f5323ef47477ee17caddf076ed428898f7100000000494830450220028eb7617dc161a282512c81975d41a1594c05f34cb26fb759682bf784da7071022100a0913abea7229b3c465a4fa32dc861f72ef684e8dd3f19aac5f0f74ea39c03cf01ffffffffd59d2a49b1883c6f7ac68a9d2649dc0dde3f0205e19d8fdaf8065381f9ba61cc000000004a4930460221009f5b27dfd397423a04cab52ee6e8215e290e9666309f0f59f5bc5f6c207d3639022100f5a79133db2cc786140aeee0bf7c8a81adca6071928e8210f1c9f0c653e2f04201ffffffff0240195e29010000001976a914944a7d4b3a8d3a5ecf19dfdfd8dcc18c6f1487dd88acc0c01e49170000001976a91432040178c5cf81cb200ab99af1131f187745b51588ac00000000` // @@ -327,9 +327,9 @@ func TestLevelDB(t *testing.T) { // } // } // } -//} +// } // -//func TestDumpIndex(t *testing.T) { +// func TestDumpIndex(t *testing.T) { // levelDBHome := "~/.tbcd" // network := "testnet3" // @@ -361,9 +361,9 @@ func TestLevelDB(t *testing.T) { // for bsIt.Next() { // t.Logf("balances key %vvalue %v", spew.Sdump(bsIt.Key()), spew.Sdump(bsIt.Value())) // } -//} +// } // -//func TestIndex(t *testing.T) { +// func TestIndex(t *testing.T) { // // t.Skip() // // // start block @@ -416,4 +416,4 @@ func TestLevelDB(t *testing.T) { // //} // } // log.Infof("Ending index height %v took %v", count, time.Now().Sub(start)) -//} +// } diff --git a/hemi/electrumx/conn_test.go b/hemi/electrumx/conn_test.go index 95953c66..9a2fd72e 100644 --- a/hemi/electrumx/conn_test.go +++ b/hemi/electrumx/conn_test.go @@ -299,7 +299,7 @@ func (s *mockServer) handleConnection(t *testing.T, conn net.Conn) { func createAddress() string { port, err := freeport.GetFreePort() if err != nil { - panic(fmt.Errorf("find free port: %v", err)) + panic(fmt.Errorf("find free port: %w", err)) } return fmt.Sprintf("localhost:%d", port) } diff --git a/hemi/electrumx/electrumx.go b/hemi/electrumx/electrumx.go index 3c70c22d..55a72464 100644 --- a/hemi/electrumx/electrumx.go +++ b/hemi/electrumx/electrumx.go @@ -232,7 +232,7 @@ func (c *Client) Broadcast(ctx context.Context, rtx []byte) ([]byte, error) { } txHash, err := btcchainhash.NewHashFromStr(txHashStr) if err != nil { - return nil, fmt.Errorf("failed to decode transaction hash: %w", err) + return nil, fmt.Errorf("decode transaction hash: %w", err) } return txHash[:], nil } @@ -260,11 +260,11 @@ func (c *Client) RawBlockHeader(ctx context.Context, height uint64) (*bitcoin.Bl } var rbhStr string if err := c.call(ctx, "blockchain.block.header", ¶ms, &rbhStr); err != nil { - return nil, fmt.Errorf("failed to get block header: %w", err) + return nil, fmt.Errorf("get block header: %w", err) } rbh, err := hex.DecodeString(rbhStr) if err != nil { - return nil, fmt.Errorf("failed to decode raw block header: %w", err) + return nil, fmt.Errorf("decode raw block header: %w", err) } return bitcoin.RawBlockHeaderFromSlice(rbh) } @@ -283,11 +283,11 @@ func (c *Client) RawTransaction(ctx context.Context, txHash []byte) ([]byte, err } var rtxStr string if err := c.call(ctx, "blockchain.transaction.get", ¶ms, &rtxStr); err != nil { - return nil, fmt.Errorf("failed to get transaction: %w", err) + return nil, fmt.Errorf("get transaction: %w", err) } rtx, err := hex.DecodeString(rtxStr) if err != nil { - return nil, fmt.Errorf("failed to decode raw transaction: %w", err) + return nil, fmt.Errorf("decode raw transaction: %w", err) } return rtx, nil } @@ -306,7 +306,7 @@ func (c *Client) Transaction(ctx context.Context, txHash []byte) ([]byte, error) } var txJSON json.RawMessage if err := c.call(ctx, "blockchain.transaction.get", ¶ms, &txJSON); err != nil { - return nil, fmt.Errorf("failed to get transaction: %w", err) + return nil, fmt.Errorf("get transaction: %w", err) } return txJSON, nil } @@ -331,12 +331,12 @@ func (c *Client) TransactionAtPosition(ctx context.Context, height, index uint64 } else if strings.HasPrefix(err.Error(), "db error: DBError('block ") && strings.Contains(err.Error(), " not on disk ") { return nil, nil, NewBlockNotOnDiskError(err) } - return nil, nil, fmt.Errorf("failed to get transaction from block: %w", err) + return nil, nil, fmt.Errorf("get transaction from block: %w", err) } txHash, err := btcchainhash.NewHashFromStr(result.TXHash) if err != nil { - return nil, nil, fmt.Errorf("failed to decode transaction hash: %w", err) + return nil, nil, fmt.Errorf("decode transaction hash: %w", err) } return txHash[:], result.Merkle, nil @@ -360,7 +360,7 @@ func (c *Client) UTXOs(ctx context.Context, scriptHash []byte) ([]*UTXO, error) for _, eutxo := range eutxos { hash, err := btcchainhash.NewHashFromStr(eutxo.Hash) if err != nil { - return nil, fmt.Errorf("failed to decode UTXO hash: %w", err) + return nil, fmt.Errorf("decode UTXO hash: %w", err) } utxos = append(utxos, &UTXO{ Hash: hash[:], diff --git a/hemi/pop/pop.go b/hemi/pop/pop.go index b574d5bc..355d84dd 100644 --- a/hemi/pop/pop.go +++ b/hemi/pop/pop.go @@ -70,13 +70,13 @@ func (tx *TransactionL2) EncodeToOpReturn() ([]byte, error) { func ParseTransactionL2FromOpReturn(script []byte) (*TransactionL2, error) { txst := txscript.MakeScriptTokenizer(0, script) if !txst.Next() { - return nil, errors.New("failed to parse script") + return nil, errors.New("parse script") } if txst.Opcode() != txscript.OP_RETURN { return nil, fmt.Errorf("not a PoP transaction, found: 0x%X", txst.Opcode()) } if !txst.Next() { - return nil, errors.New("failed to parse script") + return nil, errors.New("parse script") } data := txst.Data() if len(data) < 5 { @@ -87,7 +87,7 @@ func ParseTransactionL2FromOpReturn(script []byte) (*TransactionL2, error) { } ksh, err := hemi.NewL2KeystoneAbrevFromBytes(data[4:]) if err != nil { - return nil, fmt.Errorf("failed to parse keystone header: %w", err) + return nil, fmt.Errorf("parse keystone header: %w", err) } return &TransactionL2{L2Keystone: ksh}, nil } @@ -125,13 +125,13 @@ func (tx *Transaction) EncodeToOpReturn() ([]byte, error) { func ParseTransactionFromOpReturn(script []byte) (*Transaction, error) { txst := txscript.MakeScriptTokenizer(0, script) if !txst.Next() { - return nil, errors.New("failed to parse script") + return nil, errors.New("parse script") } if txst.Opcode() != txscript.OP_RETURN { return nil, errors.New("not a PoP transaction") } if !txst.Next() { - return nil, errors.New("failed to parse script") + return nil, errors.New("parse script") } data := txst.Data() if len(data) < 4 { @@ -142,7 +142,7 @@ func ParseTransactionFromOpReturn(script []byte) (*Transaction, error) { } ksh, err := hemi.NewHeaderFromBytes(data[4:]) if err != nil { - return nil, fmt.Errorf("failed to parse keystone header: %w", err) + return nil, fmt.Errorf("parse keystone header: %w", err) } return &Transaction{Keystone: ksh}, nil } @@ -151,13 +151,13 @@ func ParsePublicKeyFromSignatureScript(script []byte) ([]byte, error) { var err error txst := txscript.MakeScriptTokenizer(0, script) if !txst.Next() { - return nil, errors.New("failed to parse script") + return nil, errors.New("parse script") } if txst.Opcode() != txscript.OP_DATA_72 && txst.Opcode() != txscript.OP_DATA_71 { return nil, fmt.Errorf("not a signature , found: 0x%X", txst.Opcode()) } if !txst.Next() { - return nil, errors.New("failed to parse script") + return nil, errors.New("parse script") } data := txst.Data() if len(data) != 33 { diff --git a/service/bfg/bfg.go b/service/bfg/bfg.go index 7dbc935c..a8fe95d5 100644 --- a/service/bfg/bfg.go +++ b/service/bfg/bfg.go @@ -182,7 +182,7 @@ func NewServer(cfg *Config) (*Server, error) { var err error s.btcClient, err = electrumx.NewClient(cfg.EXBTCAddress) if err != nil { - return nil, fmt.Errorf("failed to create electrumx client: %w", err) + return nil, fmt.Errorf("create electrumx client: %w", err) } // We could use a PGURI verification here. @@ -432,7 +432,7 @@ func (s *Server) processBitcoinBlock(ctx context.Context, height uint64) error { rbh, err := s.btcClient.RawBlockHeader(ctx, height) if err != nil { - return fmt.Errorf("failed to get block header at height %v: %v", + return fmt.Errorf("get block header at height %v: %v", height, err) } @@ -469,7 +469,7 @@ func (s *Server) processBitcoinBlock(ctx context.Context, height uint64) error { // in a block, so hopefully we've got them all... return nil } - return fmt.Errorf("failed to get transaction at position (height %v, index %v): %w", height, index, err) + return fmt.Errorf("get transaction at position (height %v, index %v): %w", height, index, err) } txHashEncoded := hex.EncodeToString(txHash) @@ -492,7 +492,7 @@ func (s *Server) processBitcoinBlock(ctx context.Context, height uint64) error { rtx, err := s.btcClient.RawTransaction(ctx, txHash) if err != nil { - return fmt.Errorf("failed to get raw transaction with txid %x: %w", txHash, err) + return fmt.Errorf("get raw transaction with txid %x: %w", txHash, err) } log.Infof("got raw transaction with txid %x", txHash) @@ -570,7 +570,7 @@ func (s *Server) processBitcoinBlock(ctx context.Context, height uint64) error { func (s *Server) processBitcoinBlocks(ctx context.Context, start, end uint64) error { for i := start; i <= end; i++ { if err := s.processBitcoinBlock(ctx, i); err != nil { - return fmt.Errorf("failed to process bitcoin block at height %d: %w", i, err) + return fmt.Errorf("process bitcoin block at height %d: %w", i, err) } s.btcHeight = i } @@ -702,7 +702,7 @@ func (s *Server) handleWebsocketPrivateRead(ctx context.Context, bws *bfgWs) { go s.handleRequest(ctx, bws, id, "handle access key delete request", handler) default: - err = fmt.Errorf("unknown command") + err = errors.New("unknown command") } // If set, it is a terminal error. @@ -776,7 +776,7 @@ func (s *Server) handleWebsocketPublicRead(ctx context.Context, bws *bfgWs) { go s.handleRequest(ctx, bws, id, "handle bitcoin utxos request", handler) default: - err = fmt.Errorf("unknown command") + err = errors.New("unknown command") } // If set, it is a terminal error. @@ -1333,7 +1333,7 @@ func (s *Server) Run(pctx context.Context) error { defer log.Tracef("Run exit") if !s.testAndSetRunning(true) { - return fmt.Errorf("bfg already running") + return errors.New("bfg already running") } defer s.testAndSetRunning(false) @@ -1346,7 +1346,7 @@ func (s *Server) Run(pctx context.Context) error { var err error s.db, err = postgres.New(ctx, s.cfg.PgURI) if err != nil { - return fmt.Errorf("failed to connect to database: %w", err) + return fmt.Errorf("connect to database: %w", err) } defer s.db.Close() @@ -1449,7 +1449,7 @@ func (s *Server) Run(pctx context.Context) error { ListenAddress: s.cfg.PrometheusListenAddress, }) if err != nil { - return fmt.Errorf("failed to create server: %w", err) + return fmt.Errorf("create server: %w", err) } cs := []prometheus.Collector{ s.cmdsProcessed, // XXX should we make two counters? priv/pub diff --git a/service/bfg/bfg_test.go b/service/bfg/bfg_test.go index d94e4f27..ba61a757 100644 --- a/service/bfg/bfg_test.go +++ b/service/bfg/bfg_test.go @@ -34,11 +34,11 @@ func checkBitcoinFinality(bf *BitcoinFinality) error { // Parse BTC block header and transaction. btcHeader := &btcwire.BlockHeader{} if err := btcHeader.Deserialize(bytes.NewReader(bf.BTCRawBlockHeader)); err != nil { - return fmt.Errorf("failed to deserialize BTC header: %w", err) + return fmt.Errorf("deserialize BTC header: %w", err) } btcTransaction := &btcwire.MsgTx{} if err := btcTransaction.Deserialize(bytes.NewReader(bf.BTCRawTransaction)); err != nil { - return fmt.Errorf("failed to deserialize BTC transaction: %w", err) + return fmt.Errorf("deserialize BTC transaction: %w", err) } btcTxHash := btcchainhash.DoubleHashB(bf.BTCRawTransaction) @@ -48,7 +48,7 @@ func checkBitcoinFinality(bf *BitcoinFinality) error { merkleHashes = append(merkleHashes, merkleHash) } if err := bitcoin.CheckMerkleChain(btcTxHash, bf.BTCTransactionIndex, merkleHashes, btcHeader.MerkleRoot[:]); err != nil { - return fmt.Errorf("failed to verify merkle path for transaction: %w", err) + return fmt.Errorf("verify merkle path for transaction: %w", err) } // XXX - verify HEMI keystone header and PoP miner public key. diff --git a/service/bss/bss.go b/service/bss/bss.go index 5ed24210..e2908d1a 100644 --- a/service/bss/bss.go +++ b/service/bss/bss.go @@ -715,7 +715,7 @@ func (s *Server) Run(parrentCtx context.Context) error { defer log.Tracef("Run exit") if !s.testAndSetRunning(true) { - return fmt.Errorf("bss already running") + return errors.New("bss already running") } defer s.testAndSetRunning(false) @@ -752,7 +752,7 @@ func (s *Server) Run(parrentCtx context.Context) error { ListenAddress: s.cfg.PrometheusListenAddress, }) if err != nil { - return fmt.Errorf("failed to create server: %w", err) + return fmt.Errorf("create server: %w", err) } cs := []prometheus.Collector{ s.cmdsProcessed, diff --git a/service/deucalion/deucalion.go b/service/deucalion/deucalion.go index f024cc52..fdb7e5ea 100644 --- a/service/deucalion/deucalion.go +++ b/service/deucalion/deucalion.go @@ -81,7 +81,7 @@ func init() { ctx := context.Background() d, err := New(cfg) if err != nil { - panic(fmt.Errorf("failed to create server: %w", err)) + panic(fmt.Errorf("create server: %w", err)) } go func() { if err = d.Run(ctx, nil); !errors.Is(err, context.Canceled) { @@ -134,12 +134,12 @@ func (d *Deucalion) testAndSetRunning(b bool) bool { func (d *Deucalion) Run(ctx context.Context, cs []prometheus.Collector) error { if !d.testAndSetRunning(true) { - return fmt.Errorf("already running") + return errors.New("already running") } defer d.testAndSetRunning(false) if d.cfg.ListenAddress == "" { - return fmt.Errorf("listen address is required") + return errors.New("listen address is required") } reg := prometheus.NewRegistry() diff --git a/service/popm/popm.go b/service/popm/popm.go index c6cb0c02..d917a7c4 100644 --- a/service/popm/popm.go +++ b/service/popm/popm.go @@ -206,7 +206,7 @@ func (m *Miner) bitcoinHeight(ctx context.Context) (uint64, error) { biResp, ok := res.(*bfgapi.BitcoinInfoResponse) if !ok { - return 0, fmt.Errorf("not a BitcoinIfnoResponse") + return 0, errors.New("not a BitcoinIfnoResponse") } if biResp.Error != nil { @@ -279,7 +279,7 @@ func createTx(l2Keystone *hemi.L2Keystone, btcHeight uint64, utxo *bfgapi.Bitcoi popTx := pop.TransactionL2{L2Keystone: aks} popTxOpReturn, err := popTx.EncodeToOpReturn() if err != nil { - return nil, fmt.Errorf("failed to encode PoP transaction: %w", err) + return nil, fmt.Errorf("encode PoP transaction: %w", err) } btx.TxOut = append(btx.TxOut, btcwire.NewTxOut(0, popTxOpReturn)) @@ -295,12 +295,12 @@ func (m *Miner) mineKeystone(ctx context.Context, ks *hemi.L2Keystone) error { btcHeight, err := m.bitcoinHeight(ctx) if err != nil { - return fmt.Errorf("failed to get Bitcoin height: %w", err) + return fmt.Errorf("get Bitcoin height: %w", err) } payToScript, err := btctxscript.PayToAddrScript(m.btcAddress) if err != nil { - return fmt.Errorf("failed to get pay to address script: %w", err) + return fmt.Errorf("get pay to address script: %w", err) } if len(payToScript) != 25 { return fmt.Errorf("incorrect length for pay to public key script (%d != 25)", len(payToScript)) @@ -315,7 +315,7 @@ func (m *Miner) mineKeystone(ctx context.Context, ks *hemi.L2Keystone) error { // Check balance. confirmed, unconfirmed, err := m.bitcoinBalance(ctx, scriptHash[:]) if err != nil { - return fmt.Errorf("failed to get Bitcoin balance: %w", err) + return fmt.Errorf("get Bitcoin balance: %w", err) } log.Tracef("Bitcoin balance for miner is: %v confirmed, %v unconfirmed", confirmed, unconfirmed) @@ -323,7 +323,7 @@ func (m *Miner) mineKeystone(ctx context.Context, ks *hemi.L2Keystone) error { log.Tracef("Looking for UTXOs for script hash %v", scriptHash) utxos, err := m.bitcoinUTXOs(ctx, scriptHash[:]) if err != nil { - return fmt.Errorf("failed to get Bitcoin UTXOs: %w", err) + return fmt.Errorf("get Bitcoin UTXOs: %w", err) } log.Tracef("Found %d UTXOs at Bitcoin height %d", len(utxos), btcHeight) @@ -334,7 +334,7 @@ func (m *Miner) mineKeystone(ctx context.Context, ks *hemi.L2Keystone) error { utxos, err = pickUTXOs(utxos, feeAmount) if err != nil { - return fmt.Errorf("failed to pick UTXOs: %w", err) + return fmt.Errorf("pick UTXOs: %w", err) } if len(utxos) != 1 { @@ -356,7 +356,7 @@ func (m *Miner) mineKeystone(ctx context.Context, ks *hemi.L2Keystone) error { // broadcast tx var buf bytes.Buffer if err := btx.Serialize(&buf); err != nil { - return fmt.Errorf("failed to serialize Bitcoin transaction: %w", err) + return fmt.Errorf("serialize Bitcoin transaction: %w", err) } txb := buf.Bytes() @@ -364,11 +364,11 @@ func (m *Miner) mineKeystone(ctx context.Context, ks *hemi.L2Keystone) error { txh, err := m.bitcoinBroadcast(ctx, txb) if err != nil { - return fmt.Errorf("failed to broadcast PoP transaction: %w", err) + return fmt.Errorf("broadcast PoP transaction: %w", err) } txHash, err := btcchainhash.NewHash(txh) if err != nil { - return fmt.Errorf("failed to create BTC hash from transaction hash: %w", err) + return fmt.Errorf("create BTC hash from transaction hash: %w", err) } log.Infof("Successfully broadcast PoP transaction to Bitcoin with TX hash %v", txHash) @@ -591,7 +591,7 @@ func (m *Miner) callBFG(parrentCtx context.Context, timeout time.Duration, msg a return nil, ctx.Err() case m.bfgCmdCh <- bc: default: - return nil, fmt.Errorf("bfg command queue full") + return nil, errors.New("bfg command queue full") } // Wait for response @@ -622,7 +622,7 @@ func (m *Miner) checkForKeystones(ctx context.Context) error { ghkrResp, ok := res.(*bfgapi.L2KeystonesResponse) if !ok { - return fmt.Errorf("not an L2KeystonesResponse") + return errors.New("not an L2KeystonesResponse") } if ghkrResp.Error != nil { @@ -831,7 +831,7 @@ func (m *Miner) bfg(ctx context.Context) error { func (m *Miner) Run(pctx context.Context) error { if !m.testAndSetRunning(true) { - return fmt.Errorf("popmd already running") + return errors.New("popmd already running") } defer m.testAndSetRunning(false) diff --git a/service/popm/prometheus.go b/service/popm/prometheus.go index 6fe741b0..5886a51f 100644 --- a/service/popm/prometheus.go +++ b/service/popm/prometheus.go @@ -21,7 +21,7 @@ func (m *Miner) handlePrometheus(ctx context.Context) error { ListenAddress: m.cfg.PrometheusListenAddress, }) if err != nil { - return fmt.Errorf("failed to create server: %w", err) + return fmt.Errorf("create server: %w", err) } cs := []prometheus.Collector{ prometheus.NewGaugeFunc(prometheus.GaugeOpts{ diff --git a/service/tbc/crawler.go b/service/tbc/crawler.go index 3e2287dd..08d9652b 100644 --- a/service/tbc/crawler.go +++ b/service/tbc/crawler.go @@ -137,11 +137,11 @@ func (s *Server) indexUtxosInBlocks(ctx context.Context, startHeight, maxHeight log.Infof("No more blocks at: %v", height) break } - return 0, fmt.Errorf("block headers by height %v: %v", height, err) + return 0, fmt.Errorf("block headers by height %v: %w", height, err) } eb, err := s.db.BlockByHash(ctx, bhs[0].Hash) if err != nil { - return 0, fmt.Errorf("block by hash %v: %v", height, err) + return 0, fmt.Errorf("block by hash %v: %w", height, err) } b, err := btcutil.NewBlockFromBytes(eb.Block) if err != nil { @@ -154,13 +154,13 @@ func (s *Server) indexUtxosInBlocks(ctx context.Context, startHeight, maxHeight // map must be locked as it is being processed. err = s.fixupCache(ctx, b, utxos) if err != nil { - return 0, fmt.Errorf("parse block %v: %v", height, err) + return 0, fmt.Errorf("parse block %v: %w", height, err) } // At this point we can lockless since it is all single // threaded again. err = processUtxos(s.chainParams, b.Transactions(), utxos) if err != nil { - return 0, fmt.Errorf("process utxos %v: %v", height, err) + return 0, fmt.Errorf("process utxos %v: %w", height, err) } blocksProcessed++ @@ -288,11 +288,11 @@ func (s *Server) indexTxsInBlocks(ctx context.Context, startHeight, maxHeight ui log.Infof("No more blocks at: %v", height) break } - return 0, fmt.Errorf("block headers by height %v: %v", height, err) + return 0, fmt.Errorf("block headers by height %v: %w", height, err) } eb, err := s.db.BlockByHash(ctx, bhs[0].Hash) if err != nil { - return 0, fmt.Errorf("block by hash %v: %v", height, err) + return 0, fmt.Errorf("block by hash %v: %w", height, err) } b, err := btcutil.NewBlockFromBytes(eb.Block) if err != nil { @@ -303,7 +303,7 @@ func (s *Server) indexTxsInBlocks(ctx context.Context, startHeight, maxHeight ui err = processTxs(s.chainParams, b.Hash(), b.Transactions(), txs) if err != nil { - return 0, fmt.Errorf("process txs %v: %v", height, err) + return 0, fmt.Errorf("process txs %v: %w", height, err) } blocksProcessed++ diff --git a/service/tbc/peer.go b/service/tbc/peer.go index 2648418a..2ced20d9 100644 --- a/service/tbc/peer.go +++ b/service/tbc/peer.go @@ -6,6 +6,7 @@ package tbc import ( "context" + "errors" "fmt" "math/rand" "net" @@ -101,7 +102,7 @@ func (p *peer) handshake(ctx context.Context, conn net.Conn) error { v, ok := rmsg.(*wire.MsgVersion) if !ok { - return fmt.Errorf("expected version message") + return errors.New("expected version message") } p.remoteVersion = v @@ -121,7 +122,7 @@ func (p *peer) handshake(ctx context.Context, conn net.Conn) error { for count := 0; count < 3; count++ { msg, err := readTimeout(defaultHandshakeTimeout, conn, p.protocolVersion, p.network) - if err == wire.ErrUnknownMessage { + if errors.Is(err, wire.ErrUnknownMessage) { continue } else if err != nil { return fmt.Errorf("handshake read: %w", err) @@ -138,7 +139,7 @@ func (p *peer) handshake(ctx context.Context, conn net.Conn) error { } } - return fmt.Errorf("handshake failed") + return errors.New("handshake failed") } func (p *peer) connect(ctx context.Context) error { @@ -192,7 +193,7 @@ func (p *peer) close() error { if p.conn != nil { return p.conn.Close() } - return fmt.Errorf("already closed") + return errors.New("already closed") } func (p *peer) isConnected() bool { diff --git a/service/tbc/tbc.go b/service/tbc/tbc.go index a9ead495..f2dc1c0f 100644 --- a/service/tbc/tbc.go +++ b/service/tbc/tbc.go @@ -123,7 +123,7 @@ func bytes2Header(header []byte) (*wire.BlockHeader, error) { var bh wire.BlockHeader err := bh.Deserialize(bytes.NewReader(header)) if err != nil { - return nil, fmt.Errorf("Deserialize: %v", err) + return nil, fmt.Errorf("deserialize block header: %w", err) } return &bh, nil } @@ -296,14 +296,14 @@ func (s *Server) blockPeerExpire() int { func (s *Server) getHeaders(ctx context.Context, p *peer, lastHeaderHash []byte) error { bh, err := bytes2Header(lastHeaderHash) if err != nil { - return fmt.Errorf("invalid header: %v", err) + return fmt.Errorf("invalid header: %w", err) } hash := bh.BlockHash() ghs := wire.NewMsgGetHeaders() ghs.AddBlockLocatorHash(&hash) err = p.write(defaultCmdTimeout, ghs) if err != nil { - return fmt.Errorf("write get headers: %v", err) + return fmt.Errorf("write get headers: %w", err) } return nil @@ -315,7 +315,7 @@ func (s *Server) seed(pctx context.Context, peersWanted int) ([]tbcd.Peer, error peers, err := s.db.PeersRandom(pctx, peersWanted) if err != nil { - return nil, fmt.Errorf("peers random: %v", err) + return nil, fmt.Errorf("peers random: %w", err) } // return peers from db first if len(peers) >= peersWanted { @@ -339,7 +339,7 @@ func (s *Server) seed(pctx context.Context, peersWanted int) ([]tbcd.Peer, error addrs = append(addrs, ips...) } if errorsSeen == len(s.seeds) { - return nil, fmt.Errorf("could not seed") + return nil, errors.New("could not seed") } // insert into peers table @@ -418,7 +418,7 @@ func (s *Server) peerManager(ctx context.Context) error { } if len(seeds) == 0 { // should not happen - return fmt.Errorf("no seeds found") + return errors.New("no seeds found") } // Add a ticker that times out every 27 seconds regardless of what is @@ -457,7 +457,7 @@ func (s *Server) peerManager(ctx context.Context) error { } if len(seeds) == 0 { // should not happen - return fmt.Errorf("no seeds found") + return errors.New("no seeds found") } x = 0 } @@ -651,7 +651,7 @@ func (s *Server) peerConnect(ctx context.Context, peerC chan string, p *peer) { } msg, err := p.read() - if err == wire.ErrUnknownMessage { + if errors.Is(err, wire.ErrUnknownMessage) { // skip unknown continue } else if err != nil { @@ -1296,7 +1296,7 @@ func (s *Server) insertGenesis(ctx context.Context) ([]tbcd.BlockHeader, error) log.Infof("Inserting genesis block and header: %v", s.chainParams.GenesisHash) gbh, err := header2Bytes(&s.chainParams.GenesisBlock.Header) if err != nil { - return nil, fmt.Errorf("serialize genesis block header: %v", err) + return nil, fmt.Errorf("serialize genesis block header: %w", err) } genesisBlockHeader := &tbcd.BlockHeader{ @@ -1306,20 +1306,20 @@ func (s *Server) insertGenesis(ctx context.Context) ([]tbcd.BlockHeader, error) } err = s.db.BlockHeadersInsert(ctx, []tbcd.BlockHeader{*genesisBlockHeader}) if err != nil { - return nil, fmt.Errorf("genesis block header insert: %v", err) + return nil, fmt.Errorf("genesis block header insert: %w", err) } log.Debugf("Inserting genesis block") gb, err := btcutil.NewBlock(s.chainParams.GenesisBlock).Bytes() if err != nil { - return nil, fmt.Errorf("genesis block encode: %v", err) + return nil, fmt.Errorf("genesis block encode: %w", err) } _, err = s.db.BlockInsert(ctx, &tbcd.Block{ Hash: s.chainParams.GenesisHash[:], Block: gb, }) if err != nil { - return nil, fmt.Errorf("genesis block insert: %v", err) + return nil, fmt.Errorf("genesis block insert: %w", err) } return []tbcd.BlockHeader{*genesisBlockHeader}, nil @@ -1542,7 +1542,7 @@ func (s *Server) FeesAtHeight(ctx context.Context, height, count int64) (uint64, defer log.Tracef("FeesAtHeight exit") if height-count < 0 { - return 0, fmt.Errorf("height - count is less than 0") + return 0, errors.New("height - count is less than 0") } var fees uint64 for i := int64(0); i < int64(count); i++ { @@ -1573,7 +1573,7 @@ func (s *Server) FeesAtHeight(ctx context.Context, height, count int64) (uint64, } } - return fees, fmt.Errorf("not yet") + return fees, errors.New("not yet") } type SyncInfo struct { @@ -1627,7 +1627,7 @@ func (s *Server) DBOpen(ctx context.Context) error { var err error s.db, err = level.New(ctx, filepath.Join(s.cfg.LevelDBHome, s.cfg.Network)) if err != nil { - return fmt.Errorf("open level database: %v", err) + return fmt.Errorf("open level database: %w", err) } return nil @@ -1645,7 +1645,7 @@ func (s *Server) Run(pctx context.Context) error { defer log.Tracef("Run exit") if !s.testAndSetRunning(true) { - return fmt.Errorf("tbc already running") + return errors.New("tbc already running") } defer s.testAndSetRunning(false) @@ -1667,7 +1667,7 @@ func (s *Server) Run(pctx context.Context) error { err := s.DBOpen(ctx) if err != nil { - return fmt.Errorf("Failed to open level database: %w", err) + return fmt.Errorf("open level database: %w", err) } defer func() { err := s.DBClose() @@ -1679,20 +1679,20 @@ func (s *Server) Run(pctx context.Context) error { // Find out where IBD is at bhs, err := s.db.BlockHeadersBest(ctx) if err != nil { - return fmt.Errorf("block headers best: %v", err) + return fmt.Errorf("block headers best: %w", err) } // No entries means we are at genesis if len(bhs) == 0 { bhs, err = s.insertGenesis(ctx) if err != nil { - return fmt.Errorf("insert genesis: %v", err) + return fmt.Errorf("insert genesis: %w", err) } bhs, err = s.db.BlockHeadersBest(ctx) if err != nil { return err } } else if len(bhs) > 1 { - return fmt.Errorf("blockheaders best: unsupported fork") + return errors.New("blockheaders best: unsupported fork") } s.lastBlockHeader = bhs[0] // Prime last seen block header log.Infof("Starting block headers sync at height: %v time %v", @@ -1727,7 +1727,7 @@ func (s *Server) Run(pctx context.Context) error { ListenAddress: s.cfg.PrometheusListenAddress, }) if err != nil { - return fmt.Errorf("failed to create server: %w", err) + return fmt.Errorf("create server: %w", err) } cs := []prometheus.Collector{ s.cmdsProcessed, @@ -1740,7 +1740,7 @@ func (s *Server) Run(pctx context.Context) error { s.wg.Add(1) go func() { defer s.wg.Done() - if err := d.Run(ctx, cs); err != context.Canceled { + if err := d.Run(ctx, cs); !errors.Is(err, context.Canceled) { log.Errorf("prometheus terminated with error: %v", err) return } diff --git a/service/tbc/tbc_test.go b/service/tbc/tbc_test.go index 349d0c9d..205aafed 100644 --- a/service/tbc/tbc_test.go +++ b/service/tbc/tbc_test.go @@ -8,6 +8,7 @@ import ( "context" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "os" @@ -1898,7 +1899,7 @@ func getEndpointWithRetries(ctx context.Context, container testcontainers.Contai func nextPort() int { ports, err := freeport.GetFreePorts(1000) - if err != nil && err != context.Canceled { + if err != nil && !errors.Is(err, context.Canceled) { panic(err) } @@ -1932,7 +1933,7 @@ func createTbcServer(ctx context.Context, t *testing.T, mappedPeerPort nat.Port) go func() { err := tbcServer.Run(ctx) - if err != nil && err != context.Canceled { + if err != nil && !errors.Is(err, context.Canceled) { panic(err) } }() diff --git a/web/popminer/popminer.go b/web/popminer/popminer.go index d3f66ff5..9cb4cf7e 100644 --- a/web/popminer/popminer.go +++ b/web/popminer/popminer.go @@ -86,12 +86,12 @@ func generateKey(this js.Value, args []js.Value) (any, error) { } privKey, err := dcrsecpk256k1.GeneratePrivateKey() if err != nil { - return nil, fmt.Errorf("failed to generate secp256k1 private key: %w", err) + return nil, fmt.Errorf("generate secp256k1 private key: %w", err) } btcAddress, err := btcutil.NewAddressPubKey(privKey.PubKey().SerializeCompressed(), btcChainParams) if err != nil { - return nil, fmt.Errorf("failed to create BTC address from public key: %v", + return nil, fmt.Errorf("create BTC address from public key: %v", err) } hash := btcAddress.AddressPubKeyHash().String() @@ -153,7 +153,7 @@ func runPopMiner(this js.Value, args []js.Value) (any, error) { pm.miner, err = popm.NewMiner(cfg) if err != nil { globalMtx.Unlock() - return nil, fmt.Errorf("failed to create POP miner: %w", err) + return nil, fmt.Errorf("create POP miner: %w", err) } globalMtx.Unlock() @@ -201,7 +201,7 @@ func activePopMiner() (*PopMiner, error) { globalMtx.Lock() defer globalMtx.Unlock() if pm == nil { - return nil, fmt.Errorf("pop miner not running") + return nil, errors.New("pop miner not running") } return pm, nil }