github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/crypto/keys/keyerror/errors.go (about)

     1  package keyerror
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  )
     7  
     8  const (
     9  	codeKeyNotFound   = 1
    10  	codeWrongPassword = 2
    11  )
    12  
    13  type keybaseError interface {
    14  	error
    15  	Code() int
    16  }
    17  
    18  type keyNotFoundError struct {
    19  	code int
    20  	name string
    21  }
    22  
    23  func (e keyNotFoundError) Code() int {
    24  	return e.code
    25  }
    26  
    27  func (e keyNotFoundError) Error() string {
    28  	return fmt.Sprintf("Key %s not found", e.name)
    29  }
    30  
    31  // NewErrKeyNotFound returns a standardized error reflecting that the specified key doesn't exist
    32  func NewErrKeyNotFound(name string) error {
    33  	return keyNotFoundError{
    34  		code: codeKeyNotFound,
    35  		name: name,
    36  	}
    37  }
    38  
    39  // IsErrKeyNotFound returns true if the given error is keyNotFoundError
    40  func IsErrKeyNotFound(err error) bool {
    41  	if err == nil {
    42  		return false
    43  	}
    44  	var keyErr keybaseError
    45  	if errors.As(err, &keyErr) {
    46  		if keyErr.Code() == codeKeyNotFound {
    47  			return true
    48  		}
    49  	}
    50  	return false
    51  }
    52  
    53  type wrongPasswordError struct {
    54  	code int
    55  }
    56  
    57  func (e wrongPasswordError) Code() int {
    58  	return e.code
    59  }
    60  
    61  func (e wrongPasswordError) Error() string {
    62  	return "invalid account password"
    63  }
    64  
    65  // NewErrWrongPassword returns a standardized error reflecting that the specified password is wrong
    66  func NewErrWrongPassword() error {
    67  	return wrongPasswordError{
    68  		code: codeWrongPassword,
    69  	}
    70  }
    71  
    72  // IsErrWrongPassword returns true if the given error is wrongPasswordError
    73  func IsErrWrongPassword(err error) bool {
    74  	if err == nil {
    75  		return false
    76  	}
    77  	var keyErr keybaseError
    78  	if errors.As(err, &keyErr) {
    79  		if keyErr.Code() == codeWrongPassword {
    80  			return true
    81  		}
    82  	}
    83  	return false
    84  }