Implement NIP-19 bech32-encoded private and public keys

https://github.com/nostr-protocol/nips/blob/master/19.md
This commit is contained in:
Wilson Silva
2023-11-20 09:59:27 +07:00
parent 3fffcd1a4e
commit 3520cf8219
58 changed files with 1189 additions and 104 deletions

View File

@@ -0,0 +1,7 @@
# frozen_string_literal: true
module Nostr
# Base error class
class Error < StandardError
end
end

View File

@@ -0,0 +1,21 @@
# frozen_string_literal: true
module Nostr
# Raised when the human readable part of a Bech32 string is invalid
#
# @api public
#
class InvalidHRPError < KeyValidationError
# Initializes the error
#
# @example
# InvalidHRPError.new('example wrong hrp', 'nsec')
#
# @param given_hrp [String] The given human readable part of the Bech32 string
# @param allowed_hrp [String] The allowed human readable part of the Bech32 string
#
def initialize(given_hrp, allowed_hrp)
super("Invalid hrp: #{given_hrp}. The allowed hrp value for this kind of entity is '#{allowed_hrp}'.")
end
end
end

View File

@@ -0,0 +1,20 @@
# frozen_string_literal: true
module Nostr
# Raised when the private key is in an invalid format
#
# @api public
#
class InvalidKeyFormatError < KeyValidationError
# Initializes the error
#
# @example
# InvalidKeyFormatError.new('private'')
#
# @param [String] key_kind The kind of key that is invalid (public or private)
#
def initialize(key_kind)
super("Only lowercase hexadecimal characters are allowed in #{key_kind} keys.")
end
end
end

View File

@@ -0,0 +1,20 @@
# frozen_string_literal: true
module Nostr
# Raised when the private key's length is not 64 characters
#
# @api public
#
class InvalidKeyLengthError < KeyValidationError
# Initializes the error
#
# @example
# InvalidKeyLengthError.new('private'')
#
# @param [String] key_kind The kind of key that is invalid (public or private)
#
def initialize(key_kind)
super("Invalid #{key_kind} key length. It should have 64 characters.")
end
end
end

View File

@@ -0,0 +1,18 @@
# frozen_string_literal: true
module Nostr
# Raised when the private key is not a string
#
# @api public
#
class InvalidKeyTypeError < KeyValidationError
# Initializes the error
#
# @example
# InvalidKeyTypeError.new('private'')
#
# @param [String] key_kind The kind of key that is invalid (public or private)
#
def initialize(key_kind) = super("Invalid #{key_kind} key type")
end
end

View File

@@ -0,0 +1,6 @@
# frozen_string_literal: true
module Nostr
# Base class for all key validation errors
class KeyValidationError < Error; end
end