xrpl-ruby 0.2.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -0
  3. data/LICENSE +21 -0
  4. data/README.md +94 -0
  5. data/lib/address-codec/address_codec.rb +21 -4
  6. data/lib/address-codec/codec.rb +15 -2
  7. data/lib/address-codec/xrp_codec.rb +29 -2
  8. data/lib/binary-codec/binary_codec.rb +47 -21
  9. data/lib/binary-codec/enums/definitions.json +592 -1
  10. data/lib/binary-codec/enums/definitions.rb +23 -9
  11. data/lib/binary-codec/enums/fields.rb +3 -1
  12. data/lib/binary-codec/serdes/binary_parser.rb +44 -10
  13. data/lib/binary-codec/serdes/binary_serializer.rb +29 -6
  14. data/lib/binary-codec/serdes/bytes_list.rb +12 -1
  15. data/lib/binary-codec/types/account_id.rb +18 -37
  16. data/lib/binary-codec/types/amount.rb +123 -77
  17. data/lib/binary-codec/types/blob.rb +14 -5
  18. data/lib/binary-codec/types/currency.rb +15 -4
  19. data/lib/binary-codec/types/hash.rb +37 -36
  20. data/lib/binary-codec/types/issue.rb +47 -0
  21. data/lib/binary-codec/types/path_set.rb +93 -0
  22. data/lib/binary-codec/types/serialized_type.rb +52 -28
  23. data/lib/binary-codec/types/st_array.rb +106 -0
  24. data/lib/binary-codec/types/st_object.rb +150 -14
  25. data/lib/binary-codec/types/uint.rb +166 -3
  26. data/lib/binary-codec/types/vector256.rb +53 -0
  27. data/lib/binary-codec/types/xchain_bridge.rb +47 -0
  28. data/lib/binary-codec/utilities.rb +18 -0
  29. data/lib/core/base_58_xrp.rb +2 -0
  30. data/lib/core/base_x.rb +10 -0
  31. data/lib/core/core.rb +44 -6
  32. data/lib/core/utilities.rb +38 -0
  33. data/lib/key-pairs/ed25519.rb +69 -0
  34. data/lib/key-pairs/key_pairs.rb +92 -0
  35. data/lib/key-pairs/secp256k1.rb +169 -0
  36. data/lib/wallet/wallet.rb +179 -0
  37. data/lib/xrpl/client.rb +498 -0
  38. data/lib/xrpl/faucet.rb +138 -0
  39. data/lib/xrpl/version.rb +5 -0
  40. data/lib/xrpl-ruby.rb +30 -1
  41. metadata +80 -4
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BinaryCodec
4
+ class XChainBridge < SerializedType
5
+ def initialize(bytes = nil)
6
+ super(bytes || [])
7
+ end
8
+
9
+ def self.from(value)
10
+ return value if value.is_a?(XChainBridge)
11
+
12
+ if value.is_a?(String)
13
+ return XChainBridge.new(hex_to_bytes(value))
14
+ end
15
+
16
+ if value.is_a?(::Hash)
17
+ bytes = []
18
+ bytes.concat(AccountId.from(value['LockingChainDoor']).to_bytes)
19
+ bytes.concat(Issue.from(value['LockingChainIssue']).to_bytes)
20
+ bytes.concat(AccountId.from(value['IssuingChainDoor']).to_bytes)
21
+ bytes.concat(Issue.from(value['IssuingChainIssue']).to_bytes)
22
+ return XChainBridge.new(bytes)
23
+ end
24
+
25
+ raise StandardError, "Cannot construct XChainBridge from #{value.class}"
26
+ end
27
+
28
+ def self.from_parser(parser, _hint = nil)
29
+ bytes = []
30
+ bytes.concat(parser.read(20)) # LockingChainDoor
31
+ bytes.concat(Issue.from_parser(parser, 40).to_bytes) # LockingChainIssue
32
+ bytes.concat(parser.read(20)) # IssuingChainDoor
33
+ bytes.concat(Issue.from_parser(parser, 40).to_bytes) # IssuingChainIssue
34
+ XChainBridge.new(bytes)
35
+ end
36
+
37
+ def to_json(_definitions = nil, _field_name = nil)
38
+ parser = BinaryParser.new(to_hex)
39
+ result = {}
40
+ result['LockingChainDoor'] = AccountId.from_parser(parser).to_json
41
+ result['LockingChainIssue'] = Issue.from_parser(parser, 40).to_json
42
+ result['IssuingChainDoor'] = AccountId.from_parser(parser).to_json
43
+ result['IssuingChainIssue'] = Issue.from_parser(parser, 40).to_json
44
+ result
45
+ end
46
+ end
47
+ end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module BinaryCodec
2
4
 
3
5
  # Write an 8-bit unsigned integer
@@ -77,4 +79,20 @@ module BinaryCodec
77
79
  (array.length % 4).zero?
78
80
  end
79
81
 
82
+ # TODO: Marked for overhaul
83
+ def self.is_valid_x_address?(x_address)
84
+ return false unless x_address.is_a?(String) && x_address.start_with?('X')
85
+
86
+ begin
87
+ decoded = decode_x_address(x_address)
88
+ return false if decoded[:account_id].nil? || decoded[:account_id].length != 20
89
+
90
+ tag = decoded[:tag]
91
+ return false if tag && (tag < 0 || tag > MAX_32_BIT_UNSIGNED_INT)
92
+
93
+ true
94
+ rescue StandardError
95
+ false
96
+ end
97
+ end
80
98
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Core
2
4
 
3
5
  class Base58XRP < BaseX
data/lib/core/base_x.rb CHANGED
@@ -1,6 +1,10 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Core
2
4
 
3
5
  class BaseX
6
+ # Initializes a new BaseX instance with the given alphabet.
7
+ # @param alphabet [String] The alphabet to use for encoding and decoding.
4
8
  def initialize(alphabet)
5
9
  @alphabet = alphabet
6
10
  @base = alphabet.length
@@ -8,6 +12,9 @@ module Core
8
12
  alphabet.chars.each_with_index { |char, index| @alphabet_map[char] = index }
9
13
  end
10
14
 
15
+ # Encodes a byte array into a string using the alphabet.
16
+ # @param buffer [String] The byte string to encode.
17
+ # @return [String] The encoded string.
11
18
  def encode(buffer)
12
19
  return @alphabet[0] if buffer.empty?
13
20
 
@@ -30,6 +37,9 @@ module Core
30
37
  digits.reverse.map { |digit| @alphabet[digit] }.join
31
38
  end
32
39
 
40
+ # Decodes a string into a byte string using the alphabet.
41
+ # @param string [String] The string to decode.
42
+ # @return [String] The decoded byte string.
33
43
  def decode(string)
34
44
  return '' if string.empty?
35
45
 
data/lib/core/core.rb CHANGED
@@ -1,42 +1,70 @@
1
- # @!attribute
2
- require_relative 'base_x'
3
- require_relative 'base_58_xrp'
1
+ # frozen_string_literal: true
2
+
4
3
  require 'securerandom'
5
4
 
5
+ # Returns a random byte array of the given size.
6
+ # @param size [Integer] The number of bytes to generate.
7
+ # @return [Array<Integer>] The generated random byte array.
6
8
  def random_bytes(size)
7
9
  SecureRandom.random_bytes(size).bytes
8
10
  end
9
11
 
12
+ # Converts a byte array to a hex string.
13
+ # @param bytes [Array<Integer>] The byte array to convert.
14
+ # @return [String] The hex string.
10
15
  def bytes_to_hex(bytes)
11
16
  bytes.pack('C*').unpack1('H*').upcase
12
17
  end
18
+ # Converts a hex string to a byte array.
19
+ # @param hex [String] The hex string to convert.
20
+ # @return [Array<Integer>] The byte array.
13
21
  def hex_to_bytes(hex)
14
22
  raise ArgumentError, 'Invalid hex string' unless valid_hex?(hex)
15
23
  [hex].pack('H*').bytes
16
24
  end
17
25
 
26
+ # Converts a binary string to a hex string.
27
+ # @param bin [String] The binary string to convert.
28
+ # @return [String] The hex string.
18
29
  def bin_to_hex(bin)
19
30
  bin.unpack("H*").first.upcase
20
31
  end
21
32
 
33
+ # Converts a hex string to a binary string.
34
+ # @param hex [String] The hex string to convert.
35
+ # @return [String] The binary string.
22
36
  def hex_to_bin(hex)
23
37
  raise ArgumentError, 'Invalid hex string' unless valid_hex?(hex)
24
38
  [hex].pack("H*")
25
39
  end
26
40
 
41
+ # Converts a hex string to a string with the given encoding.
42
+ # @param hex [String] The hex string to convert.
43
+ # @param encoding [String] The encoding to use.
44
+ # @return [String] The decoded string.
27
45
  def hex_to_string(hex, encoding = 'utf-8')
28
46
  raise ArgumentError, 'Invalid hex string' unless valid_hex?(hex)
29
47
  hex_to_bin(hex).force_encoding(encoding).encode('utf-8')
30
48
  end
31
49
 
50
+ # Converts a string to a hex string.
51
+ # @param string [String] The string to convert.
52
+ # @return [String] The hex string.
32
53
  def string_to_hex(string)
33
54
  string.unpack1('H*').upcase
34
55
  end
35
56
 
57
+ # Checks if a string is a valid hex string.
58
+ # @param str [String] The string to check.
59
+ # @return [Boolean] True if the string is a valid hex string, false otherwise.
36
60
  def valid_hex?(str)
37
61
  str =~ /\A[0-9a-fA-F]*\z/ && str.length.even?
38
62
  end
39
63
 
64
+ # Checks if a byte array has the expected length.
65
+ # @param bytes [Array<Integer>, String] The byte array or string to check.
66
+ # @param expected_length [Integer] The expected length.
67
+ # @return [Boolean] True if the length matches, false otherwise.
40
68
  def check_byte_length(bytes, expected_length)
41
69
  if bytes.respond_to?(:byte_length)
42
70
  bytes.byte_length == expected_length
@@ -45,24 +73,34 @@ def check_byte_length(bytes, expected_length)
45
73
  end
46
74
  end
47
75
 
76
+ # Concatenates multiple arguments into a single array.
77
+ # @param args [Array] The arguments to concatenate.
78
+ # @return [Array] The concatenated array.
48
79
  def concat_args(*args)
49
80
  args.flat_map do |arg|
50
81
  is_scalar?(arg) ? [arg] : arg.to_a
51
82
  end
52
83
  end
53
84
 
85
+ # Checks if a value is a scalar.
86
+ # @param val [Object] The value to check.
87
+ # @return [Boolean] True if the value is a numeric scalar, false otherwise.
54
88
  def is_scalar?(val)
55
89
  val.is_a?(Numeric)
56
90
  end
57
91
 
92
+ # Converts an integer to a byte array.
93
+ # @param number [Integer] The integer to convert.
94
+ # @param width [Integer] The number of bytes in the result.
95
+ # @param byteorder [Symbol] The byte order (:big or :little).
96
+ # @return [Array<Integer>] The byte array.
58
97
  def int_to_bytes(number, width = 1, byteorder = :big)
59
98
  bytes = []
60
99
  while number > 0
61
- bytes << (number & 0xFF) # Extract the lowest 8 bits (1 byte)
62
- number >>= 8 # Shift the number 8 bits to the right
100
+ bytes << (number & 0xFF)
101
+ number >>= 8
63
102
  end
64
103
 
65
- # Ensure the result has at least `width` bytes (pad with zeroes if necessary)
66
104
  while bytes.size < width
67
105
  bytes << 0
68
106
  end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Core
4
+
5
+ class Utilities
6
+
7
+ @address_codec = nil
8
+
9
+ def initialize
10
+ @address_codec = AddressCodec.new
11
+ end
12
+
13
+ # Returns the singleton instance of the Utilities class.
14
+ # @return [Utilities] The singleton instance.
15
+ def self.instance
16
+ @@instance ||= new
17
+ end
18
+
19
+ # Checks if a string is a valid X-address.
20
+ # @param x_address [String] The X-address to check.
21
+ # @return [Boolean] True if the string is a valid X-address, false otherwise.
22
+ def is_x_address?(x_address)
23
+ return false unless x_address.is_a?(String) && x_address.start_with?('X')
24
+
25
+ begin
26
+ decoded = @address_codec.decode_x_address(x_address)
27
+ return false if decoded[:account_id].nil? || decoded[:account_id].length != 20
28
+
29
+ tag = decoded[:tag]
30
+ return false if tag && (tag < 0 || tag > MAX_32_BIT_UNSIGNED_INT)
31
+
32
+ true
33
+ rescue StandardError
34
+ false
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ed25519'
4
+
5
+ module KeyPairs
6
+ # Ed25519 implementation for XRPL key pairs.
7
+ module Ed25519
8
+ # Derives a key pair from a seed.
9
+ # @param seed [Array<Integer>] 16 bytes of seed entropy.
10
+ # @return [Hash] A hash containing :public_key and :private_key (hex strings).
11
+ def self.derive_key_pair(seed)
12
+ # XRPL Ed25519 uses the SHA512 of the 16-byte seed as the 32-byte entropy for the signing key.
13
+ seed_bytes = seed.is_a?(Array) ? seed.pack('C*') : seed
14
+ hash = Digest::SHA512.digest(seed_bytes)[0...32]
15
+ signing_key = ::Ed25519::SigningKey.new(hash)
16
+
17
+ # Public key in XRPL is 0xED followed by 32 bytes of public key.
18
+ public_key = [0xED].pack('C') + signing_key.verify_key.to_bytes
19
+
20
+ # Private key in XRPL is 0xED followed by the 32-byte hash.
21
+ private_key = [0xED].pack('C') + hash
22
+
23
+ {
24
+ public_key: public_key.unpack1('H*').upcase,
25
+ private_key: private_key.unpack1('H*').upcase
26
+ }
27
+ end
28
+
29
+ # Signs a message with a private key.
30
+ # @param message [Array<Integer>, String] The message to sign.
31
+ # @param private_key [String] The private key (32-byte hash as hex).
32
+ # @return [String] The signature (hex string).
33
+ def self.sign(message, private_key)
34
+ msg_bytes = message.is_a?(String) ? [message].pack('H*') : message.pack('C*')
35
+ key_bytes = [private_key].pack('H*')
36
+ # In XRPL, Ed25519 private keys are often prefixed with 0xED (33 bytes).
37
+ # The ed25519 gem expects 32 bytes.
38
+ key_bytes = key_bytes[1..-1] if key_bytes.length == 33 && key_bytes[0].ord == 0xED
39
+ signing_key = ::Ed25519::SigningKey.new(key_bytes)
40
+
41
+ signature = signing_key.sign(msg_bytes)
42
+ signature.unpack1('H*').upcase
43
+ end
44
+
45
+ # Verifies a signature.
46
+ # @param message [Array<Integer>, String] The message.
47
+ # @param signature [String] The signature (hex string).
48
+ # @param public_key [String] The public key (33-byte hex, starts with ED).
49
+ # @return [Boolean] True if the signature is valid.
50
+ def self.verify(message, signature, public_key)
51
+ msg_bytes = message.is_a?(String) ? hex_to_bin(message) : message.pack('C*')
52
+ sig_bytes = [signature].pack('H*')
53
+
54
+ # Strip the 0xED prefix from the public key
55
+ pub_bytes = [public_key].pack('H*')
56
+ if pub_bytes[0].ord != 0xED
57
+ raise ArgumentError, "Invalid Ed25519 public key prefix"
58
+ end
59
+
60
+ verify_key = ::Ed25519::VerifyKey.new(pub_bytes[1..-1])
61
+ begin
62
+ verify_key.verify(sig_bytes, msg_bytes)
63
+ true
64
+ rescue ::Ed25519::VerifyError
65
+ false
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+
5
+ module KeyPairs
6
+ # Main entry point for XRPL key pair operations.
7
+ class KeyPairs
8
+ def initialize
9
+ @address_codec = AddressCodec::AddressCodec.new
10
+ end
11
+
12
+ # Generates a new seed.
13
+ # @param entropy [Array<Integer>, nil] 16 bytes of entropy.
14
+ # @param type [String] The seed type ('secp256k1' or 'ed25519').
15
+ # @return [String] The encoded seed string.
16
+ def generate_seed(entropy = nil, type = 'secp256k1')
17
+ entropy ||= SecureRandom.random_bytes(16).bytes
18
+ @address_codec.encode_seed(entropy, type)
19
+ end
20
+
21
+ # Derives a key pair from an encoded seed.
22
+ # @param seed [String] The encoded seed string.
23
+ # @param options [Hash] Options including :account_index (for secp256k1).
24
+ # @return [Hash] A hash containing :public_key and :private_key (hex strings).
25
+ def derive_key_pair(seed, options = {})
26
+ decoded = @address_codec.decode_seed(seed)
27
+ type = decoded[:type]
28
+ entropy = decoded[:bytes]
29
+
30
+ if type == 'ed25519'
31
+ Ed25519.derive_key_pair(entropy)
32
+ else
33
+ # For secp256k1, we use the entropy as seed
34
+ Secp256k1.derive_key_pair(entropy)
35
+ end
36
+ end
37
+
38
+ # Signs a message with a private key.
39
+ # @param message [String] The message to sign as hex.
40
+ # @param private_key [String] The private key as hex.
41
+ # @param algorithm [String, nil] The algorithm to use ('secp256k1' or 'ed25519').
42
+ # @return [String] The signature as hex.
43
+ def sign(message, private_key, algorithm = nil)
44
+ if algorithm == 'ed25519' || (algorithm.nil? && private_key.length == 64)
45
+ # Heuristic: Ed25519 private keys in our lib are 32 bytes (64 hex chars).
46
+ # Secp256k1 are also 32 bytes, but Ed25519 is often explicitly requested.
47
+ # Actually, let's look at the prefix of the public key if we had it.
48
+ # Since we don't have the public key here, we rely on the caller or length.
49
+ # In XRPL-Ruby, Ed25519 private keys are 64 hex chars (32 bytes).
50
+ # Secp256k1 are also 64 hex chars. This is ambiguous!
51
+ # Let's try to see if it's explicitly 'ed25519'.
52
+ begin
53
+ return Ed25519.sign(message, private_key) if algorithm == 'ed25519'
54
+ return Secp256k1.sign(message, private_key)
55
+ rescue => e
56
+ # If secp fails and we didn't specify, maybe it was ed?
57
+ # But that's dangerous.
58
+ raise e
59
+ end
60
+ else
61
+ Secp256k1.sign(message, private_key)
62
+ end
63
+ end
64
+
65
+ # Verifies a signature.
66
+ # @param message [String] The message as hex.
67
+ # @param signature [String] The signature as hex.
68
+ # @param public_key [String] The public key as hex.
69
+ # @return [Boolean] True if the signature is valid.
70
+ def verify(message, signature, public_key)
71
+ if public_key.start_with?('ED')
72
+ Ed25519.verify(message, signature, public_key)
73
+ else
74
+ Secp256k1.verify(message, signature, public_key)
75
+ end
76
+ end
77
+
78
+ # Derives an XRP address from a public key.
79
+ # @param public_key [String] The public key as hex.
80
+ # @return [String] The XRP address.
81
+ def derive_address(public_key)
82
+ public_key_bytes = [public_key].pack('H*')
83
+ # Account ID is RIPEMD160(SHA256(public_key))
84
+ sha256 = Digest::SHA256.digest(public_key_bytes)
85
+ # Ruby doesn't have RIPEMD160 in Digest by default sometimes,
86
+ # but OpenSSL has it.
87
+ ripemd160 = OpenSSL::Digest.new('RIPEMD160').digest(sha256)
88
+
89
+ @address_codec.encode_account_id(ripemd160.unpack('C*'))
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'openssl'
4
+ require 'ecdsa'
5
+ require 'digest'
6
+
7
+ module KeyPairs
8
+ # Secp256k1 implementation for XRPL key pairs.
9
+ module Secp256k1
10
+ GROUP = ECDSA::Group::Secp256k1
11
+
12
+ # Derives a key pair from a seed.
13
+ # @param seed [Array<Integer>] 16 bytes of seed entropy.
14
+ # @return [Hash] A hash containing :public_key and :private_key (hex strings).
15
+ def self.derive_key_pair(seed)
16
+ # XRPL Secp256k1 uses a specific derivation algorithm (seed -> family seed -> sequence 0 key).
17
+ # Seed is passed as a 16-byte array.
18
+ private_key = derive_private_key(seed)
19
+ public_key = derive_public_key(private_key)
20
+
21
+ {
22
+ public_key: public_key.unpack1('H*').upcase,
23
+ private_key: private_key.upcase.rjust(66, '00')
24
+ }
25
+ end
26
+
27
+ # Signs a message with a private key.
28
+ # @param message [Array<Integer>, String] The message to sign (hex string or byte array).
29
+ # @param private_key [String] The private key (hex string).
30
+ # @return [String] The signature (hex string).
31
+ def self.sign(message, private_key)
32
+ msg_hash = message.is_a?(String) ? [message].pack('H*') : message.pack('C*')
33
+
34
+ # If message is not already 32 bytes, we hash it.
35
+ # This is a bit of a heuristic. XRPL signs the SHA512Half hash of the serialized transaction.
36
+ if msg_hash.length != 32
37
+ msg_hash = Digest::SHA512.digest(msg_hash)[0...32]
38
+ end
39
+
40
+ priv_key_bn = private_key.to_i(16)
41
+ k = generate_k(priv_key_bn, msg_hash)
42
+ signature = ECDSA.sign(GROUP, priv_key_bn, msg_hash, k)
43
+
44
+ # XRPL requires "canonical" signatures: S <= order / 2
45
+ if signature.s > (GROUP.order / 2)
46
+ signature = ECDSA::Signature.new(signature.r, GROUP.order - signature.s)
47
+ end
48
+
49
+ ECDSA::Format::SignatureDerString.encode(signature).unpack1('H*').upcase
50
+ end
51
+
52
+ # Deterministic k generation (RFC 6979)
53
+ def self.generate_k(private_key_bn, message_hash)
54
+ q = GROUP.order
55
+ q_len = q.bit_length
56
+ holeren = (q_len + 7) / 8
57
+
58
+ # Step b
59
+ v = "\x01" * holeren
60
+ # Step c
61
+ k = "\x00" * holeren
62
+
63
+ # bits2octets(x)
64
+ x_bytes = [private_key_bn.to_s(16).rjust(holeren * 2, '0')].pack('H*')
65
+ # bits2octets(bits2int(h1))
66
+ h1_val = message_hash.unpack1('H*').to_i(16)
67
+ if h1_val >= q
68
+ h1_val %= q
69
+ end
70
+ h1 = [h1_val.to_s(16).rjust(holeren * 2, '0')].pack('H*')
71
+
72
+ # Step d
73
+ k = OpenSSL::HMAC.digest('sha256', k, v + "\x00" + x_bytes + h1)
74
+ # Step e
75
+ v = OpenSSL::HMAC.digest('sha256', k, v)
76
+ # Step f
77
+ k = OpenSSL::HMAC.digest('sha256', k, v + "\x01" + x_bytes + h1)
78
+ # Step g
79
+ v = OpenSSL::HMAC.digest('sha256', k, v)
80
+
81
+ # Step h
82
+ loop do
83
+ t = ""
84
+ while t.length < holeren
85
+ v = OpenSSL::HMAC.digest('sha256', k, v)
86
+ t += v
87
+ end
88
+
89
+ k_val = t[0...holeren].unpack1('H*').to_i(16)
90
+ # bits2int(T)
91
+ if q_len < 8 * holeren
92
+ k_val >>= (8 * holeren - q_len)
93
+ end
94
+
95
+ return k_val if k_val > 0 && k_val < q
96
+
97
+ k = OpenSSL::HMAC.digest('sha256', k, v + "\x00")
98
+ v = OpenSSL::HMAC.digest('sha256', k, v)
99
+ end
100
+ end
101
+
102
+ # Verifies a signature.
103
+ # @param message [Array<Integer>, String] The message (hex string or byte array).
104
+ # @param signature [String] The signature (hex string).
105
+ # @param public_key [String] The public key (hex string).
106
+ # @return [Boolean] True if the signature is valid.
107
+ def self.verify(message, signature, public_key)
108
+ msg_hash = message.is_a?(String) ? [message].pack('H*') : message.pack('C*')
109
+
110
+ # If message is not already 32 bytes, we hash it.
111
+ if msg_hash.length != 32
112
+ msg_hash = Digest::SHA512.digest(msg_hash)[0...32]
113
+ end
114
+
115
+ sig_bytes = [signature].pack('H*')
116
+
117
+ point = ECDSA::Format::PointOctetString.decode([public_key].pack('H*'), GROUP)
118
+ sig = ECDSA::Format::SignatureDerString.decode(sig_bytes)
119
+
120
+ ECDSA.valid_signature?(point, msg_hash, sig)
121
+ end
122
+
123
+ private
124
+
125
+ # Derives the 32-byte private key from the 16-byte seed.
126
+ # This follows the Ripple seed derivation algorithm.
127
+ def self.derive_private_key(seed, account_index = 0)
128
+ # 1. Derive root private key from seed
129
+ root_private_key = derive_scalar(seed)
130
+
131
+ # 2. Derive root public key from root private key
132
+ root_public_key = derive_root_public_key(root_private_key)
133
+
134
+ # 3. Derive child scalar from root public key and account_index
135
+ child_scalar = derive_scalar(root_public_key, account_index)
136
+
137
+ # 4. child_private_key = (root_private_key + child_scalar) % order
138
+ child_private_key = (root_private_key.to_i(16) + child_scalar.to_i(16)) % GROUP.order
139
+ child_private_key.to_s(16).rjust(64, '0')
140
+ end
141
+
142
+ def self.derive_scalar(seed, sequence = nil)
143
+ seed_bytes = seed.is_a?(Array) ? seed.pack('C*') : seed
144
+ loop_count = 0
145
+ loop do
146
+ data = sequence ? seed_bytes + [sequence].pack('N') : seed_bytes
147
+ data += [loop_count].pack('N')
148
+ hash = Digest::SHA512.digest(data)[0...32]
149
+ scalar = hash.unpack1('H*').to_i(16)
150
+
151
+ if scalar > 0 && scalar < GROUP.order
152
+ return scalar.to_s(16).rjust(64, '0')
153
+ end
154
+ loop_count += 1
155
+ raise "Too many loops" if loop_count > 100
156
+ end
157
+ end
158
+
159
+ def self.derive_root_public_key(private_key_hex)
160
+ key_bn = private_key_hex.to_i(16)
161
+ pub_key_point = GROUP.generator.multiply_by_scalar(key_bn)
162
+ ECDSA::Format::PointOctetString.encode(pub_key_point, compression: true)
163
+ end
164
+
165
+ def self.derive_public_key(private_key_hex)
166
+ derive_root_public_key(private_key_hex)
167
+ end
168
+ end
169
+ end