secp256k1rb 0.3.0 → 0.8.1

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6a26cd2beaa9525ea8f7a0db0e411dbb3d049ec976214f4651e787f02ed76f83
4
- data.tar.gz: 05c9fce673e0f97e48faa60335cb5de37a3be74a12c50f5cfc541621c11526f2
3
+ metadata.gz: d1626509b5565bd7eb99f4099c97beedf44bf2a080e983aefef55dd615bd4edb
4
+ data.tar.gz: 3b0df7520dde0973d3ee747ef1e40ca6ecb61777431d0e76ccb9a2a302322ac5
5
5
  SHA512:
6
- metadata.gz: 71dbb792ccefcf0a852ff5ff96173c2f7c784cff9313489782b03159dd0163860938435d66ec974cccf7fe3755b5bd1ded9bbdf20a77a9d4d41bc2a6b65d63f9
7
- data.tar.gz: b5e36b1dae73beb4c7e2420efb792c9185fa08f96acbbd2090b5858fc305b88bd9b8a42197900bf1dfea9d1ff9c4b754d491719a63754e817c1c1854969b3db9
6
+ metadata.gz: 3b9bc340ac3a1c81397a053362e7a55311ab182a2208ee7bf3c2e4483df7950485518aaef676aeb96dc16258d4f386455860e3667e10d88072c61b537acdbc3c
7
+ data.tar.gz: 68fc807c8b8a5610a90d92e74151f739631c28ffc6a4691c1d6ef7fdd7f074adbeee5305b4dce0680ad51cbbf0519fe1c278181cbb2ab150c312baccdb07eb18
data/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.8.1] - 2026-11-01
4
+
5
+ - Install a non-aborting illegal-argument callback on every secp256k1 context.
6
+ Previously any `ARG_CHECK` failure inside libsecp256k1 (e.g. `generate_pubkey` with an invalid
7
+ private key, `verify_ecdsa` with an unparsable public key, `aggregate_pubkey([])`,
8
+ `aggregate_musig_nonce([])`) called `abort()` and killed the Ruby process. These cases now
9
+ raise `Secp256k1::Error`/`ArgumentError` or return `false`.
10
+ - Fix C return values being treated as Ruby truthy: `0` (failure) was never detected in
11
+ `sign_ecdsa`, `verify_ecdsa`, `create_keypair`, `generate_pubkey` and `serialize_pubkey_internal`.
12
+ - Fix heap buffer overflow in `MuSig::Session#partial_sign` (key pair buffer was 86 bytes instead of 96).
13
+ - Fix `create_keypair` raising `NoMethodError` instead of `Secp256k1::Error` for an invalid private key.
14
+ - Fix `generate_musig_nonce` raising `NoMethodError` when `key_agg_ctx` is omitted.
15
+ - Fix `sign_schnorr` (`aux_rand`) and `sign_ecdsa` (`extra_entropy`) rejecting hex-encoded input.
16
+ - Fix `verify_schnorr_custom` always returning `false` for the empty message.
17
+ - Fix `parse_ec_pubkey?('')` raising `NoMethodError`.
18
+ - `valid_xonly_pubkey?` no longer rescues `Exception`.
19
+ - `verify_schnorr`/`verify_schnorr_custom` now return `false` instead of raising `ArgumentError`
20
+ when the public key is not a valid point on the curve, consistent with `verify_ecdsa`.
21
+ - Use `size_t`/`int` sized buffers for length and recovery id out-parameters.
22
+ - Raise a descriptive `LoadError` when `SECP256K1_LIB_PATH` is not set.
23
+
24
+ ## [0.8.0]
25
+
26
+ - Change versioning policy: the gem's major and minor version now match the
27
+ supported secp256k1 version. Patch releases are used for gem-side changes.
28
+ - Support secp256k1 v0.8.0.
29
+ - Add `Secp256k1::SilentPayments` module (BIP-352 Silent Payments):
30
+ `silentpayments_sender_create_outputs`, `silentpayments_create_label`,
31
+ `silentpayments_create_labeled_spend_pubkey`, `silentpayments_create_prevouts_summary` and
32
+ `silentpayments_scan_outputs`. Tested against the official BIP-352 test vectors.
33
+ The silentpayments bindings (and `secp256k1_context_set_sha256_compression`) are attached
34
+ optionally, so the gem remains loadable with older libsecp256k1 (e.g. v0.7.x) where these
35
+ features raise `Secp256k1::Error`. Availability can be checked with `silentpayments_available?`.
36
+ - Add FFI binding for `secp256k1_context_set_sha256_compression`.
37
+ - Remove FFI binding for `secp256k1_schnorrsig_sign` which was removed in secp256k1 v0.8.0.
38
+ Use `secp256k1_schnorrsig_sign32` instead.
39
+ - Fix `generate_pubkey` to return a wrong public key when a binary private key
40
+ happens to consist of hexadecimal characters (the key was converted twice).
41
+
3
42
  ## [0.3.0]
4
43
 
5
44
  - Support secp256k1 v0.7.1.
data/Gemfile CHANGED
@@ -8,3 +8,4 @@ gemspec
8
8
  gem "rake", "~> 13.0"
9
9
  gem "rspec", "~> 3.0"
10
10
  gem "csv", '~> 3.3'
11
+ gem "bech32", "~> 1.5"
data/README.md CHANGED
@@ -23,8 +23,11 @@ Or install it yourself as:
23
23
  To use this library, you need to specify the path of the secp256k1 shared library in environment variable
24
24
  `SECP256K1_LIB_PATH`, e.g: `$ export SECP256K1_LIB_PATH=/var/local/lib/libsecp256k1.so`.
25
25
 
26
- Note: This library also implements the recovery module, so you must have built the secp256k1 library with the
27
- `--enable-module-recovery` option.
26
+ Note: This library binds the `recovery`, `ecdh`, `extrakeys`, `schnorrsig`, `musig` and `ellswift` modules,
27
+ so the secp256k1 library must have been built with these modules enabled
28
+ (e.g. `--enable-module-recovery --enable-module-musig --enable-module-ellswift`; the others are enabled by default).
29
+ Loading fails with `FFI::NotFoundError` if one of them is missing.
30
+ The `silentpayments` module (`--enable-module-silentpayments`, experimental) is optional.
28
31
 
29
32
  By including the Secp256k1 module, you can use the features provided by the `libsepc256k1` library. For example:
30
33
 
@@ -46,9 +49,20 @@ In addition, the following modules are also included, so you can use them as the
46
49
  * [SchnorrSig](https://www.rubydoc.info/gems/secp256k1rb/Secp256k1/SchnorrSig)
47
50
  * [MuSig](https://www.rubydoc.info/gems/secp256k1rb/Secp256k1/MuSig)
48
51
  * [EllSwift](https://www.rubydoc.info/gems/secp256k1rb/Secp256k1/EllSwift)
52
+ * [SilentPayments](https://www.rubydoc.info/gems/secp256k1rb/Secp256k1/SilentPayments)
49
53
 
50
54
  ### Compatibility
51
55
 
56
+ Since v0.8.0, the major and minor version of this gem matches the supported
57
+ secp256k1 version (e.g. secp256k1rb v0.8.x supports secp256k1 v0.8.x).
58
+ Patch releases are used for gem-side changes.
59
+
60
+ The gem also loads with older libsecp256k1 versions; features that require a newer
61
+ library (e.g. the silentpayments module) raise `Secp256k1::Error` when used.
62
+ Use `silentpayments_available?` to check availability at runtime.
63
+
64
+ Older versions:
65
+
52
66
  secp256k1 version | secp256k1rb version
53
67
  :---:|:---:
54
68
  v0.4.0 | v0.1.x
data/lib/secp256k1/c.rb CHANGED
@@ -6,7 +6,11 @@ module Secp256k1
6
6
  module C
7
7
  extend FFI::Library
8
8
 
9
- ffi_lib(ENV['SECP256K1_LIB_PATH'])
9
+ lib_path = ENV['SECP256K1_LIB_PATH']
10
+ if lib_path.nil? || lib_path.empty?
11
+ raise LoadError, 'The environment variable SECP256K1_LIB_PATH must specify the path to the libsecp256k1 shared library.'
12
+ end
13
+ ffi_lib(lib_path)
10
14
 
11
15
  attach_function(:secp256k1_context_create, [:uint], :pointer)
12
16
  attach_function(:secp256k1_context_destroy, [:pointer], :void)
@@ -45,7 +49,6 @@ module Secp256k1
45
49
  attach_function(:secp256k1_ecdsa_signature_normalize, [:pointer, :pointer, :pointer], :int)
46
50
  attach_function(:secp256k1_ecdsa_verify, [:pointer, :pointer, :pointer, :pointer], :int)
47
51
  attach_function(:secp256k1_schnorrsig_sign32, [:pointer, :pointer, :pointer, :pointer, :pointer], :int)
48
- attach_function(:secp256k1_schnorrsig_sign, [:pointer, :pointer, :pointer, :pointer, :pointer], :int)
49
52
  attach_function(:secp256k1_schnorrsig_sign_custom, [:pointer, :pointer, :pointer, :size_t, :pointer, :pointer], :int)
50
53
  attach_function(:secp256k1_schnorrsig_verify, [:pointer, :pointer, :pointer, :size_t, :pointer], :int)
51
54
  attach_function(:secp256k1_keypair_create, [:pointer, :pointer, :pointer], :int)
@@ -94,6 +97,42 @@ module Secp256k1
94
97
  attach_function(:secp256k1_musig_partial_sig_verify, [:pointer, :pointer, :pointer, :pointer, :pointer, :pointer], :int)
95
98
  attach_function(:secp256k1_musig_partial_sig_agg, [:pointer, :pointer, :pointer, :pointer, :size_t], :int)
96
99
 
100
+ # The following functions only exist in libsecp256k1 v0.8.0 or later, so they are
101
+ # attached optionally to keep this gem loadable with older libraries.
102
+
103
+ # for SilentPayments module
104
+ SILENTPAYMENTS_AVAILABLE = begin
105
+ attach_function(:secp256k1_silentpayments_sender_create_outputs, [:pointer, :pointer, :pointer, :size_t, :pointer, :pointer, :size_t, :pointer, :size_t], :int)
106
+ attach_function(:secp256k1_silentpayments_recipient_label_parse, [:pointer, :pointer, :pointer], :int)
107
+ attach_function(:secp256k1_silentpayments_recipient_label_serialize, [:pointer, :pointer, :pointer], :int)
108
+ attach_function(:secp256k1_silentpayments_recipient_label_create, [:pointer, :pointer, :pointer, :pointer, :uint32], :int)
109
+ attach_function(:secp256k1_silentpayments_recipient_create_labeled_spend_pubkey, [:pointer, :pointer, :pointer, :pointer], :int)
110
+ attach_function(:secp256k1_silentpayments_recipient_prevouts_summary_create, [:pointer, :pointer, :pointer, :pointer, :size_t, :pointer, :size_t], :int)
111
+ attach_function(:secp256k1_silentpayments_recipient_scan_outputs, [:pointer, :pointer, :pointer, :pointer, :size_t, :pointer, :pointer, :pointer, :pointer, :pointer], :int)
112
+ true
113
+ rescue FFI::NotFoundError
114
+ false
115
+ end
116
+
117
+ SHA256_COMPRESSION_AVAILABLE = begin
118
+ attach_function(:secp256k1_context_set_sha256_compression, [:pointer, :pointer], :void)
119
+ true
120
+ rescue FFI::NotFoundError
121
+ false
122
+ end
123
+
124
+ # Whether the loaded libsecp256k1 supports the silentpayments module.
125
+ # @return [Boolean]
126
+ def self.silentpayments_available?
127
+ SILENTPAYMENTS_AVAILABLE
128
+ end
129
+
130
+ # Whether the loaded libsecp256k1 supports secp256k1_context_set_sha256_compression.
131
+ # @return [Boolean]
132
+ def self.sha256_compression_available?
133
+ SHA256_COMPRESSION_AVAILABLE
134
+ end
135
+
97
136
  # Pointer to secp256k1_ellswift_xdh_hash_function_bip324 constant.
98
137
  # @return [FFI::Pointer]
99
138
  def self.ellswift_xdh_hash_function_bip324
@@ -60,7 +60,7 @@ module Secp256k1
60
60
  # @param [String] their_ell_pubkey Their EllSwift public key.
61
61
  # @param [String] our_ell_pubkey Our EllSwift public key.
62
62
  # @param [String] private_key private key with hex format.
63
- # @param [Boolean] initiating Whether your initiator or not.
63
+ # @param [Boolean] initiating Whether we are the initiator of the connection (BIP-324).
64
64
  # @return [String] x coordinate with hex format.
65
65
  # @raise [Secp256k1::Error] If secret is invalid or hashfp return 0.
66
66
  def ellswift_ecdh_xonly(their_ell_pubkey, our_ell_pubkey, private_key, initiating)
@@ -16,7 +16,7 @@ module Secp256k1
16
16
  # @param [Secp256k1::MuSig::KeyAggCache] key_agg_cache Key aggregation cache.
17
17
  # @raise [ArgumentError] If invalid arguments specified.
18
18
  def initialize(key_agg_cache)
19
- raise ArgumentError, "key_agg_cache must be Secp256k1::KeyAggCache." unless key_agg_cache.is_a?(Secp256k1::KeyAggCache)
19
+ raise ArgumentError, "key_agg_cache must be Secp256k1::MuSig::KeyAggCache." unless key_agg_cache.is_a?(KeyAggCache)
20
20
  @cache = key_agg_cache
21
21
  end
22
22
 
@@ -49,11 +49,7 @@ module Secp256k1
49
49
  with_context do |context|
50
50
  partial_sig = FFI::MemoryPointer.new(:uchar, 36)
51
51
  sec_nonce_ptr = FFI::MemoryPointer.new(:uchar, 132).put_bytes(0, hex2bin(sec_nonce))
52
- private_key_ptr = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, hex2bin(private_key))
53
- key_pair = FFI::MemoryPointer.new(:uchar, 86)
54
- if secp256k1_keypair_create(context, key_pair, private_key_ptr) == 0
55
- raise Error, "secp256k1_keypair_create invalid private_key."
56
- end
52
+ key_pair = create_keypair_internal(context, hex2bin(private_key))
57
53
  if secp256k1_musig_partial_sign(
58
54
  context, partial_sig, sec_nonce_ptr, key_pair, key_agg_ctx.cache.pointer, session) == 0
59
55
  raise Error, "secp256k1_musig_partial_sign arguments invalid or sec_nonce has already been used for signing."
@@ -26,7 +26,7 @@ module Secp256k1
26
26
  #
27
27
  # # Nonce generation
28
28
  # session_id1 = generate_musig_session_id
29
- # secnonce1, pubnonce1 = target.generate_musig_nonce(
29
+ # secnonce1, pubnonce1 = generate_musig_nonce(
30
30
  # session_id1,
31
31
  # pk1,
32
32
  # sk: sk1,
@@ -35,7 +35,7 @@ module Secp256k1
35
35
  # )
36
36
  #
37
37
  # session_id2 = generate_musig_session_id
38
- # secnonce2, pubnonce2 = target.generate_musig_nonce(
38
+ # secnonce2, pubnonce2 = generate_musig_nonce(
39
39
  # session_id2,
40
40
  # pk2,
41
41
  # sk: sk2,
@@ -60,10 +60,11 @@ module Secp256k1
60
60
 
61
61
  # Aggregate public keys.
62
62
  # @param [Array] pubkeys An array of public keys.
63
- # @return [Secp2561k::MuSig::KeyAggContext]
63
+ # @return [Secp256k1::MuSig::KeyAggContext]
64
64
  # @raise [Secp256k1::Error]
65
65
  def aggregate_pubkey(pubkeys)
66
66
  raise ArgumentError, "pubkeys must be an array." unless pubkeys.is_a?(Array)
67
+ raise ArgumentError, "pubkeys must not be empty." if pubkeys.empty?
67
68
  with_context do |context|
68
69
  pubkeys_ptrs = pubkeys.map do |pubkey|
69
70
  pubkey = hex2bin(pubkey)
@@ -124,7 +125,7 @@ module Secp256k1
124
125
  session_secrand32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, hex2bin(session_id))
125
126
 
126
127
  raise Error, "arguments is invalid." unless secp256k1_musig_nonce_gen(
127
- context, secnonce, pubnonce, session_secrand32, seckey, pubkey, msg32, key_agg_ctx.pointer, extra_input32) == 1
128
+ context, secnonce, pubnonce, session_secrand32, seckey, pubkey, msg32, key_agg_ctx&.pointer, extra_input32) == 1
128
129
 
129
130
  pub66 = FFI::MemoryPointer.new(:uchar, 66)
130
131
  secp256k1_musig_pubnonce_serialize(context, pub66, pubnonce)
@@ -153,8 +154,7 @@ module Secp256k1
153
154
  end
154
155
 
155
156
  with_context do |context|
156
- keypair = [create_keypair(private_key)].pack('H*')
157
- keypair_ptr = FFI::MemoryPointer.new(:uchar, 96).put_bytes(0, keypair)
157
+ keypair_ptr = create_keypair_internal(context, hex2bin(private_key))
158
158
  pubnonce = FFI::MemoryPointer.new(:uchar, 132)
159
159
  secnonce = FFI::MemoryPointer.new(:uchar, 132)
160
160
  msg32 = msg ? FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, hex2bin(msg)) : nil
@@ -177,6 +177,7 @@ module Secp256k1
177
177
  # @raise [ArgumentError] If invalid arguments specified.
178
178
  def aggregate_musig_nonce(pub_nonces)
179
179
  raise ArgumentError, "pub_nonces must be Array." unless pub_nonces.is_a?(Array)
180
+ raise ArgumentError, "pub_nonces must not be empty." if pub_nonces.empty?
180
181
 
181
182
  with_context do |context|
182
183
  nonce_ptrs = pub_nonces.map do |pub_nonce|
@@ -8,7 +8,7 @@ module Secp256k1
8
8
  # sig, rec = sign_recoverable(msg, sk)
9
9
  # full_sig = [rec + 0x1b + 4].pack('C') + [sig].pack('H*')
10
10
  # compressed = true
11
- # recover_pubkey = target.recover(msg, full_sig, compressed)
11
+ # recover_pubkey = recover(msg, full_sig, compressed)
12
12
  #
13
13
  module Recover
14
14
  # Sign data with compact format.
@@ -24,18 +24,18 @@ module Secp256k1
24
24
  data = hex2bin(data)
25
25
  with_context do |context|
26
26
  sig = FFI::MemoryPointer.new(:uchar, 65)
27
- hash =FFI::MemoryPointer.new(:uchar, data.bytesize).put_bytes(0, data)
27
+ hash = FFI::MemoryPointer.new(:uchar, data.bytesize).put_bytes(0, data)
28
28
  sec_key = FFI::MemoryPointer.new(:uchar, private_key.bytesize).put_bytes(0, private_key)
29
29
  result = secp256k1_ecdsa_sign_recoverable(context, sig, hash, sec_key, nil, nil)
30
30
  raise Error, 'secp256k1_ecdsa_sign_recoverable failed.' if result == 0
31
31
 
32
32
  output = FFI::MemoryPointer.new(:uchar, 64)
33
- rec = FFI::MemoryPointer.new(:uint64)
33
+ rec = FFI::MemoryPointer.new(:int)
34
34
  result = secp256k1_ecdsa_recoverable_signature_serialize_compact(context, output, rec, sig)
35
35
  raise Error, 'secp256k1_ecdsa_recoverable_signature_serialize_compact failed.' unless result == 1
36
36
 
37
37
  sig = output.read_string(64).unpack1('H*')
38
- [sig, rec.read(:int)]
38
+ [sig, rec.read_int]
39
39
  end
40
40
  end
41
41
 
@@ -52,7 +52,6 @@ module Secp256k1
52
52
  signature = hex2bin(signature)
53
53
  data = hex2bin(data)
54
54
  rec = (signature[0].ord - 0x1b) & 3
55
- raise ArgumentError, "rec must be between 0 and 3." if rec < 0 || rec > 3
56
55
 
57
56
  with_context do |context|
58
57
  sig = FFI::MemoryPointer.new(:uchar, 65)
@@ -65,7 +64,7 @@ module Secp256k1
65
64
  result = secp256k1_ecdsa_recover(context, pubkey, sig, msg)
66
65
  raise Error, 'secp256k1_ecdsa_recover failed.' unless result == 1
67
66
 
68
- serialize_pubkey_internal(context, pubkey.read_string(64), compressed)
67
+ serialize_pubkey_internal(context, pubkey, compressed)
69
68
  end
70
69
  end
71
70
 
@@ -78,17 +77,13 @@ module Secp256k1
78
77
  validate_string!("signature", signature, 65)
79
78
  signature = hex2bin(signature)
80
79
  rec = (signature[0].ord - 0x1b) & 3
81
- raise ArgumentError, "rec must be between 0 and 3." if rec < 0 || rec > 3
82
80
  with_context do |context|
83
81
  recoverable = FFI::MemoryPointer.new(:uchar, 65)
84
82
  input = FFI::MemoryPointer.new(:uchar, 64).put_bytes(0, signature[1..-1])
85
83
  raise Error, 'secp256k1_ecdsa_recoverable_signature_parse_compact failed.' unless secp256k1_ecdsa_recoverable_signature_parse_compact(context, recoverable, input, rec) == 1
86
84
  internal_signature = FFI::MemoryPointer.new(:uchar, 64)
87
85
  raise Error, 'secp256k1_ecdsa_recoverable_signature_convert failed.' unless secp256k1_ecdsa_recoverable_signature_convert(context, internal_signature, recoverable) == 1
88
- output = FFI::MemoryPointer.new(:uchar, 72)
89
- output_len = FFI::MemoryPointer.new(:uint64).put_uint64(0, 72)
90
- raise Error, 'secp256k1_ecdsa_signature_serialize_der failed.' unless secp256k1_ecdsa_signature_serialize_der(context, output, output_len, internal_signature) == 1
91
- output.read_string(output_len.read_uint64)
86
+ serialize_ecdsa_signature_der(context, internal_signature)
92
87
  end
93
88
  end
94
89
  end
@@ -14,20 +14,20 @@ module Secp256k1
14
14
  # Sign to data using schnorr.
15
15
  # @param [String] data The 32-byte message hash being signed with binary format.
16
16
  # @param [String] private_key a private key with hex format using sign.
17
- # @param [String] aux_rand The 32-byte extra entropy.
18
- # @return [String] signature data with binary format. If unsupported algorithm specified, return nil.
17
+ # @param [String] aux_rand (Optional)The 32-byte extra entropy with hex or binary format.
18
+ # @return [String] signature data with binary format(64 bytes).
19
+ # @raise [Secp256k1::Error] If signing failed.
19
20
  # @raise [ArgumentError] If invalid arguments specified.
20
21
  def sign_schnorr(data, private_key, aux_rand = nil)
21
22
  validate_string!("data", data, 32)
22
23
  validate_string!("private_key", private_key, 32)
23
24
  validate_string!("aux_rand", aux_rand, 32) if aux_rand
24
- raise ArgumentError, "aux_rand must be String." if !aux_rand.nil? && !aux_rand.is_a?(String)
25
25
  private_key = hex2bin(private_key)
26
26
  data = hex2bin(data)
27
+ aux_rand = hex2bin(aux_rand) if aux_rand
27
28
 
28
29
  with_context do |context|
29
- keypair = [create_keypair(private_key)].pack('H*')
30
- keypair = FFI::MemoryPointer.new(:uchar, 96).put_bytes(0, keypair)
30
+ keypair = create_keypair_internal(context, private_key)
31
31
  signature = FFI::MemoryPointer.new(:uchar, 64)
32
32
  msg32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, data)
33
33
  aux_rand = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, aux_rand) if aux_rand
@@ -55,8 +55,7 @@ module Secp256k1
55
55
  aux_rand = hex2bin(aux_rand) if aux_rand
56
56
 
57
57
  with_context do |context|
58
- keypair = [create_keypair(private_key)].pack('H*')
59
- keypair = FFI::MemoryPointer.new(:uchar, 96).put_bytes(0, keypair)
58
+ keypair = create_keypair_internal(context, private_key)
60
59
  signature = FFI::MemoryPointer.new(:uchar, 64)
61
60
  msg = FFI::MemoryPointer.new(:uchar, [data.bytesize, 1].max).put_bytes(0, data)
62
61
 
@@ -77,7 +76,7 @@ module Secp256k1
77
76
  # @param [String] data The 32-byte message hash assumed to be signed.
78
77
  # @param [String] signature signature data with binary format
79
78
  # @param [String] pubkey a public key with hex format using verify.
80
- # @return [Boolean] verification result.
79
+ # @return [Boolean] verification result. Returns false if +pubkey+ is not a valid x-only public key.
81
80
  # @raise [ArgumentError] If invalid arguments specified.
82
81
  def verify_schnorr(data, signature, pubkey)
83
82
  validate_string!("data", data, 32)
@@ -88,7 +87,7 @@ module Secp256k1
88
87
  # @param [String] data The message assumed to be signed. The length is arbitrary.
89
88
  # @param [String] signature signature data with binary format(64 bytes).
90
89
  # @param [String] pubkey an x-only public key with hex format(32 bytes) using verify.
91
- # @return [Boolean] verification result.
90
+ # @return [Boolean] verification result. Returns false if +pubkey+ is not a valid x-only public key.
92
91
  # @raise [ArgumentError] If invalid arguments specified.
93
92
  def verify_schnorr_custom(data, signature, pubkey)
94
93
  raise ArgumentError, "data must be String." unless data.is_a?(String)
@@ -104,13 +103,13 @@ module Secp256k1
104
103
  pubkey = hex2bin(pubkey)
105
104
  signature = hex2bin(signature)
106
105
  with_context do |context|
107
- return false if data.bytesize == 0
108
- pubkey = [full_pubkey_from_xonly_pubkey(pubkey)].pack('H*')
109
- xonly_pubkey = FFI::MemoryPointer.new(:uchar, pubkey.bytesize).put_bytes(0, pubkey)
110
- signature = FFI::MemoryPointer.new(:uchar, signature.bytesize).put_bytes(0, signature)
106
+ xonly_input = FFI::MemoryPointer.new(:uchar, X_ONLY_PUBKEY_SIZE).put_bytes(0, pubkey)
107
+ xonly_pubkey = FFI::MemoryPointer.new(:uchar, 64)
108
+ # A public key that is not a valid point on the curve cannot have signed anything.
109
+ return false unless secp256k1_xonly_pubkey_parse(context, xonly_pubkey, xonly_input) == 1
110
+ sig_ptr = FFI::MemoryPointer.new(:uchar, 64).put_bytes(0, signature)
111
111
  msg = FFI::MemoryPointer.new(:uchar, [data.bytesize, 1].max).put_bytes(0, data)
112
- result = secp256k1_schnorrsig_verify(context, signature, msg, data.bytesize, xonly_pubkey)
113
- result == 1
112
+ secp256k1_schnorrsig_verify(context, sig_ptr, msg, data.bytesize, xonly_pubkey) == 1
114
113
  end
115
114
  end
116
115
  end
@@ -0,0 +1,319 @@
1
+ module Secp256k1
2
+
3
+ # Silent Payments module (BIP-352).
4
+ # This module provides elliptic-curve operations required for sending and
5
+ # receiving Silent Payments. Note that this is not a full implementation of
6
+ # BIP-352; higher-level concepts like addresses, output script types or
7
+ # transactions must be handled by the caller.
8
+ # @example
9
+ # include Secp256k1
10
+ #
11
+ # # Sender side:
12
+ # outputs = silentpayments_sender_create_outputs(
13
+ # [[scan_pubkey, spend_pubkey]], outpoint_smallest, plain_seckeys: [seckey])
14
+ #
15
+ # # Recipient side:
16
+ # prevouts_summary = silentpayments_create_prevouts_summary(
17
+ # outpoint_smallest, plain_pubkeys: [pubkey])
18
+ # found = silentpayments_scan_outputs(
19
+ # outputs, scan_key, prevouts_summary, spend_pubkey)
20
+ module SilentPayments
21
+
22
+ # Size of a serialized Silent Payments label.
23
+ SP_LABEL_SIZE = 33
24
+ # Size of an internal Silent Payments label object.
25
+ SP_LABEL_INTERNAL_SIZE = 68
26
+ # Size of a Silent Payments prevouts summary object.
27
+ SP_PREVOUTS_SUMMARY_SIZE = 101
28
+ # Maximum number of recipients sharing the same scan public key (BIP-352).
29
+ SP_RECIPIENT_GROUP_LIMIT = 2323
30
+
31
+ # Struct mirroring secp256k1_silentpayments_recipient.
32
+ class Recipient < FFI::Struct
33
+ layout :scan_pubkey, [:uchar, 64],
34
+ :spend_pubkey, [:uchar, 64],
35
+ :index, :size_t
36
+ end
37
+
38
+ # Struct mirroring secp256k1_silentpayments_found_output.
39
+ class FoundOutput < FFI::Struct
40
+ layout :output, [:uchar, 64],
41
+ :tweak, [:uchar, 32],
42
+ :found_with_label, :int,
43
+ :label, [:uchar, SP_LABEL_INTERNAL_SIZE]
44
+ end
45
+
46
+ # Whether the loaded libsecp256k1 supports the silentpayments module.
47
+ # The module is available in libsecp256k1 v0.8.0 or later.
48
+ # @return [Boolean]
49
+ def silentpayments_available?
50
+ C.silentpayments_available?
51
+ end
52
+
53
+ # Create Silent Payments outputs for recipient(s) (sender side).
54
+ # @param [Array] recipients An array of recipient's key pair. Each element is an array of
55
+ # scan public key and (labeled) spend public key with hex format(33 bytes each).
56
+ # @param [String] outpoint_smallest The smallest outpoint lexicographically from the transaction inputs(36 bytes).
57
+ # @param [Array] plain_seckeys (Optional) An array of private keys of non-taproot inputs with hex format(32 bytes each).
58
+ # @param [Array] taproot_seckeys (Optional) An array of private keys of taproot inputs with hex format(32 bytes each).
59
+ # @return [Array] An array of x-only public keys(hex format) for the taproot outputs, ordered same as +recipients+.
60
+ # @raise [Secp256k1::Error] If creation failed.
61
+ # @raise [ArgumentError] If invalid arguments specified.
62
+ def silentpayments_sender_create_outputs(recipients, outpoint_smallest, plain_seckeys: [], taproot_seckeys: [])
63
+ check_silentpayments_support!
64
+ raise ArgumentError, "recipients must be an Array." unless recipients.is_a?(Array)
65
+ raise ArgumentError, "recipients must not be empty." if recipients.empty?
66
+ plain_seckeys ||= []
67
+ taproot_seckeys ||= []
68
+ raise ArgumentError, "plain_seckeys must be an Array." unless plain_seckeys.is_a?(Array)
69
+ raise ArgumentError, "taproot_seckeys must be an Array." unless taproot_seckeys.is_a?(Array)
70
+ if plain_seckeys.empty? && taproot_seckeys.empty?
71
+ raise ArgumentError, "At least one private key(plain_seckeys or taproot_seckeys) is required."
72
+ end
73
+ validate_string!("outpoint_smallest", outpoint_smallest, 36)
74
+
75
+ with_context do |context|
76
+ recipient_structs = recipients.each_with_index.map do |recipient, i|
77
+ scan_pubkey, spend_pubkey = recipient
78
+ validate_string!("scan_pubkey", scan_pubkey, 33)
79
+ validate_string!("spend_pubkey", spend_pubkey, 33)
80
+ st = Recipient.new
81
+ st.pointer.put_bytes(0, parse_pubkey_internal(context, hex2bin(scan_pubkey)).read_string(64))
82
+ st.pointer.put_bytes(64, parse_pubkey_internal(context, hex2bin(spend_pubkey)).read_string(64))
83
+ st[:index] = i
84
+ st
85
+ end
86
+ recipients_ptr = FFI::MemoryPointer.new(:pointer, recipient_structs.length)
87
+ recipients_ptr.write_array_of_pointer(recipient_structs.map(&:pointer))
88
+
89
+ generated_outputs = Array.new(recipients.length) { FFI::MemoryPointer.new(:uchar, 64) }
90
+ generated_outputs_ptr = FFI::MemoryPointer.new(:pointer, generated_outputs.length)
91
+ generated_outputs_ptr.write_array_of_pointer(generated_outputs)
92
+
93
+ outpoint_ptr = FFI::MemoryPointer.new(:uchar, 36).put_bytes(0, hex2bin(outpoint_smallest))
94
+
95
+ keypairs = taproot_seckeys.map do |sk|
96
+ validate_string!("taproot_seckey", sk, 32)
97
+ seckey = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, hex2bin(sk))
98
+ keypair = FFI::MemoryPointer.new(:uchar, 96)
99
+ raise Error, "taproot_seckey is invalid." unless secp256k1_keypair_create(context, keypair, seckey) == 1
100
+ keypair
101
+ end
102
+ keypairs_ptr = if keypairs.empty?
103
+ nil
104
+ else
105
+ FFI::MemoryPointer.new(:pointer, keypairs.length).write_array_of_pointer(keypairs)
106
+ end
107
+
108
+ seckeys = plain_seckeys.map do |sk|
109
+ validate_string!("plain_seckey", sk, 32)
110
+ FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, hex2bin(sk))
111
+ end
112
+ seckeys_ptr = if seckeys.empty?
113
+ nil
114
+ else
115
+ FFI::MemoryPointer.new(:pointer, seckeys.length).write_array_of_pointer(seckeys)
116
+ end
117
+
118
+ result = secp256k1_silentpayments_sender_create_outputs(
119
+ context, generated_outputs_ptr, recipients_ptr, recipients.length, outpoint_ptr,
120
+ keypairs_ptr, keypairs.length, seckeys_ptr, seckeys.length)
121
+ raise Error, "secp256k1_silentpayments_sender_create_outputs failed." unless result == 1
122
+
123
+ generated_outputs.map { |output| serialize_xonly_pubkey_internal(context, output) }
124
+ end
125
+ end
126
+
127
+ # Create Silent Payments label tweak and label(recipient side).
128
+ # @param [String] scan_key The recipient's scan key with hex format(32 bytes).
129
+ # @param [Integer] m The integer for the m-th label (0 is used for change outputs).
130
+ # @return [Array(String)] An array of serialized label(33 bytes) and label tweak(32 bytes) with hex format.
131
+ # @raise [Secp256k1::Error] If creation failed.
132
+ # @raise [ArgumentError] If invalid arguments specified.
133
+ def silentpayments_create_label(scan_key, m)
134
+ check_silentpayments_support!
135
+ validate_string!("scan_key", scan_key, 32)
136
+ raise ArgumentError, "m must be Integer." unless m.is_a?(Integer)
137
+ raise ArgumentError, "m must be between 0 and 2**32-1." if m < 0 || m > 0xffffffff
138
+
139
+ with_context do |context|
140
+ label = FFI::MemoryPointer.new(:uchar, SP_LABEL_INTERNAL_SIZE)
141
+ label_tweak = FFI::MemoryPointer.new(:uchar, 32)
142
+ scan_key_ptr = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, hex2bin(scan_key))
143
+ result = secp256k1_silentpayments_recipient_label_create(context, label, label_tweak, scan_key_ptr, m)
144
+ raise Error, "secp256k1_silentpayments_recipient_label_create failed." unless result == 1
145
+ out33 = FFI::MemoryPointer.new(:uchar, SP_LABEL_SIZE)
146
+ secp256k1_silentpayments_recipient_label_serialize(context, out33, label)
147
+ [out33.read_string(SP_LABEL_SIZE).unpack1('H*'), label_tweak.read_string(32).unpack1('H*')]
148
+ end
149
+ end
150
+
151
+ # Create Silent Payments labeled spend public key(recipient side).
152
+ # @param [String] spend_pubkey The recipient's unlabeled spend public key with hex format(33 bytes).
153
+ # @param [String] label The serialized label with hex format(33 bytes).
154
+ # @return [String] The labeled spend public key with hex format(33 bytes).
155
+ # @raise [Secp256k1::Error] If creation failed.
156
+ # @raise [ArgumentError] If invalid arguments specified.
157
+ def silentpayments_create_labeled_spend_pubkey(spend_pubkey, label)
158
+ check_silentpayments_support!
159
+ validate_string!("spend_pubkey", spend_pubkey, 33)
160
+ validate_string!("label", label, SP_LABEL_SIZE)
161
+
162
+ with_context do |context|
163
+ spend_pubkey_ptr = parse_pubkey_internal(context, hex2bin(spend_pubkey))
164
+ label_ptr = parse_label_internal(context, hex2bin(label))
165
+ labeled = FFI::MemoryPointer.new(:uchar, 64)
166
+ result = secp256k1_silentpayments_recipient_create_labeled_spend_pubkey(context, labeled, spend_pubkey_ptr, label_ptr)
167
+ raise Error, "secp256k1_silentpayments_recipient_create_labeled_spend_pubkey failed." unless result == 1
168
+ serialize_pubkey_internal(context, labeled, true)
169
+ end
170
+ end
171
+
172
+ # Compute Silent Payments prevouts summary from prevout public keys and transaction inputs(recipient side).
173
+ # @param [String] outpoint_smallest The smallest outpoint lexicographically from the transaction inputs(36 bytes).
174
+ # @param [Array] plain_pubkeys (Optional) An array of public keys of non-taproot inputs with hex format(33 bytes each).
175
+ # @param [Array] xonly_pubkeys (Optional) An array of x-only public keys of taproot inputs with hex format(32 bytes each).
176
+ # @return [String] The prevouts summary data with hex format(101 bytes).
177
+ # Note that this is an opaque representation which is not guaranteed to be
178
+ # portable between different platforms or library versions.
179
+ # @raise [Secp256k1::Error] If the transaction is not a Silent Payments transaction.
180
+ # @raise [ArgumentError] If invalid arguments specified.
181
+ def silentpayments_create_prevouts_summary(outpoint_smallest, plain_pubkeys: [], xonly_pubkeys: [])
182
+ check_silentpayments_support!
183
+ plain_pubkeys ||= []
184
+ xonly_pubkeys ||= []
185
+ raise ArgumentError, "plain_pubkeys must be an Array." unless plain_pubkeys.is_a?(Array)
186
+ raise ArgumentError, "xonly_pubkeys must be an Array." unless xonly_pubkeys.is_a?(Array)
187
+ if plain_pubkeys.empty? && xonly_pubkeys.empty?
188
+ raise ArgumentError, "At least one public key(plain_pubkeys or xonly_pubkeys) is required."
189
+ end
190
+ validate_string!("outpoint_smallest", outpoint_smallest, 36)
191
+
192
+ with_context do |context|
193
+ xonly_ptrs = xonly_pubkeys.map do |pubkey|
194
+ validate_string!("xonly_pubkey", pubkey, 32)
195
+ parse_xonly_pubkey_internal(context, hex2bin(pubkey))
196
+ end
197
+ plain_ptrs = plain_pubkeys.map do |pubkey|
198
+ validate_string!("plain_pubkey", pubkey, 33)
199
+ parse_pubkey_internal(context, hex2bin(pubkey))
200
+ end
201
+ xonly_arr = if xonly_ptrs.empty?
202
+ nil
203
+ else
204
+ FFI::MemoryPointer.new(:pointer, xonly_ptrs.length).write_array_of_pointer(xonly_ptrs)
205
+ end
206
+ plain_arr = if plain_ptrs.empty?
207
+ nil
208
+ else
209
+ FFI::MemoryPointer.new(:pointer, plain_ptrs.length).write_array_of_pointer(plain_ptrs)
210
+ end
211
+ outpoint_ptr = FFI::MemoryPointer.new(:uchar, 36).put_bytes(0, hex2bin(outpoint_smallest))
212
+ prevouts_summary = FFI::MemoryPointer.new(:uchar, SP_PREVOUTS_SUMMARY_SIZE)
213
+ result = secp256k1_silentpayments_recipient_prevouts_summary_create(
214
+ context, prevouts_summary, outpoint_ptr, xonly_arr, xonly_ptrs.length, plain_arr, plain_ptrs.length)
215
+ raise Error, "secp256k1_silentpayments_recipient_prevouts_summary_create failed." unless result == 1
216
+ prevouts_summary.read_string(SP_PREVOUTS_SUMMARY_SIZE).unpack1('H*')
217
+ end
218
+ end
219
+
220
+ # Scan for Silent Payments transaction outputs(recipient side).
221
+ # @param [Array] tx_outputs An array of the transaction's x-only public key outputs with hex format(32 bytes each),
222
+ # in their original transaction (vout) order.
223
+ # @param [String] scan_key The recipient's scan key with hex format(32 bytes).
224
+ # @param [String] prevouts_summary The prevouts summary data created by #silentpayments_create_prevouts_summary
225
+ # with hex format(101 bytes).
226
+ # @param [String] spend_pubkey The recipient's unlabeled spend public key with hex format(33 bytes).
227
+ # @param [Hash] labels (Optional) The recipient's label cache. A hash whose key is a serialized label(33 bytes)
228
+ # and whose value is the corresponding label tweak(32 bytes), both with hex format.
229
+ # Can be created with #silentpayments_create_label.
230
+ # @return [Array] An array of found outputs. Each element is a hash with the following keys:
231
+ # - :output x-only public key of the found output with hex format(32 bytes).
232
+ # - :tweak The 32-byte tweak needed to spend the output with hex format.
233
+ # - :label The serialized label(33 bytes with hex format) if the output was sent to a labeled address, otherwise nil.
234
+ # @raise [Secp256k1::Error] If the transaction is not a Silent Payments transaction or arguments are invalid.
235
+ # @raise [ArgumentError] If invalid arguments specified.
236
+ def silentpayments_scan_outputs(tx_outputs, scan_key, prevouts_summary, spend_pubkey, labels: nil)
237
+ check_silentpayments_support!
238
+ raise ArgumentError, "tx_outputs must be an Array." unless tx_outputs.is_a?(Array)
239
+ raise ArgumentError, "tx_outputs must not be empty." if tx_outputs.empty?
240
+ validate_string!("scan_key", scan_key, 32)
241
+ validate_string!("prevouts_summary", prevouts_summary, SP_PREVOUTS_SUMMARY_SIZE)
242
+ validate_string!("spend_pubkey", spend_pubkey, 33)
243
+ raise ArgumentError, "labels must be a Hash." if labels && !labels.is_a?(Hash)
244
+
245
+ with_context do |context|
246
+ output_ptrs = tx_outputs.map do |output|
247
+ validate_string!("tx_output", output, 32)
248
+ parse_xonly_pubkey_internal(context, hex2bin(output))
249
+ end
250
+ tx_outputs_ptr = FFI::MemoryPointer.new(:pointer, output_ptrs.length).write_array_of_pointer(output_ptrs)
251
+
252
+ found_outputs = Array.new(tx_outputs.length) { FoundOutput.new }
253
+ found_outputs_ptr = FFI::MemoryPointer.new(:pointer, found_outputs.length)
254
+ found_outputs_ptr.write_array_of_pointer(found_outputs.map(&:pointer))
255
+ n_found = FFI::MemoryPointer.new(:uint32)
256
+
257
+ scan_key_ptr = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, hex2bin(scan_key))
258
+ prevouts_summary_ptr = FFI::MemoryPointer.new(:uchar, SP_PREVOUTS_SUMMARY_SIZE).
259
+ put_bytes(0, hex2bin(prevouts_summary))
260
+ spend_pubkey_ptr = parse_pubkey_internal(context, hex2bin(spend_pubkey))
261
+
262
+ label_lookup = nil
263
+ if labels
264
+ # Keep tweak pointers referenced in this hash so they remain valid while scanning.
265
+ tweak_cache = {}
266
+ labels.each do |label, tweak|
267
+ validate_string!("label", label, SP_LABEL_SIZE)
268
+ validate_string!("label_tweak", tweak, 32)
269
+ tweak_cache[hex2bin(label)] = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, hex2bin(tweak))
270
+ end
271
+ label_lookup = FFI::Function.new(:pointer, [:pointer, :pointer]) do |label33, _|
272
+ tweak_cache[label33.read_string(SP_LABEL_SIZE)] || FFI::Pointer::NULL
273
+ end
274
+ end
275
+
276
+ result = secp256k1_silentpayments_recipient_scan_outputs(
277
+ context, found_outputs_ptr, n_found, tx_outputs_ptr, tx_outputs.length,
278
+ scan_key_ptr, prevouts_summary_ptr, spend_pubkey_ptr, label_lookup, nil)
279
+ raise Error, "secp256k1_silentpayments_recipient_scan_outputs failed." unless result == 1
280
+
281
+ Array.new(n_found.read_uint32) do |i|
282
+ found = found_outputs[i]
283
+ label = if found[:found_with_label] != 0
284
+ out33 = FFI::MemoryPointer.new(:uchar, SP_LABEL_SIZE)
285
+ secp256k1_silentpayments_recipient_label_serialize(
286
+ context, out33, found.pointer + FoundOutput.offset_of(:label))
287
+ out33.read_string(SP_LABEL_SIZE).unpack1('H*')
288
+ end
289
+ {
290
+ output: serialize_xonly_pubkey_internal(context, found.pointer),
291
+ tweak: found.pointer.get_bytes(FoundOutput.offset_of(:tweak), 32).unpack1('H*'),
292
+ label: label
293
+ }
294
+ end
295
+ end
296
+ end
297
+
298
+ private
299
+
300
+ # @raise [Secp256k1::Error] If the loaded libsecp256k1 does not support the silentpayments module.
301
+ def check_silentpayments_support!
302
+ unless C.silentpayments_available?
303
+ raise Error, "The loaded libsecp256k1 does not support the silentpayments module. libsecp256k1 v0.8.0 or later is required."
304
+ end
305
+ end
306
+
307
+ # Parse a serialized label into an internal label pointer.
308
+ # @param [FFI::Pointer] context secp256k1 context.
309
+ # @param [String] label serialized label with binary format(33 bytes).
310
+ # @return [FFI::Pointer] internal label pointer(68 bytes).
311
+ # @raise [Secp256k1::Error] If the label is invalid.
312
+ def parse_label_internal(context, label)
313
+ label_ptr = FFI::MemoryPointer.new(:uchar, SP_LABEL_SIZE).put_bytes(0, label)
314
+ internal = FFI::MemoryPointer.new(:uchar, SP_LABEL_INTERNAL_SIZE)
315
+ raise Error, 'An invalid label was specified.' unless secp256k1_silentpayments_recipient_label_parse(context, internal, label_ptr) == 1
316
+ internal
317
+ end
318
+ end
319
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Secp256k1
4
- VERSION = "0.3.0"
4
+ VERSION = "0.8.1"
5
5
  end
data/lib/secp256k1.rb CHANGED
@@ -9,6 +9,7 @@ require_relative 'secp256k1/recovery'
9
9
  require_relative 'secp256k1/ellswift'
10
10
  require_relative 'secp256k1/schnorrsig'
11
11
  require_relative 'secp256k1/musig'
12
+ require_relative 'secp256k1/silentpayments'
12
13
 
13
14
  # Binding for secp256k1 (https://github.com/bitcoin-core/secp256k1/)
14
15
  # @example
@@ -36,6 +37,7 @@ module Secp256k1
36
37
  include SchnorrSig
37
38
  include EllSwift
38
39
  include MuSig
40
+ include SilentPayments
39
41
 
40
42
  FLAGS_TYPE_MASK = ((1 << 8) - 1)
41
43
  FLAGS_TYPE_CONTEXT = (1 << 0)
@@ -56,13 +58,21 @@ module Secp256k1
56
58
  X_ONLY_PUBKEY_SIZE = 32
57
59
  ELL_SWIFT_KEY_SIZE = 64
58
60
 
61
+ # Illegal-argument callback installed on every context created by {#with_context}.
62
+ # libsecp256k1's default callback calls abort(), which kills the whole Ruby process whenever
63
+ # an ARG_CHECK fails inside the library. With this no-op callback installed the C function
64
+ # simply returns 0 and the Ruby wrapper raises a proper exception instead.
65
+ ILLEGAL_CALLBACK = FFI::Function.new(:void, [:string, :pointer]) { |_message, _data| }
66
+
59
67
  # Creates a secp256k1 context object, performs the operations passed in the block,
60
68
  # and then ensures that the secp256k1 context object is destroyed at the end.
61
69
  # @param [Integer] flags The flag to use when performing the operation.
62
70
  # @raise [Secp256k1::Error] If secp256k1_context_randomize failed.
63
71
  def with_context(flags: (CONTEXT_VERIFY | CONTEXT_SIGN))
72
+ context = nil
64
73
  begin
65
74
  context = secp256k1_context_create(flags)
75
+ secp256k1_context_set_illegal_callback(context, ILLEGAL_CALLBACK, nil)
66
76
  ret, tries, max = 0, 0, 20
67
77
  while ret != 1
68
78
  raise Error, 'secp256k1_context_randomize failed.' if tries >= max
@@ -88,8 +98,8 @@ module Secp256k1
88
98
  private_key = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, SecureRandom.random_bytes(32))
89
99
  ret = secp256k1_ec_seckey_verify(context, private_key)
90
100
  end
91
- private_key = private_key.read_string(32).unpack1('H*')
92
- [private_key , generate_pubkey_in_context(context, private_key, compressed: compressed) ]
101
+ private_key = private_key.read_string(32)
102
+ [private_key.unpack1('H*'), generate_pubkey_in_context(context, private_key, compressed: compressed)]
93
103
  end
94
104
  end
95
105
 
@@ -114,6 +124,7 @@ module Secp256k1
114
124
  def parse_ec_pubkey?(pubkey, allow_hybrid = false)
115
125
  raise ArgumentError, "pubkey must be String." unless pubkey.is_a?(String)
116
126
  pubkey = hex2bin(pubkey)
127
+ return false if pubkey.empty?
117
128
  return false if !allow_hybrid && ![0x02, 0x03, 0x04].include?(pubkey[0].ord)
118
129
  with_context do |context|
119
130
  pubkey_size = pubkey.bytesize
@@ -133,11 +144,7 @@ module Secp256k1
133
144
  validate_string!("private_key", private_key, 32)
134
145
  private_key = hex2bin(private_key)
135
146
  with_context do |context|
136
- secret = FFI::MemoryPointer.new(:uchar, private_key.bytesize).put_bytes(0, private_key)
137
- raise Error, 'private_key is invalid.' unless secp256k1_ec_seckey_verify(context, secret)
138
- keypair = FFI::MemoryPointer.new(:uchar, 96)
139
- raise Error 'private_key is invalid.' unless secp256k1_keypair_create(context, keypair, secret) == 1
140
- keypair.read_string(96).unpack1('H*')
147
+ create_keypair_internal(context, private_key).read_string(96).unpack1('H*')
141
148
  end
142
149
  end
143
150
 
@@ -148,7 +155,7 @@ module Secp256k1
148
155
  return false unless pubkey.is_a?(String)
149
156
  begin
150
157
  full_pubkey_from_xonly_pubkey(hex2bin(pubkey))
151
- rescue Exception
158
+ rescue ArgumentError, Error
152
159
  return false
153
160
  end
154
161
  true
@@ -157,8 +164,9 @@ module Secp256k1
157
164
  # Sign to data using ecdsa.
158
165
  # @param [String] data The 32-byte message hash being signed with binary format.
159
166
  # @param [String] private_key a private key with hex format using sign.
160
- # @param [String] extra_entropy (Optional)An extra entropy with binary format for rfc6979.
161
- # @return [String] signature data with binary format. If unsupported algorithm specified, return nil.
167
+ # @param [String] extra_entropy (Optional)A 32-byte extra entropy with hex or binary format for rfc6979.
168
+ # @return [String] DER-encoded signature data with binary format.
169
+ # @raise [Secp256k1::Error] If private_key is invalid or signing failed.
162
170
  # @raise [ArgumentError] If invalid arguments specified.
163
171
  def sign_ecdsa(data, private_key, extra_entropy = nil)
164
172
  validate_string!("private_key", private_key, 32)
@@ -166,29 +174,20 @@ module Secp256k1
166
174
  validate_string!("extra_entropy", extra_entropy, 32) if extra_entropy
167
175
  private_key = hex2bin(private_key)
168
176
  data = hex2bin(data)
177
+ extra_entropy = hex2bin(extra_entropy) if extra_entropy
169
178
 
170
179
  with_context do |context|
171
- secret = FFI::MemoryPointer.new(:uchar, private_key.bytesize).put_bytes(0, private_key)
172
- raise Error, 'private_key is invalid' unless secp256k1_ec_seckey_verify(context, secret)
180
+ secret = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, private_key)
181
+ raise Error, 'private_key is invalid.' unless secp256k1_ec_seckey_verify(context, secret) == 1
173
182
 
174
183
  internal_signature = FFI::MemoryPointer.new(:uchar, 64)
175
184
  msg32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, data)
176
185
  entropy = extra_entropy ? FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, extra_entropy) : nil
177
186
 
178
- ret, tries, max = 0, 0, 20
179
-
180
- while ret != 1
181
- raise Error, 'secp256k1_ecdsa_sign failed.' if tries >= max
182
- tries += 1
183
- ret = secp256k1_ecdsa_sign(context, internal_signature, msg32, secret, nil, entropy)
184
- end
185
-
186
- signature = FFI::MemoryPointer.new(:uchar, 72)
187
- signature_len = FFI::MemoryPointer.new(:uint64).put_uint64(0, 72)
188
- result = secp256k1_ecdsa_signature_serialize_der(context, signature, signature_len, internal_signature)
189
- raise Error, 'secp256k1_ecdsa_signature_serialize_der failed' unless result
187
+ # The nonce is derived deterministically (RFC6979), so retrying with the same inputs cannot help.
188
+ raise Error, 'secp256k1_ecdsa_sign failed.' unless secp256k1_ecdsa_sign(context, internal_signature, msg32, secret, nil, entropy) == 1
190
189
 
191
- signature.read_string(signature_len.read_uint64)
190
+ serialize_ecdsa_signature_der(context, internal_signature)
192
191
  end
193
192
  end
194
193
 
@@ -205,17 +204,15 @@ module Secp256k1
205
204
  data = hex2bin(data)
206
205
  pubkey = hex2bin(pubkey)
207
206
  signature = hex2bin(signature)
207
+ return false if pubkey.empty? || signature.empty?
208
208
  with_context do |context|
209
- return false if data.bytesize == 0
210
- pubkey = FFI::MemoryPointer.new(:uchar, pubkey.bytesize).put_bytes(0, pubkey)
209
+ pubkey_ptr = FFI::MemoryPointer.new(:uchar, pubkey.bytesize).put_bytes(0, pubkey)
211
210
  internal_pubkey = FFI::MemoryPointer.new(:uchar, 64)
212
- result = secp256k1_ec_pubkey_parse(context, internal_pubkey, pubkey, pubkey.size)
213
- return false unless result
211
+ return false unless secp256k1_ec_pubkey_parse(context, internal_pubkey, pubkey_ptr, pubkey.bytesize) == 1
214
212
 
215
- signature = FFI::MemoryPointer.new(:uchar, signature.bytesize).put_bytes(0, signature)
213
+ sig_ptr = FFI::MemoryPointer.new(:uchar, signature.bytesize).put_bytes(0, signature)
216
214
  internal_signature = FFI::MemoryPointer.new(:uchar, 64)
217
- result = secp256k1_ecdsa_signature_parse_der(context, internal_signature, signature, signature.size)
218
- return false unless result
215
+ return false unless secp256k1_ecdsa_signature_parse_der(context, internal_signature, sig_ptr, signature.bytesize) == 1
219
216
 
220
217
  # libsecp256k1's ECDSA verification requires lower-S signatures, which have not historically been enforced in Bitcoin, so normalize them first.
221
218
  secp256k1_ecdsa_signature_normalize(context, internal_signature, internal_signature)
@@ -257,10 +254,7 @@ module Secp256k1
257
254
  sig_ptr = FFI::MemoryPointer.new(:uchar, 64).put_bytes(0, signature)
258
255
  internal_signature = FFI::MemoryPointer.new(:uchar, 64)
259
256
  raise Error, 'secp256k1_ecdsa_signature_parse_compact failed.' unless secp256k1_ecdsa_signature_parse_compact(context, internal_signature, sig_ptr) == 1
260
- output = FFI::MemoryPointer.new(:uchar, 72)
261
- output_len = FFI::MemoryPointer.new(:uint64).put_uint64(0, 72)
262
- raise Error, 'secp256k1_ecdsa_signature_serialize_der failed.' unless secp256k1_ecdsa_signature_serialize_der(context, output, output_len, internal_signature) == 1
263
- output.read_string(output_len.read_uint64)
257
+ serialize_ecdsa_signature_der(context, internal_signature)
264
258
  end
265
259
  end
266
260
 
@@ -323,27 +317,46 @@ module Secp256k1
323
317
  output.read_string(X_ONLY_PUBKEY_SIZE).unpack1('H*')
324
318
  end
325
319
 
320
+ # Generate public key from +private_key+ using given +context+.
321
+ # +private_key+ must be a 32-byte binary string, not hex, to avoid a second
322
+ # hex conversion corrupting binary keys that happen to look like hex strings.
326
323
  def generate_pubkey_in_context(context, private_key, compressed: true)
327
324
  internal_pubkey = FFI::MemoryPointer.new(:uchar, 64)
328
- priv_ptr = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, hex2bin(private_key))
325
+ priv_ptr = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, private_key)
329
326
  result = secp256k1_ec_pubkey_create(context, internal_pubkey, priv_ptr)
330
- raise 'error creating pubkey' unless result
327
+ raise Error, 'private_key is invalid.' unless result == 1
331
328
  serialize_pubkey_internal(context, internal_pubkey, compressed)
332
329
  end
333
330
 
334
331
  # Serialize public key.
335
332
  def serialize_pubkey_internal(context, pubkey_input, compressed)
336
333
  pubkey = FFI::MemoryPointer.new(:uchar, 65)
337
- pubkey_len = FFI::MemoryPointer.new(:uint64)
338
- result = if compressed
339
- pubkey_len.put_uint64(0, 33)
340
- secp256k1_ec_pubkey_serialize(context, pubkey, pubkey_len, pubkey_input, EC_COMPRESSED)
341
- else
342
- pubkey_len.put_uint64(0, 65)
343
- secp256k1_ec_pubkey_serialize(context, pubkey, pubkey_len, pubkey_input, EC_UNCOMPRESSED)
344
- end
345
- raise Error, 'error serialize pubkey' unless result || pubkey_len.read_uint64 > 0
346
- pubkey.read_string(pubkey_len.read_uint64).unpack1('H*')
334
+ pubkey_len = FFI::MemoryPointer.new(:size_t)
335
+ pubkey_len.write(:size_t, compressed ? 33 : 65)
336
+ flags = compressed ? EC_COMPRESSED : EC_UNCOMPRESSED
337
+ raise Error, 'error serialize pubkey' unless secp256k1_ec_pubkey_serialize(context, pubkey, pubkey_len, pubkey_input, flags) == 1
338
+ pubkey.read_string(pubkey_len.read(:size_t)).unpack1('H*')
339
+ end
340
+
341
+ # Create an internal key pair(96 bytes) from a 32-byte binary private key using given +context+.
342
+ # @return [FFI::MemoryPointer] key pair pointer(96 bytes).
343
+ # @raise [Secp256k1::Error] If private_key is invalid.
344
+ def create_keypair_internal(context, private_key)
345
+ secret = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, private_key)
346
+ keypair = FFI::MemoryPointer.new(:uchar, 96)
347
+ raise Error, 'private_key is invalid.' unless secp256k1_keypair_create(context, keypair, secret) == 1
348
+ keypair
349
+ end
350
+
351
+ # Serialize an internal ECDSA signature(64 bytes) into DER format.
352
+ # @return [String] DER-encoded signature with binary format.
353
+ # @raise [Secp256k1::Error] If serialization failed.
354
+ def serialize_ecdsa_signature_der(context, internal_signature)
355
+ output = FFI::MemoryPointer.new(:uchar, 72)
356
+ output_len = FFI::MemoryPointer.new(:size_t)
357
+ output_len.write(:size_t, 72)
358
+ raise Error, 'secp256k1_ecdsa_signature_serialize_der failed.' unless secp256k1_ecdsa_signature_serialize_der(context, output, output_len, internal_signature) == 1
359
+ output.read_string(output_len.read(:size_t))
347
360
  end
348
361
 
349
362
  def hex_string?(str)
data/secp256k1rb.gemspec CHANGED
@@ -16,7 +16,7 @@ Gem::Specification.new do |spec|
16
16
 
17
17
  spec.metadata["homepage_uri"] = spec.homepage
18
18
  spec.metadata["source_code_uri"] = spec.homepage
19
- spec.metadata["changelog_uri"] = spec.homepage
19
+ spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/master/CHANGELOG.md"
20
20
 
21
21
  # Specify which files should be added to the gem when it is released.
22
22
  # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: secp256k1rb
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.8.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - azuchi
@@ -51,6 +51,7 @@ files:
51
51
  - lib/secp256k1/musig/session.rb
52
52
  - lib/secp256k1/recovery.rb
53
53
  - lib/secp256k1/schnorrsig.rb
54
+ - lib/secp256k1/silentpayments.rb
54
55
  - lib/secp256k1/version.rb
55
56
  - secp256k1rb.gemspec
56
57
  - sig/secp256k1.rbs
@@ -60,7 +61,7 @@ licenses:
60
61
  metadata:
61
62
  homepage_uri: https://github.com/azuchi/secp256k1rb
62
63
  source_code_uri: https://github.com/azuchi/secp256k1rb
63
- changelog_uri: https://github.com/azuchi/secp256k1rb
64
+ changelog_uri: https://github.com/azuchi/secp256k1rb/blob/master/CHANGELOG.md
64
65
  rdoc_options: []
65
66
  require_paths:
66
67
  - lib