From 5305b41db4145b75cab2cb6ac852e243bd5c08f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Lewandowski?= <35259896+pawellewandowski98@users.noreply.github.com> Date: Thu, 4 Jul 2024 14:49:22 +0200 Subject: [PATCH] feat(SPV-846): refactor numeric error codes into strings (#245) Co-authored-by: chris-4chain <152964795+chris-4chain@users.noreply.github.com> --- authentication.go | 13 +- errors.go | 63 +++----- examples/go.mod | 4 +- examples/go.sum | 4 + .../handle_exceptions/handle_exceptions.go | 10 +- go.mod | 31 +++- go.sum | 83 ++++++++++ http.go | 148 +++++++++--------- search.go | 7 +- walletclient.go | 2 +- 10 files changed, 236 insertions(+), 129 deletions(-) diff --git a/authentication.go b/authentication.go index 55d2386b..7e226e03 100644 --- a/authentication.go +++ b/authentication.go @@ -8,7 +8,6 @@ import ( "github.com/bitcoin-sv/spv-wallet-go-client/utils" "github.com/bitcoin-sv/spv-wallet/models" - "github.com/bitcoin-sv/spv-wallet/models/apierrors" "github.com/bitcoinschema/go-bitcoin/v2" "github.com/libsv/go-bk/bec" "github.com/libsv/go-bk/bip32" @@ -18,7 +17,7 @@ import ( ) // SetSignature will set the signature on the header for the request -func setSignature(header *http.Header, xPriv *bip32.ExtendedKey, bodyString string) ResponseError { +func setSignature(header *http.Header, xPriv *bip32.ExtendedKey, bodyString string) error { // Create the signature authData, err := createSignature(xPriv, bodyString) if err != nil { @@ -28,7 +27,9 @@ func setSignature(header *http.Header, xPriv *bip32.ExtendedKey, bodyString stri // Set the auth header header.Set(models.AuthHeader, authData.XPub) - return setSignatureHeaders(header, authData) + setSignatureHeaders(header, authData) + + return nil } // GetSignedHex will sign all the inputs using the given xPriv key @@ -134,7 +135,7 @@ func getUnlockingScript(tx *bt.Tx, inputIndex uint32, privateKey *bec.PrivateKey func createSignature(xPriv *bip32.ExtendedKey, bodyString string) (payload *models.AuthPayload, err error) { // No key? if xPriv == nil { - err = apierrors.ErrMissingXPriv + err = ErrMissingXpriv return } @@ -199,7 +200,7 @@ func getSigningMessage(xPub string, auth *models.AuthPayload) string { return fmt.Sprintf("%s%s%s%d", xPub, auth.AuthHash, auth.AuthNonce, auth.AuthTime) } -func setSignatureHeaders(header *http.Header, authData *models.AuthPayload) ResponseError { +func setSignatureHeaders(header *http.Header, authData *models.AuthPayload) { // Create the auth header hash header.Set(models.AuthHeaderHash, authData.AuthHash) @@ -211,6 +212,4 @@ func setSignatureHeaders(header *http.Header, authData *models.AuthPayload) Resp // Set the signature header.Set(models.AuthSignature, authData.Signature) - - return nil } diff --git a/errors.go b/errors.go index e4e22c86..b9eb5740 100644 --- a/errors.go +++ b/errors.go @@ -2,71 +2,56 @@ package walletclient import ( "encoding/json" - "errors" - "fmt" - "io" + "github.com/bitcoin-sv/spv-wallet/models" "net/http" ) // ErrAdminKey admin key not set -var ErrAdminKey = errors.New("an admin key must be set to be able to create an xpub") +var ErrAdminKey = models.SPVError{Message: "an admin key must be set to be able to create an xpub", StatusCode: 401, Code: "error-unauthorized-admin-key-not-set"} -// ErrNoClientSet is when no client is set -var ErrNoClientSet = errors.New("no transport client set") +// ErrMissingXpriv is when xpriv is missing +var ErrMissingXpriv = models.SPVError{Message: "xpriv missing", StatusCode: 401, Code: "error-unauthorized-xpriv-missing"} -// ResError is a struct which contain information about error -type ResError struct { - StatusCode int - Message string -} - -// ResponseError is an interface for error -type ResponseError interface { - Error() string - GetStatusCode() int -} +// ErrCouldNotFindDraftTransaction is when draft transaction is not found +var ErrCouldNotFindDraftTransaction = models.SPVError{Message: "could not find draft transaction", StatusCode: 404, Code: "error-draft-transaction-not-found"} -// WrapError wraps an error into ResponseError -func WrapError(err error) ResponseError { +// WrapError wraps an error into SPVError +func WrapError(err error) error { if err == nil { return nil } - return &ResError{ + return &models.SPVError{ StatusCode: http.StatusInternalServerError, Message: err.Error(), + Code: models.UnknownErrorCode, } } -// WrapResponseError wraps a http response into ResponseError -func WrapResponseError(res *http.Response) ResponseError { +// WrapResponseError wraps a http response into SPVError +func WrapResponseError(res *http.Response) error { if res == nil { return nil } - var errorMsg string + var resError *models.ResponseError - err := json.NewDecoder(res.Body).Decode(&errorMsg) + err := json.NewDecoder(res.Body).Decode(&resError) if err != nil { - // if EOF, then body is empty and we return response status as error message - if !errors.Is(err, io.EOF) { - errorMsg = fmt.Sprintf("spv-wallet error message can't be decoded. Reason: %s", err.Error()) - } - errorMsg = res.Status + return WrapError(err) } - return &ResError{ + return &models.SPVError{ StatusCode: res.StatusCode, - Message: errorMsg, + Code: resError.Code, + Message: resError.Message, } } -// Error returns the error message -func (e *ResError) Error() string { - return e.Message -} - -// GetStatusCode returns the status code of error -func (e *ResError) GetStatusCode() int { - return e.StatusCode +func CreateErrorResponse(code string, message string) error { + return &models.SPVError{ + StatusCode: http.StatusInternalServerError, + Code: code, + Message: message, + } } diff --git a/examples/go.mod b/examples/go.mod index 458eab34..7b7b0bd8 100644 --- a/examples/go.mod +++ b/examples/go.mod @@ -1,12 +1,12 @@ module github.com/bitcoin-sv/spv-wallet-go-client/examples -go 1.21 +go 1.22.4 replace github.com/bitcoin-sv/spv-wallet-go-client => ../ require ( github.com/bitcoin-sv/spv-wallet-go-client v0.0.0-00010101000000-000000000000 - github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.13 + github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.15 ) require ( diff --git a/examples/go.sum b/examples/go.sum index fdd302c1..99f6fce5 100644 --- a/examples/go.sum +++ b/examples/go.sum @@ -1,5 +1,9 @@ github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.13 h1:rBscs3Gbz0RWY03eI3Z9AwD7/MxajdJF54oy3xMqKRQ= github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.13/go.mod h1:i3txysriHpprqYd3u97wEQsC4/jn+KHcyFOmuFYMw8M= +github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.14.0.20240626082725-2c073c5330a6 h1:ZTEHuSNbXszs+5TKN0uiW6DY7JdWIM5m6NQpBJZyre4= +github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.14.0.20240626082725-2c073c5330a6/go.mod h1:u3gnRDS3uHWZNM2qbYATTpN+mAphyozCJrYIKGwBX7k= +github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.15 h1:Qjp9gSe1XlBwADgDlkaIGuzqNoQwktu1DuB6tzurdQI= +github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.15/go.mod h1:Ni6SFkmMjV39Bg4FtlgPAsnsiJUfRDVEPlbzTZa8z40= github.com/bitcoinschema/go-bitcoin/v2 v2.0.5 h1:Sgh5Eb746Zck/46rFDrZZEXZWyO53fMuWYhNoZa1tck= github.com/bitcoinschema/go-bitcoin/v2 v2.0.5/go.mod h1:JjO1ivfZv6vhK0uAXzyH08AAHlzNMAfnyK1Fiv9r4ZA= github.com/bitcoinsv/bsvd v0.0.0-20190609155523-4c29707f7173 h1:2yTIV9u7H0BhRDGXH5xrAwAz7XibWJtX2dNezMeNsUo= diff --git a/examples/handle_exceptions/handle_exceptions.go b/examples/handle_exceptions/handle_exceptions.go index 62437a87..29fcfeea 100644 --- a/examples/handle_exceptions/handle_exceptions.go +++ b/examples/handle_exceptions/handle_exceptions.go @@ -5,11 +5,13 @@ package main import ( "context" + "errors" "fmt" "os" walletclient "github.com/bitcoin-sv/spv-wallet-go-client" "github.com/bitcoin-sv/spv-wallet-go-client/examples" + "github.com/bitcoin-sv/spv-wallet/models" ) func main() { @@ -24,8 +26,12 @@ func main() { status, err := client.AdminGetStatus(ctx) if err != nil { - fmt.Println("Response status: ", err.GetStatusCode()) - fmt.Println("Content: ", err.Error()) + var extendedErr models.ExtendedError + if errors.As(err, &extendedErr) { + fmt.Printf("Extended error: [%d] '%s': %s\n", extendedErr.GetStatusCode(), extendedErr.GetCode(), extendedErr.GetMessage()) + } else { + fmt.Println("Error: ", err.Error()) + } os.Exit(1) } diff --git a/go.mod b/go.mod index 5e1d0774..523c5d7f 100644 --- a/go.mod +++ b/go.mod @@ -1,9 +1,9 @@ module github.com/bitcoin-sv/spv-wallet-go-client -go 1.21 +go 1.22.4 require ( - github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.13 + github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.15 github.com/bitcoinschema/go-bitcoin/v2 v2.0.5 github.com/libsv/go-bk v0.1.6 github.com/libsv/go-bt/v2 v2.2.5 @@ -15,8 +15,35 @@ require ( require ( github.com/bitcoinsv/bsvd v0.0.0-20190609155523-4c29707f7173 // indirect github.com/boombuler/barcode v1.0.1 // indirect + github.com/bytedance/sonic v1.11.6 // indirect + github.com/bytedance/sonic/loader v0.1.1 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.10.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.20.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/rs/zerolog v1.33.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.8.0 // indirect golang.org/x/crypto v0.23.0 // indirect + golang.org/x/net v0.25.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect + google.golang.org/protobuf v1.34.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 5413a3d2..bc4ae1f6 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,9 @@ github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.13 h1:rBscs3Gbz0RWY03eI3Z9AwD7/MxajdJF54oy3xMqKRQ= github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.13/go.mod h1:i3txysriHpprqYd3u97wEQsC4/jn+KHcyFOmuFYMw8M= +github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.14.0.20240626082725-2c073c5330a6 h1:ZTEHuSNbXszs+5TKN0uiW6DY7JdWIM5m6NQpBJZyre4= +github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.14.0.20240626082725-2c073c5330a6/go.mod h1:u3gnRDS3uHWZNM2qbYATTpN+mAphyozCJrYIKGwBX7k= +github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.15 h1:Qjp9gSe1XlBwADgDlkaIGuzqNoQwktu1DuB6tzurdQI= +github.com/bitcoin-sv/spv-wallet/models v1.0.0-beta.15/go.mod h1:Ni6SFkmMjV39Bg4FtlgPAsnsiJUfRDVEPlbzTZa8z40= github.com/bitcoinschema/go-bitcoin/v2 v2.0.5 h1:Sgh5Eb746Zck/46rFDrZZEXZWyO53fMuWYhNoZa1tck= github.com/bitcoinschema/go-bitcoin/v2 v2.0.5/go.mod h1:JjO1ivfZv6vhK0uAXzyH08AAHlzNMAfnyK1Fiv9r4ZA= github.com/bitcoinsv/bsvd v0.0.0-20190609155523-4c29707f7173 h1:2yTIV9u7H0BhRDGXH5xrAwAz7XibWJtX2dNezMeNsUo= @@ -7,17 +11,63 @@ github.com/bitcoinsv/bsvd v0.0.0-20190609155523-4c29707f7173/go.mod h1:BZ1UcC9+t github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/boombuler/barcode v1.0.1 h1:NDBbPmhS+EqABEs5Kg3n/5ZNjy73Pz7SIV+KCeqyXcs= github.com/boombuler/barcode v1.0.1/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= +github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= +github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= +github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= +github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/libsv/go-bk v0.1.6 h1:c9CiT5+64HRDbzxPl1v/oiFmbvWZTuUYqywCf+MBs/c= github.com/libsv/go-bk v0.1.6/go.mod h1:khJboDoH18FPUaZlzRFKzlVN84d4YfdmlDtdX4LAjQA= github.com/libsv/go-bt/v2 v2.2.5 h1:VoggBLMRW9NYoFujqe5bSYKqnw5y+fYfufgERSoubog= github.com/libsv/go-bt/v2 v2.2.5/go.mod h1:cV45+jDlPOLfhJLfpLmpQoWzrIvVth9Ao2ZO1f6CcqU= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -26,14 +76,47 @@ github.com/pquerna/otp v1.4.0 h1:wZvl1TIVxKRThZIBiwOOHOGP/1+nZyWBil9Y2XNEDzg= github.com/pquerna/otp v1.4.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= +github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= +golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/http.go b/http.go index 6c66be6b..4b0b66de 100644 --- a/http.go +++ b/http.go @@ -12,7 +12,6 @@ import ( "github.com/bitcoin-sv/spv-wallet-go-client/utils" "github.com/bitcoin-sv/spv-wallet/models" - "github.com/bitcoin-sv/spv-wallet/models/apierrors" "github.com/bitcoin-sv/spv-wallet/models/filter" "github.com/bitcoinschema/go-bitcoin/v2" "github.com/libsv/go-bk/bec" @@ -35,7 +34,7 @@ func (wc *WalletClient) SetAdminKey(adminKey *bip32.ExtendedKey) { } // GetXPub will get the xpub of the current xpub -func (wc *WalletClient) GetXPub(ctx context.Context) (*models.Xpub, ResponseError) { +func (wc *WalletClient) GetXPub(ctx context.Context) (*models.Xpub, error) { var xPub models.Xpub if err := wc.doHTTPRequest( ctx, http.MethodGet, "/xpub", nil, wc.xPriv, true, &xPub, @@ -47,7 +46,7 @@ func (wc *WalletClient) GetXPub(ctx context.Context) (*models.Xpub, ResponseErro } // UpdateXPubMetadata update the metadata of the logged in xpub -func (wc *WalletClient) UpdateXPubMetadata(ctx context.Context, metadata map[string]any) (*models.Xpub, ResponseError) { +func (wc *WalletClient) UpdateXPubMetadata(ctx context.Context, metadata map[string]any) (*models.Xpub, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldMetadata: metadata, }) @@ -66,7 +65,7 @@ func (wc *WalletClient) UpdateXPubMetadata(ctx context.Context, metadata map[str } // GetAccessKey will get an access key by id -func (wc *WalletClient) GetAccessKey(ctx context.Context, id string) (*models.AccessKey, ResponseError) { +func (wc *WalletClient) GetAccessKey(ctx context.Context, id string) (*models.AccessKey, error) { var accessKey models.AccessKey if err := wc.doHTTPRequest( ctx, http.MethodGet, "/access-key?"+FieldID+"="+id, nil, wc.xPriv, true, &accessKey, @@ -83,7 +82,7 @@ func (wc *WalletClient) GetAccessKeys( conditions *filter.AccessKeyFilter, metadata map[string]any, queryParams *filter.QueryParams, -) ([]*models.AccessKey, ResponseError) { +) ([]*models.AccessKey, error) { return Search[filter.AccessKeyFilter, []*models.AccessKey]( ctx, http.MethodPost, "/access-key/search", @@ -100,7 +99,7 @@ func (wc *WalletClient) GetAccessKeysCount( ctx context.Context, conditions *filter.AccessKeyFilter, metadata map[string]any, -) (int64, ResponseError) { +) (int64, error) { return Count[filter.AccessKeyFilter]( ctx, http.MethodPost, "/access-key/count", @@ -112,7 +111,7 @@ func (wc *WalletClient) GetAccessKeysCount( } // RevokeAccessKey will revoke an access key by id -func (wc *WalletClient) RevokeAccessKey(ctx context.Context, id string) (*models.AccessKey, ResponseError) { +func (wc *WalletClient) RevokeAccessKey(ctx context.Context, id string) (*models.AccessKey, error) { var accessKey models.AccessKey if err := wc.doHTTPRequest( ctx, http.MethodDelete, "/access-key?"+FieldID+"="+id, nil, wc.xPriv, true, &accessKey, @@ -124,7 +123,7 @@ func (wc *WalletClient) RevokeAccessKey(ctx context.Context, id string) (*models } // CreateAccessKey will create new access key -func (wc *WalletClient) CreateAccessKey(ctx context.Context, metadata map[string]any) (*models.AccessKey, ResponseError) { +func (wc *WalletClient) CreateAccessKey(ctx context.Context, metadata map[string]any) (*models.AccessKey, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldMetadata: metadata, }) @@ -142,7 +141,7 @@ func (wc *WalletClient) CreateAccessKey(ctx context.Context, metadata map[string } // GetDestinationByID will get a destination by id -func (wc *WalletClient) GetDestinationByID(ctx context.Context, id string) (*models.Destination, ResponseError) { +func (wc *WalletClient) GetDestinationByID(ctx context.Context, id string) (*models.Destination, error) { var destination models.Destination if err := wc.doHTTPRequest( ctx, http.MethodGet, fmt.Sprintf("/destination?%s=%s", FieldID, id), nil, wc.xPriv, true, &destination, @@ -154,7 +153,7 @@ func (wc *WalletClient) GetDestinationByID(ctx context.Context, id string) (*mod } // GetDestinationByAddress will get a destination by address -func (wc *WalletClient) GetDestinationByAddress(ctx context.Context, address string) (*models.Destination, ResponseError) { +func (wc *WalletClient) GetDestinationByAddress(ctx context.Context, address string) (*models.Destination, error) { var destination models.Destination if err := wc.doHTTPRequest( ctx, http.MethodGet, "/destination?"+FieldAddress+"="+address, nil, wc.xPriv, true, &destination, @@ -166,7 +165,7 @@ func (wc *WalletClient) GetDestinationByAddress(ctx context.Context, address str } // GetDestinationByLockingScript will get a destination by locking script -func (wc *WalletClient) GetDestinationByLockingScript(ctx context.Context, lockingScript string) (*models.Destination, ResponseError) { +func (wc *WalletClient) GetDestinationByLockingScript(ctx context.Context, lockingScript string) (*models.Destination, error) { var destination models.Destination if err := wc.doHTTPRequest( ctx, http.MethodGet, "/destination?"+FieldLockingScript+"="+lockingScript, nil, wc.xPriv, true, &destination, @@ -178,7 +177,7 @@ func (wc *WalletClient) GetDestinationByLockingScript(ctx context.Context, locki } // GetDestinations will get all destinations matching the metadata filter -func (wc *WalletClient) GetDestinations(ctx context.Context, conditions *filter.DestinationFilter, metadata map[string]any, queryParams *filter.QueryParams) ([]*models.Destination, ResponseError) { +func (wc *WalletClient) GetDestinations(ctx context.Context, conditions *filter.DestinationFilter, metadata map[string]any, queryParams *filter.QueryParams) ([]*models.Destination, error) { return Search[filter.DestinationFilter, []*models.Destination]( ctx, http.MethodPost, "/destination/search", @@ -191,7 +190,7 @@ func (wc *WalletClient) GetDestinations(ctx context.Context, conditions *filter. } // GetDestinationsCount will get the count of destinations matching the metadata filter -func (wc *WalletClient) GetDestinationsCount(ctx context.Context, conditions *filter.DestinationFilter, metadata map[string]any) (int64, ResponseError) { +func (wc *WalletClient) GetDestinationsCount(ctx context.Context, conditions *filter.DestinationFilter, metadata map[string]any) (int64, error) { return Count( ctx, http.MethodPost, @@ -204,7 +203,7 @@ func (wc *WalletClient) GetDestinationsCount(ctx context.Context, conditions *fi } // NewDestination will create a new destination and return it -func (wc *WalletClient) NewDestination(ctx context.Context, metadata map[string]any) (*models.Destination, ResponseError) { +func (wc *WalletClient) NewDestination(ctx context.Context, metadata map[string]any) (*models.Destination, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldMetadata: metadata, }) @@ -222,7 +221,7 @@ func (wc *WalletClient) NewDestination(ctx context.Context, metadata map[string] } // UpdateDestinationMetadataByID updates the destination metadata by id -func (wc *WalletClient) UpdateDestinationMetadataByID(ctx context.Context, id string, metadata map[string]any) (*models.Destination, ResponseError) { +func (wc *WalletClient) UpdateDestinationMetadataByID(ctx context.Context, id string, metadata map[string]any) (*models.Destination, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldID: id, FieldMetadata: metadata, @@ -242,7 +241,7 @@ func (wc *WalletClient) UpdateDestinationMetadataByID(ctx context.Context, id st } // UpdateDestinationMetadataByAddress updates the destination metadata by address -func (wc *WalletClient) UpdateDestinationMetadataByAddress(ctx context.Context, address string, metadata map[string]any) (*models.Destination, ResponseError) { +func (wc *WalletClient) UpdateDestinationMetadataByAddress(ctx context.Context, address string, metadata map[string]any) (*models.Destination, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldAddress: address, FieldMetadata: metadata, @@ -262,7 +261,7 @@ func (wc *WalletClient) UpdateDestinationMetadataByAddress(ctx context.Context, } // UpdateDestinationMetadataByLockingScript updates the destination metadata by locking script -func (wc *WalletClient) UpdateDestinationMetadataByLockingScript(ctx context.Context, lockingScript string, metadata map[string]any) (*models.Destination, ResponseError) { +func (wc *WalletClient) UpdateDestinationMetadataByLockingScript(ctx context.Context, lockingScript string, metadata map[string]any) (*models.Destination, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldLockingScript: lockingScript, FieldMetadata: metadata, @@ -282,7 +281,7 @@ func (wc *WalletClient) UpdateDestinationMetadataByLockingScript(ctx context.Con } // GetTransaction will get a transaction by ID -func (wc *WalletClient) GetTransaction(ctx context.Context, txID string) (*models.Transaction, ResponseError) { +func (wc *WalletClient) GetTransaction(ctx context.Context, txID string) (*models.Transaction, error) { var transaction models.Transaction if err := wc.doHTTPRequest(ctx, http.MethodGet, "/transaction?"+FieldID+"="+txID, nil, wc.xPriv, wc.signRequest, &transaction); err != nil { return nil, err @@ -297,7 +296,7 @@ func (wc *WalletClient) GetTransactions( conditions *filter.TransactionFilter, metadata map[string]any, queryParams *filter.QueryParams, -) ([]*models.Transaction, ResponseError) { +) ([]*models.Transaction, error) { return Search[filter.TransactionFilter, []*models.Transaction]( ctx, http.MethodPost, "/transaction/search", @@ -314,7 +313,7 @@ func (wc *WalletClient) GetTransactionsCount( ctx context.Context, conditions *filter.TransactionFilter, metadata map[string]any, -) (int64, ResponseError) { +) (int64, error) { return Count[filter.TransactionFilter]( ctx, http.MethodPost, "/transaction/count", @@ -326,7 +325,7 @@ func (wc *WalletClient) GetTransactionsCount( } // DraftToRecipients is a draft transaction to a slice of recipients -func (wc *WalletClient) DraftToRecipients(ctx context.Context, recipients []*Recipients, metadata map[string]any) (*models.DraftTransaction, ResponseError) { +func (wc *WalletClient) DraftToRecipients(ctx context.Context, recipients []*Recipients, metadata map[string]any) (*models.DraftTransaction, error) { outputs := make([]map[string]interface{}, 0) for _, recipient := range recipients { outputs = append(outputs, map[string]interface{}{ @@ -345,7 +344,7 @@ func (wc *WalletClient) DraftToRecipients(ctx context.Context, recipients []*Rec } // DraftTransaction is a draft transaction -func (wc *WalletClient) DraftTransaction(ctx context.Context, transactionConfig *models.TransactionConfig, metadata map[string]any) (*models.DraftTransaction, ResponseError) { +func (wc *WalletClient) DraftTransaction(ctx context.Context, transactionConfig *models.TransactionConfig, metadata map[string]any) (*models.DraftTransaction, error) { return wc.createDraftTransaction(ctx, map[string]interface{}{ FieldConfig: transactionConfig, FieldMetadata: metadata, @@ -355,7 +354,7 @@ func (wc *WalletClient) DraftTransaction(ctx context.Context, transactionConfig // createDraftTransaction will create a draft transaction func (wc *WalletClient) createDraftTransaction(ctx context.Context, jsonData map[string]interface{}, -) (*models.DraftTransaction, ResponseError) { +) (*models.DraftTransaction, error) { jsonStr, err := json.Marshal(jsonData) if err != nil { return nil, WrapError(err) @@ -368,14 +367,14 @@ func (wc *WalletClient) createDraftTransaction(ctx context.Context, return nil, err } if draftTransaction == nil { - return nil, WrapError(apierrors.ErrDraftNotFound) + return nil, ErrCouldNotFindDraftTransaction } return draftTransaction, nil } // RecordTransaction will record a transaction -func (wc *WalletClient) RecordTransaction(ctx context.Context, hex, referenceID string, metadata map[string]any) (*models.Transaction, ResponseError) { +func (wc *WalletClient) RecordTransaction(ctx context.Context, hex, referenceID string, metadata map[string]any) (*models.Transaction, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldHex: hex, FieldReferenceID: referenceID, @@ -396,7 +395,7 @@ func (wc *WalletClient) RecordTransaction(ctx context.Context, hex, referenceID } // UpdateTransactionMetadata update the metadata of a transaction -func (wc *WalletClient) UpdateTransactionMetadata(ctx context.Context, txID string, metadata map[string]any) (*models.Transaction, ResponseError) { +func (wc *WalletClient) UpdateTransactionMetadata(ctx context.Context, txID string, metadata map[string]any) (*models.Transaction, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldID: txID, FieldMetadata: metadata, @@ -416,7 +415,7 @@ func (wc *WalletClient) UpdateTransactionMetadata(ctx context.Context, txID stri } // SetSignatureFromAccessKey will set the signature on the header for the request from an access key -func SetSignatureFromAccessKey(header *http.Header, privateKeyHex, bodyString string) ResponseError { +func SetSignatureFromAccessKey(header *http.Header, privateKeyHex, bodyString string) error { // Create the signature authData, err := createSignatureAccessKey(privateKeyHex, bodyString) if err != nil { @@ -426,11 +425,13 @@ func SetSignatureFromAccessKey(header *http.Header, privateKeyHex, bodyString st // Set the auth header header.Set(models.AuthAccessKey, authData.AccessKey) - return setSignatureHeaders(header, authData) + setSignatureHeaders(header, authData) + + return nil } // GetUtxo will get a utxo by transaction ID -func (wc *WalletClient) GetUtxo(ctx context.Context, txID string, outputIndex uint32) (*models.Utxo, ResponseError) { +func (wc *WalletClient) GetUtxo(ctx context.Context, txID string, outputIndex uint32) (*models.Utxo, error) { outputIndexStr := strconv.FormatUint(uint64(outputIndex), 10) url := fmt.Sprintf("/utxo?%s=%s&%s=%s", FieldTransactionID, txID, FieldOutputIndex, outputIndexStr) @@ -446,7 +447,7 @@ func (wc *WalletClient) GetUtxo(ctx context.Context, txID string, outputIndex ui } // GetUtxos will get a list of utxos filtered by conditions and metadata -func (wc *WalletClient) GetUtxos(ctx context.Context, conditions *filter.UtxoFilter, metadata map[string]any, queryParams *filter.QueryParams) ([]*models.Utxo, ResponseError) { +func (wc *WalletClient) GetUtxos(ctx context.Context, conditions *filter.UtxoFilter, metadata map[string]any, queryParams *filter.QueryParams) ([]*models.Utxo, error) { return Search[filter.UtxoFilter, []*models.Utxo]( ctx, http.MethodPost, "/utxo/search", @@ -459,7 +460,7 @@ func (wc *WalletClient) GetUtxos(ctx context.Context, conditions *filter.UtxoFil } // GetUtxosCount will get the count of utxos filtered by conditions and metadata -func (wc *WalletClient) GetUtxosCount(ctx context.Context, conditions *filter.UtxoFilter, metadata map[string]any) (int64, ResponseError) { +func (wc *WalletClient) GetUtxosCount(ctx context.Context, conditions *filter.UtxoFilter, metadata map[string]any) (int64, error) { return Count[filter.UtxoFilter]( ctx, http.MethodPost, "/utxo/count", @@ -474,7 +475,7 @@ func (wc *WalletClient) GetUtxosCount(ctx context.Context, conditions *filter.Ut func createSignatureAccessKey(privateKeyHex, bodyString string) (payload *models.AuthPayload, err error) { // No key? if privateKeyHex == "" { - err = apierrors.ErrMissingAccessKey + err = CreateErrorResponse("error-unauthorized-missing-access-key", "missing access key") return } @@ -503,7 +504,7 @@ func createSignatureAccessKey(privateKeyHex, bodyString string) (payload *models // doHTTPRequest will create and submit the HTTP request func (wc *WalletClient) doHTTPRequest(ctx context.Context, method string, path string, rawJSON []byte, xPriv *bip32.ExtendedKey, sign bool, responseJSON interface{}, -) ResponseError { +) error { req, err := http.NewRequestWithContext(ctx, method, wc.server+path, bytes.NewBuffer(rawJSON)) if err != nil { return WrapError(err) @@ -546,7 +547,7 @@ func (wc *WalletClient) doHTTPRequest(ctx context.Context, method string, path s return nil } -func (wc *WalletClient) authenticateWithXpriv(sign bool, req *http.Request, xPriv *bip32.ExtendedKey, rawJSON []byte) ResponseError { +func (wc *WalletClient) authenticateWithXpriv(sign bool, req *http.Request, xPriv *bip32.ExtendedKey, rawJSON []byte) error { if sign { if err := addSignature(&req.Header, xPriv, string(rawJSON)); err != nil { return err @@ -563,12 +564,15 @@ func (wc *WalletClient) authenticateWithXpriv(sign bool, req *http.Request, xPri return nil } -func (wc *WalletClient) authenticateWithAccessKey(req *http.Request, rawJSON []byte) ResponseError { +func (wc *WalletClient) authenticateWithAccessKey(req *http.Request, rawJSON []byte) error { + if wc.accessKey == nil { + return WrapError(errors.New("access key is missing")) + } return SetSignatureFromAccessKey(&req.Header, hex.EncodeToString(wc.accessKey.Serialise()), string(rawJSON)) } // AcceptContact will accept the contact associated with the paymail -func (wc *WalletClient) AcceptContact(ctx context.Context, paymail string) ResponseError { +func (wc *WalletClient) AcceptContact(ctx context.Context, paymail string) error { if err := wc.doHTTPRequest( ctx, http.MethodPatch, "/contact/accepted/"+paymail, nil, wc.xPriv, wc.signRequest, nil, ); err != nil { @@ -579,7 +583,7 @@ func (wc *WalletClient) AcceptContact(ctx context.Context, paymail string) Respo } // RejectContact will reject the contact associated with the paymail -func (wc *WalletClient) RejectContact(ctx context.Context, paymail string) ResponseError { +func (wc *WalletClient) RejectContact(ctx context.Context, paymail string) error { if err := wc.doHTTPRequest( ctx, http.MethodPatch, "/contact/rejected/"+paymail, nil, wc.xPriv, wc.signRequest, nil, ); err != nil { @@ -590,7 +594,7 @@ func (wc *WalletClient) RejectContact(ctx context.Context, paymail string) Respo } // ConfirmContact will confirm the contact associated with the paymail -func (wc *WalletClient) ConfirmContact(ctx context.Context, contact *models.Contact, passcode, requesterPaymail string, period, digits uint) ResponseError { +func (wc *WalletClient) ConfirmContact(ctx context.Context, contact *models.Contact, passcode, requesterPaymail string, period, digits uint) error { isTotpValid, err := wc.ValidateTotpForContact(contact, passcode, requesterPaymail, period, digits) if err != nil { return WrapError(fmt.Errorf("totp validation failed: %w", err)) @@ -610,7 +614,7 @@ func (wc *WalletClient) ConfirmContact(ctx context.Context, contact *models.Cont } // GetContacts will get contacts by conditions -func (wc *WalletClient) GetContacts(ctx context.Context, conditions *filter.ContactFilter, metadata map[string]any, queryParams *filter.QueryParams) (*models.SearchContactsResponse, ResponseError) { +func (wc *WalletClient) GetContacts(ctx context.Context, conditions *filter.ContactFilter, metadata map[string]any, queryParams *filter.QueryParams) (*models.SearchContactsResponse, error) { return Search[filter.ContactFilter, *models.SearchContactsResponse]( ctx, http.MethodPost, "/contact/search", @@ -623,12 +627,12 @@ func (wc *WalletClient) GetContacts(ctx context.Context, conditions *filter.Cont } // UpsertContact add or update contact. When adding a new contact, the system utilizes Paymail's PIKE capability to dispatch an invitation request, asking the counterparty to include the current user in their contacts. -func (wc *WalletClient) UpsertContact(ctx context.Context, paymail, fullName, requesterPaymail string, metadata map[string]any) (*models.Contact, ResponseError) { +func (wc *WalletClient) UpsertContact(ctx context.Context, paymail, fullName, requesterPaymail string, metadata map[string]any) (*models.Contact, error) { return wc.UpsertContactForPaymail(ctx, paymail, fullName, metadata, requesterPaymail) } // UpsertContactForPaymail add or update contact. When adding a new contact, the system utilizes Paymail's PIKE capability to dispatch an invitation request, asking the counterparty to include the current user in their contacts. -func (wc *WalletClient) UpsertContactForPaymail(ctx context.Context, paymail, fullName string, metadata map[string]any, requesterPaymail string) (*models.Contact, ResponseError) { +func (wc *WalletClient) UpsertContactForPaymail(ctx context.Context, paymail, fullName string, metadata map[string]any, requesterPaymail string) (*models.Contact, error) { payload := map[string]interface{}{ "fullName": fullName, FieldMetadata: metadata, @@ -654,7 +658,7 @@ func (wc *WalletClient) UpsertContactForPaymail(ctx context.Context, paymail, fu } // GetSharedConfig gets the shared config -func (wc *WalletClient) GetSharedConfig(ctx context.Context) (*models.SharedConfig, ResponseError) { +func (wc *WalletClient) GetSharedConfig(ctx context.Context) (*models.SharedConfig, error) { var model *models.SharedConfig key := wc.xPriv @@ -674,7 +678,7 @@ func (wc *WalletClient) GetSharedConfig(ctx context.Context) (*models.SharedConf } // AdminNewXpub will register an xPub -func (wc *WalletClient) AdminNewXpub(ctx context.Context, rawXPub string, metadata map[string]any) ResponseError { +func (wc *WalletClient) AdminNewXpub(ctx context.Context, rawXPub string, metadata map[string]any) error { // Adding a xpub needs to be signed by an admin key if wc.adminXPriv == nil { return WrapError(ErrAdminKey) @@ -696,7 +700,7 @@ func (wc *WalletClient) AdminNewXpub(ctx context.Context, rawXPub string, metada } // AdminGetStatus get whether admin key is valid -func (wc *WalletClient) AdminGetStatus(ctx context.Context) (bool, ResponseError) { +func (wc *WalletClient) AdminGetStatus(ctx context.Context) (bool, error) { var status bool if err := wc.doHTTPRequest( ctx, http.MethodGet, "/admin/status", nil, wc.adminXPriv, true, &status, @@ -708,7 +712,7 @@ func (wc *WalletClient) AdminGetStatus(ctx context.Context) (bool, ResponseError } // AdminGetStats get admin stats -func (wc *WalletClient) AdminGetStats(ctx context.Context) (*models.AdminStats, ResponseError) { +func (wc *WalletClient) AdminGetStats(ctx context.Context) (*models.AdminStats, error) { var stats *models.AdminStats if err := wc.doHTTPRequest( ctx, http.MethodGet, "/admin/stats", nil, wc.adminXPriv, true, &stats, @@ -725,7 +729,7 @@ func (wc *WalletClient) AdminGetAccessKeys( conditions *filter.AdminAccessKeyFilter, metadata map[string]any, queryParams *filter.QueryParams, -) ([]*models.AccessKey, ResponseError) { +) ([]*models.AccessKey, error) { return Search[filter.AdminAccessKeyFilter, []*models.AccessKey]( ctx, http.MethodPost, "/admin/access-keys/search", @@ -742,7 +746,7 @@ func (wc *WalletClient) AdminGetAccessKeysCount( ctx context.Context, conditions *filter.AdminAccessKeyFilter, metadata map[string]any, -) (int64, ResponseError) { +) (int64, error) { return Count[filter.AdminAccessKeyFilter]( ctx, http.MethodPost, "/admin/access-keys/count", @@ -759,7 +763,7 @@ func (wc *WalletClient) AdminGetBlockHeaders( conditions map[string]interface{}, metadata map[string]any, queryParams *filter.QueryParams, -) ([]*models.BlockHeader, ResponseError) { +) ([]*models.BlockHeader, error) { var models []*models.BlockHeader if err := wc.adminGetModels(ctx, conditions, metadata, queryParams, "/admin/block-headers/search", &models); err != nil { return nil, err @@ -773,14 +777,14 @@ func (wc *WalletClient) AdminGetBlockHeadersCount( ctx context.Context, conditions map[string]interface{}, metadata map[string]any, -) (int64, ResponseError) { +) (int64, error) { return wc.adminCount(ctx, conditions, metadata, "/admin/block-headers/count") } // AdminGetDestinations get all block destinations filtered by conditions func (wc *WalletClient) AdminGetDestinations(ctx context.Context, conditions *filter.DestinationFilter, metadata map[string]any, queryParams *filter.QueryParams, -) ([]*models.Destination, ResponseError) { +) ([]*models.Destination, error) { return Search[filter.DestinationFilter, []*models.Destination]( ctx, http.MethodPost, "/admin/destinations/search", @@ -793,7 +797,7 @@ func (wc *WalletClient) AdminGetDestinations(ctx context.Context, conditions *fi } // AdminGetDestinationsCount get a count of all the destinations filtered by conditions -func (wc *WalletClient) AdminGetDestinationsCount(ctx context.Context, conditions *filter.DestinationFilter, metadata map[string]any) (int64, ResponseError) { +func (wc *WalletClient) AdminGetDestinationsCount(ctx context.Context, conditions *filter.DestinationFilter, metadata map[string]any) (int64, error) { return Count( ctx, http.MethodPost, @@ -806,7 +810,7 @@ func (wc *WalletClient) AdminGetDestinationsCount(ctx context.Context, condition } // AdminGetPaymail get a paymail by address -func (wc *WalletClient) AdminGetPaymail(ctx context.Context, address string) (*models.PaymailAddress, ResponseError) { +func (wc *WalletClient) AdminGetPaymail(ctx context.Context, address string) (*models.PaymailAddress, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldAddress: address, }) @@ -830,7 +834,7 @@ func (wc *WalletClient) AdminGetPaymails( conditions *filter.AdminPaymailFilter, metadata map[string]any, queryParams *filter.QueryParams, -) ([]*models.PaymailAddress, ResponseError) { +) ([]*models.PaymailAddress, error) { return Search[filter.AdminPaymailFilter, []*models.PaymailAddress]( ctx, http.MethodPost, "/admin/paymails/search", @@ -843,7 +847,7 @@ func (wc *WalletClient) AdminGetPaymails( } // AdminGetPaymailsCount get a count of all the paymails filtered by conditions -func (wc *WalletClient) AdminGetPaymailsCount(ctx context.Context, conditions *filter.AdminPaymailFilter, metadata map[string]any) (int64, ResponseError) { +func (wc *WalletClient) AdminGetPaymailsCount(ctx context.Context, conditions *filter.AdminPaymailFilter, metadata map[string]any) (int64, error) { return Count( ctx, http.MethodPost, "/admin/paymails/count", @@ -855,7 +859,7 @@ func (wc *WalletClient) AdminGetPaymailsCount(ctx context.Context, conditions *f } // AdminCreatePaymail create a new paymail for a xpub -func (wc *WalletClient) AdminCreatePaymail(ctx context.Context, rawXPub string, address string, publicName string, avatar string) (*models.PaymailAddress, ResponseError) { +func (wc *WalletClient) AdminCreatePaymail(ctx context.Context, rawXPub string, address string, publicName string, avatar string) (*models.PaymailAddress, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldXpubKey: rawXPub, FieldAddress: address, @@ -877,7 +881,7 @@ func (wc *WalletClient) AdminCreatePaymail(ctx context.Context, rawXPub string, } // AdminDeletePaymail delete a paymail address from the database -func (wc *WalletClient) AdminDeletePaymail(ctx context.Context, address string) ResponseError { +func (wc *WalletClient) AdminDeletePaymail(ctx context.Context, address string) error { jsonStr, err := json.Marshal(map[string]interface{}{ FieldAddress: address, }) @@ -900,7 +904,7 @@ func (wc *WalletClient) AdminGetTransactions( conditions *filter.TransactionFilter, metadata map[string]any, queryParams *filter.QueryParams, -) ([]*models.Transaction, ResponseError) { +) ([]*models.Transaction, error) { return Search[filter.TransactionFilter, []*models.Transaction]( ctx, http.MethodPost, "/admin/transactions/search", @@ -917,7 +921,7 @@ func (wc *WalletClient) AdminGetTransactionsCount( ctx context.Context, conditions *filter.TransactionFilter, metadata map[string]any, -) (int64, ResponseError) { +) (int64, error) { return Count[filter.TransactionFilter]( ctx, http.MethodPost, "/admin/transactions/count", @@ -934,7 +938,7 @@ func (wc *WalletClient) AdminGetUtxos( conditions *filter.AdminUtxoFilter, metadata map[string]any, queryParams *filter.QueryParams, -) ([]*models.Utxo, ResponseError) { +) ([]*models.Utxo, error) { return Search[filter.AdminUtxoFilter, []*models.Utxo]( ctx, http.MethodPost, "/admin/utxos/search", @@ -951,7 +955,7 @@ func (wc *WalletClient) AdminGetUtxosCount( ctx context.Context, conditions *filter.AdminUtxoFilter, metadata map[string]any, -) (int64, ResponseError) { +) (int64, error) { return Count[filter.AdminUtxoFilter]( ctx, http.MethodPost, "/admin/utxos/count", @@ -965,7 +969,7 @@ func (wc *WalletClient) AdminGetUtxosCount( // AdminGetXPubs get all block xpubs filtered by conditions func (wc *WalletClient) AdminGetXPubs(ctx context.Context, conditions *filter.XpubFilter, metadata map[string]any, queryParams *filter.QueryParams, -) ([]*models.Xpub, ResponseError) { +) ([]*models.Xpub, error) { return Search[filter.XpubFilter, []*models.Xpub]( ctx, http.MethodPost, "/admin/xpubs/search", @@ -982,7 +986,7 @@ func (wc *WalletClient) AdminGetXPubsCount( ctx context.Context, conditions *filter.XpubFilter, metadata map[string]any, -) (int64, ResponseError) { +) (int64, error) { return Count[filter.XpubFilter]( ctx, http.MethodPost, "/admin/xpubs/count", @@ -1000,7 +1004,7 @@ func (wc *WalletClient) adminGetModels( queryParams *filter.QueryParams, path string, models interface{}, -) ResponseError { +) error { jsonStr, err := json.Marshal(map[string]interface{}{ FieldConditions: conditions, FieldMetadata: metadata, @@ -1019,7 +1023,7 @@ func (wc *WalletClient) adminGetModels( return nil } -func (wc *WalletClient) adminCount(ctx context.Context, conditions map[string]interface{}, metadata map[string]any, path string) (int64, ResponseError) { +func (wc *WalletClient) adminCount(ctx context.Context, conditions map[string]interface{}, metadata map[string]any, path string) (int64, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldConditions: conditions, FieldMetadata: metadata, @@ -1039,7 +1043,7 @@ func (wc *WalletClient) adminCount(ctx context.Context, conditions map[string]in } // AdminRecordTransaction will record a transaction as an admin -func (wc *WalletClient) AdminRecordTransaction(ctx context.Context, hex string) (*models.Transaction, ResponseError) { +func (wc *WalletClient) AdminRecordTransaction(ctx context.Context, hex string) (*models.Transaction, error) { jsonStr, err := json.Marshal(map[string]interface{}{ FieldHex: hex, }) @@ -1058,7 +1062,7 @@ func (wc *WalletClient) AdminRecordTransaction(ctx context.Context, hex string) } // AdminGetContacts executes an HTTP POST request to search for contacts based on specified conditions, metadata, and query parameters. -func (wc *WalletClient) AdminGetContacts(ctx context.Context, conditions *filter.ContactFilter, metadata map[string]any, queryParams *filter.QueryParams) (*models.SearchContactsResponse, ResponseError) { +func (wc *WalletClient) AdminGetContacts(ctx context.Context, conditions *filter.ContactFilter, metadata map[string]any, queryParams *filter.QueryParams) (*models.SearchContactsResponse, error) { return Search[filter.ContactFilter, *models.SearchContactsResponse]( ctx, http.MethodPost, "/admin/contact/search", @@ -1071,7 +1075,7 @@ func (wc *WalletClient) AdminGetContacts(ctx context.Context, conditions *filter } // AdminUpdateContact executes an HTTP PATCH request to update a specific contact's full name using their ID. -func (wc *WalletClient) AdminUpdateContact(ctx context.Context, id, fullName string, metadata map[string]any) (*models.Contact, ResponseError) { +func (wc *WalletClient) AdminUpdateContact(ctx context.Context, id, fullName string, metadata map[string]any) (*models.Contact, error) { jsonStr, err := json.Marshal(map[string]interface{}{ "fullName": fullName, FieldMetadata: metadata, @@ -1085,27 +1089,27 @@ func (wc *WalletClient) AdminUpdateContact(ctx context.Context, id, fullName str } // AdminDeleteContact executes an HTTP DELETE request to remove a contact using their ID. -func (wc *WalletClient) AdminDeleteContact(ctx context.Context, id string) ResponseError { +func (wc *WalletClient) AdminDeleteContact(ctx context.Context, id string) error { err := wc.doHTTPRequest(ctx, http.MethodDelete, fmt.Sprintf("/admin/contact/%s", id), nil, wc.adminXPriv, true, nil) return WrapError(err) } // AdminAcceptContact executes an HTTP PATCH request to mark a contact as accepted using their ID. -func (wc *WalletClient) AdminAcceptContact(ctx context.Context, id string) (*models.Contact, ResponseError) { +func (wc *WalletClient) AdminAcceptContact(ctx context.Context, id string) (*models.Contact, error) { var contact models.Contact err := wc.doHTTPRequest(ctx, http.MethodPatch, fmt.Sprintf("/admin/contact/accepted/%s", id), nil, wc.adminXPriv, true, &contact) return &contact, WrapError(err) } // AdminRejectContact executes an HTTP PATCH request to mark a contact as rejected using their ID. -func (wc *WalletClient) AdminRejectContact(ctx context.Context, id string) (*models.Contact, ResponseError) { +func (wc *WalletClient) AdminRejectContact(ctx context.Context, id string) (*models.Contact, error) { var contact models.Contact err := wc.doHTTPRequest(ctx, http.MethodPatch, fmt.Sprintf("/admin/contact/rejected/%s", id), nil, wc.adminXPriv, true, &contact) return &contact, WrapError(err) } // FinalizeTransaction will finalize the transaction -func (wc *WalletClient) FinalizeTransaction(draft *models.DraftTransaction) (string, ResponseError) { +func (wc *WalletClient) FinalizeTransaction(draft *models.DraftTransaction) (string, error) { res, err := GetSignedHex(draft, wc.xPriv) if err != nil { return "", WrapError(err) @@ -1115,7 +1119,7 @@ func (wc *WalletClient) FinalizeTransaction(draft *models.DraftTransaction) (str } // SendToRecipients send to recipients -func (wc *WalletClient) SendToRecipients(ctx context.Context, recipients []*Recipients, metadata map[string]any) (*models.Transaction, ResponseError) { +func (wc *WalletClient) SendToRecipients(ctx context.Context, recipients []*Recipients, metadata map[string]any) (*models.Transaction, error) { draft, err := wc.DraftToRecipients(ctx, recipients, metadata) if err != nil { return nil, err diff --git a/search.go b/search.go index 34344a0e..e2f93623 100644 --- a/search.go +++ b/search.go @@ -3,13 +3,12 @@ package walletclient import ( "context" "encoding/json" - "github.com/bitcoin-sv/spv-wallet/models/filter" "github.com/libsv/go-bk/bip32" ) // SearchRequester is a function that sends a request to the server and returns the response. -type SearchRequester func(ctx context.Context, method string, path string, rawJSON []byte, xPriv *bip32.ExtendedKey, sign bool, responseJSON interface{}) ResponseError +type SearchRequester func(ctx context.Context, method string, path string, rawJSON []byte, xPriv *bip32.ExtendedKey, sign bool, responseJSON interface{}) error // Search prepares and sends a search request to the server. func Search[TFilter any, TResp any]( @@ -21,7 +20,7 @@ func Search[TFilter any, TResp any]( metadata map[string]any, queryParams *filter.QueryParams, requester SearchRequester, -) (TResp, ResponseError) { +) (TResp, error) { jsonStr, err := json.Marshal(filter.SearchModel[TFilter]{ ConditionsModel: filter.ConditionsModel[TFilter]{ Conditions: f, @@ -50,7 +49,7 @@ func Count[TFilter any]( f *TFilter, metadata map[string]any, requester SearchRequester, -) (int64, ResponseError) { +) (int64, error) { jsonStr, err := json.Marshal(filter.ConditionsModel[TFilter]{ Conditions: f, Metadata: metadata, diff --git a/walletclient.go b/walletclient.go index e5a50e70..aae8d23f 100644 --- a/walletclient.go +++ b/walletclient.go @@ -78,7 +78,7 @@ func makeClient(configurators ...configurator) *WalletClient { } // addSignature will add the signature to the request -func addSignature(header *http.Header, xPriv *bip32.ExtendedKey, bodyString string) ResponseError { +func addSignature(header *http.Header, xPriv *bip32.ExtendedKey, bodyString string) error { return setSignature(header, xPriv, bodyString) }