secp256k1rb 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b1d7e33a444d5bbf4bf5cdfb3d57870bf810a568dbd5ff739c19b8f06a5e9329
4
+ data.tar.gz: 40a5994a593fef14c7f8a9993d9917d27b66405e5ab545f744f03f1d99554f9b
5
+ SHA512:
6
+ metadata.gz: 65a12acd88ec6e5b01faed7d98b950d1de72c08d0aab286266d4aceba2844f03319e86fb4a9d687107e94b6729f6c24d93897285c7c92cb036c2c43af2a40b55
7
+ data.tar.gz: 4b0f6b2e4b2faf1ebd7e59a07f28396eaf0bc07681ff429ad9189ecbc1fec7259458a53accd1cc618df14fccf240f9635b6ae596cbf88b56a2e297f7dbb73948
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-05-07
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at azuchi@chaintope.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in secp256k1.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 azuchi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # secp256k1rb
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/secp256k1`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'secp256k1rb', require: 'secp256k1'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install secp256k1rb
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/secp256k1. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/secp256k1/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the Secp256k1 project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/secp256k1/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "secp256k1"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,39 @@
1
+ require 'ffi'
2
+
3
+ module Secp256k1
4
+
5
+ # C interface
6
+ module C
7
+ extend FFI::Library
8
+
9
+ ffi_lib(ENV['SECP256K1_LIB_PATH'])
10
+
11
+ attach_function(:secp256k1_context_create, [:uint], :pointer)
12
+ attach_function(:secp256k1_context_destroy, [:pointer], :void)
13
+ attach_function(:secp256k1_context_randomize, [:pointer, :pointer], :int)
14
+ attach_function(:secp256k1_ec_pubkey_create, [:pointer, :pointer, :pointer], :int)
15
+ attach_function(:secp256k1_ec_seckey_verify, [:pointer, :pointer], :int)
16
+ attach_function(:secp256k1_ecdsa_sign, [:pointer, :pointer, :pointer, :pointer, :pointer, :pointer], :int)
17
+ attach_function(:secp256k1_ec_pubkey_serialize, [:pointer, :pointer, :pointer, :pointer, :uint], :int)
18
+ attach_function(:secp256k1_ecdsa_signature_serialize_der, [:pointer, :pointer, :pointer, :pointer], :int)
19
+ attach_function(:secp256k1_ec_pubkey_parse, [:pointer, :pointer, :pointer, :size_t], :int)
20
+ attach_function(:secp256k1_ecdsa_signature_parse_der, [:pointer, :pointer, :pointer, :size_t], :int)
21
+ attach_function(:secp256k1_ecdsa_signature_normalize, [:pointer, :pointer, :pointer], :int)
22
+ attach_function(:secp256k1_ecdsa_verify, [:pointer, :pointer, :pointer, :pointer], :int)
23
+ attach_function(:secp256k1_schnorrsig_sign32, [:pointer, :pointer, :pointer, :pointer, :pointer], :int)
24
+ attach_function(:secp256k1_schnorrsig_verify, [:pointer, :pointer, :pointer, :size_t, :pointer], :int)
25
+ attach_function(:secp256k1_keypair_create, [:pointer, :pointer, :pointer], :int)
26
+ attach_function(:secp256k1_xonly_pubkey_parse, [:pointer, :pointer, :pointer], :int)
27
+ attach_function(:secp256k1_ecdsa_sign_recoverable, [:pointer, :pointer, :pointer, :pointer, :pointer, :pointer], :int)
28
+ attach_function(:secp256k1_ecdsa_recoverable_signature_serialize_compact, [:pointer, :pointer, :pointer, :pointer], :int)
29
+ attach_function(:secp256k1_ecdsa_recover, [:pointer, :pointer, :pointer, :pointer], :int)
30
+ attach_function(:secp256k1_ecdsa_recoverable_signature_parse_compact, [:pointer, :pointer, :pointer, :int], :int)
31
+ attach_function(:secp256k1_ellswift_decode, [:pointer, :pointer, :pointer], :int)
32
+ attach_function(:secp256k1_ellswift_create, [:pointer, :pointer, :pointer, :pointer], :int)
33
+ # Define function pointer
34
+ callback(:secp256k1_ellswift_xdh_hash_function, [:pointer, :pointer, :pointer, :pointer, :pointer], :int)
35
+ attach_variable(:secp256k1_ellswift_xdh_hash_function_bip324, :secp256k1_ellswift_xdh_hash_function)
36
+ attach_function(:secp256k1_ellswift_xdh, [:pointer, :pointer, :pointer, :pointer, :pointer, :int, :pointer, :pointer], :int)
37
+
38
+ end
39
+ end
@@ -0,0 +1,74 @@
1
+ module Secp256k1
2
+ module ELLSwift
3
+ # Decode ellswift public key.
4
+ # @param [String] ell_key ElligatorSwift key with binary format.
5
+ # @return [String] Decoded public key with hex format.
6
+ # @raise [Secp256k1::Error] If decode failed.
7
+ # @raise [ArgumentError] If invalid arguments specified.
8
+ def ellswift_decode(ell_key)
9
+ raise ArgumentError, "ell_key must be String." unless ell_key.is_a?(String)
10
+ ell_key = hex2bin(ell_key)
11
+ raise ArgumentError, "ell_key must be 64 bytes." unless ell_key.bytesize == 64
12
+ with_context do |context|
13
+ ell64 = FFI::MemoryPointer.new(:uchar, ell_key.bytesize).put_bytes(0, ell_key)
14
+ internal = FFI::MemoryPointer.new(:uchar, 64)
15
+ result = secp256k1_ellswift_decode(context, internal, ell64)
16
+ raise Error, 'Decode failed.' unless result == 1
17
+ serialize_pubkey_internal(context, internal, true)
18
+ end
19
+ end
20
+
21
+ # Compute an ElligatorSwift public key for a secret key.
22
+ # @param [String] private_key private key with hex format
23
+ # @return [String] ElligatorSwift public key with hex format.
24
+ # @raise [Secp256k1::Error] If failed to create elligattor swhift public key.
25
+ # @raise [ArgumentError] If invalid arguments specified.
26
+ def ellswift_create(private_key)
27
+ raise ArgumentError, "private_key must be String." unless private_key.is_a?(String)
28
+ private_key = hex2bin(private_key)
29
+ raise ArgumentError, "private_key must be 32 bytes." unless private_key.bytesize == 32
30
+ with_context(flags: SECP256K1_CONTEXT_SIGN) do |context|
31
+ ell64 = FFI::MemoryPointer.new(:uchar, 64)
32
+ seckey32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, private_key)
33
+ result = secp256k1_ellswift_create(context, ell64, seckey32, nil)
34
+ raise Error, 'Failed to create ElligatorSwift public key.' unless result == 1
35
+ ell64.read_string(64).unpack1('H*')
36
+ end
37
+ end
38
+
39
+ # Compute X coordinate of shared ECDH point between elswift pubkey and private_key.
40
+ # @param [String] their_ell_pubkey Their EllSwift public key.
41
+ # @param [String] our_ell_pubkey Our EllSwift public key.
42
+ # @param [String] private_key private key with hex format.
43
+ # @param [Boolean] initiating Whether your initiator or not.
44
+ # @return [String] x coordinate with hex format.
45
+ # @raise [Secp256k1::Error] If secret is invalid or hashfp return 0.
46
+ def ellswift_ecdh_xonly(their_ell_pubkey, our_ell_pubkey, private_key, initiating)
47
+ raise ArgumentError, "their_ell_pubkey must be String." unless their_ell_pubkey.is_a?(String)
48
+ raise ArgumentError, "our_ell_pubkey must be String." unless our_ell_pubkey.is_a?(String)
49
+ raise ArgumentError, "private_key must be String." unless private_key.is_a?(String)
50
+ their_ell_pubkey = hex2bin(their_ell_pubkey)
51
+ our_ell_pubkey = hex2bin(our_ell_pubkey)
52
+ private_key = hex2bin(private_key)
53
+ raise ArgumentError, "their_ell_pubkey must be #{ELL_SWIFT_KEY_SIZE} bytes." unless their_ell_pubkey.bytesize == ELL_SWIFT_KEY_SIZE
54
+ raise ArgumentError, "our_ell_pubkey must be #{ELL_SWIFT_KEY_SIZE} bytes." unless our_ell_pubkey.bytesize == ELL_SWIFT_KEY_SIZE
55
+ raise ArgumentError, "private_key must be 32 bytes." unless private_key.bytesize == 32
56
+
57
+ with_context(flags: SECP256K1_CONTEXT_SIGN) do |context|
58
+ output = FFI::MemoryPointer.new(:uchar, 32)
59
+ our_ell_ptr = FFI::MemoryPointer.new(:uchar, 64).put_bytes(0, our_ell_pubkey)
60
+ their_ell_ptr = FFI::MemoryPointer.new(:uchar, 64).put_bytes(0, their_ell_pubkey)
61
+ seckey32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, private_key)
62
+ hashfp = secp256k1_ellswift_xdh_hash_function_bip324
63
+ result = secp256k1_ellswift_xdh(context, output,
64
+ initiating ? our_ell_ptr : their_ell_ptr,
65
+ initiating ? their_ell_ptr : our_ell_ptr,
66
+ seckey32,
67
+ initiating ? 0 : 1,
68
+ hashfp, nil)
69
+ raise Error, "secret was invalid or hashfp returned 0." unless result == 1
70
+ output.read_string(32).unpack1('H*')
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,66 @@
1
+ module Secp256k1
2
+ module Recover
3
+ # Sign data with compact format.
4
+ # @param [String] data The 32-byte message hash being signed.
5
+ # @param [String] private_key a private key using sign with hex format
6
+ # @return [Array] Array of signature and recovery id.
7
+ # @raise [Secp256k1::Error] If recovery failed.
8
+ # @raise [ArgumentError] If invalid arguments specified.
9
+ def sign_recoverable(data, private_key)
10
+ raise ArgumentError, "private_key must be String." unless private_key.is_a?(String)
11
+ raise ArgumentError, "data must by String." unless data.is_a?(String)
12
+ private_key = hex2bin(private_key)
13
+ raise ArgumentError, "private_key must be 32 bytes." unless private_key.bytesize == 32
14
+ data = hex2bin(data)
15
+ raise ArgumentError, "data must be 32 bytes." unless data.bytesize == 32
16
+
17
+ with_context do |context|
18
+ sig = FFI::MemoryPointer.new(:uchar, 65)
19
+ hash =FFI::MemoryPointer.new(:uchar, data.bytesize).put_bytes(0, data)
20
+ sec_key = FFI::MemoryPointer.new(:uchar, private_key.bytesize).put_bytes(0, private_key)
21
+ result = secp256k1_ecdsa_sign_recoverable(context, sig, hash, sec_key, nil, nil)
22
+ raise Error, 'secp256k1_ecdsa_sign_recoverable failed.' if result == 0
23
+
24
+ output = FFI::MemoryPointer.new(:uchar, 64)
25
+ rec = FFI::MemoryPointer.new(:uint64)
26
+ result = secp256k1_ecdsa_recoverable_signature_serialize_compact(context, output, rec, sig)
27
+ raise Error, 'secp256k1_ecdsa_recoverable_signature_serialize_compact failed.' unless result == 1
28
+
29
+ sig = output.read_string(64).unpack1('H*')
30
+ [sig, rec.read(:int)]
31
+ end
32
+ end
33
+
34
+ # Recover public key from compact signature.
35
+ # @param [String] data The 32-byte message hash assumed to be signed.
36
+ # @param [String] signature The signature with binary format (65 bytes).
37
+ # @param [Boolean] compressed whether compressed public key or not.
38
+ # @return [String] Recovered public key with hex format.
39
+ # @raise [Secp256k1::Error] If recover failed.
40
+ # @raise [ArgumentError] If invalid arguments specified.
41
+ def recover(data, signature, compressed)
42
+ raise ArgumentError, "data must be String." unless data.is_a?(String)
43
+ raise ArgumentError, "signature must be String." unless signature.is_a?(String)
44
+ signature = hex2bin(signature)
45
+ raise ArgumentError, "signature must be 64 bytes." unless signature.bytesize == 65
46
+ data = hex2bin(data)
47
+ raise ArgumentError, "data must be 32 bytes." unless data.bytesize == 32
48
+ rec = (signature[0].ord - 0x1b) & 3
49
+ raise ArgumentError, "rec must be between 0 and 3." if rec < 0 || rec > 3
50
+
51
+ with_context do |context|
52
+ sig = FFI::MemoryPointer.new(:uchar, 65)
53
+ input = FFI::MemoryPointer.new(:uchar, 64).put_bytes(0, signature[1..-1])
54
+ result = secp256k1_ecdsa_recoverable_signature_parse_compact(context, sig, input, rec)
55
+ raise Error, 'secp256k1_ecdsa_recoverable_signature_parse_compact failed.' unless result == 1
56
+
57
+ pubkey = FFI::MemoryPointer.new(:uchar, 64)
58
+ msg = FFI::MemoryPointer.new(:uchar, data.bytesize).put_bytes(0, data)
59
+ result = secp256k1_ecdsa_recover(context, pubkey, sig, msg)
60
+ raise Error, 'secp256k1_ecdsa_recover failed.' unless result == 1
61
+
62
+ serialize_pubkey_internal(context, pubkey.read_string(64), compressed)
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,55 @@
1
+ module Secp256k1
2
+ module SchnorrSig
3
+
4
+ # Sign to data using schnorr.
5
+ # @param [String] data The 32-byte message hash being signed with binary format.
6
+ # @param [String] private_key a private key with hex format using sign.
7
+ # @param [String] aux_rand a extra entropy.
8
+ # @return [String] signature data with binary format. If unsupported algorithm specified, return nil.
9
+ # @raise [ArgumentError] If invalid arguments specified.
10
+ def sign_schnorr(data, private_key, aux_rand = nil)
11
+ raise ArgumentError, "private_key must be String." unless private_key.is_a?(String)
12
+ raise ArgumentError, "data must by String." unless data.is_a?(String)
13
+ raise ArgumentError, "aux_rand must be String." if !aux_rand.nil? && !aux_rand.is_a?(String)
14
+ private_key = hex2bin(private_key)
15
+ raise ArgumentError, "private_key must be 32 bytes." unless private_key.bytesize == 32
16
+ data = hex2bin(data)
17
+ raise ArgumentError, "data must be 32 bytes." unless data.bytesize == 32
18
+
19
+ with_context do |context|
20
+ keypair = [create_keypair(private_key)].pack('H*')
21
+ keypair = FFI::MemoryPointer.new(:uchar, 96).put_bytes(0, keypair)
22
+ signature = FFI::MemoryPointer.new(:uchar, 64)
23
+ msg32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, data)
24
+ aux_rand = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, aux_rand) if aux_rand
25
+ raise Error, 'Failed to generate schnorr signature.' unless secp256k1_schnorrsig_sign32(context, signature, msg32, keypair, aux_rand) == 1
26
+ signature.read_string(64)
27
+ end
28
+ end
29
+
30
+ # Verify ecdsa signature.
31
+ # @param [String] data The 32-byte message hash assumed to be signed.
32
+ # @param [String] signature signature data with binary format
33
+ # @param [String] pubkey a public key with hex format using verify.
34
+ # @return [Boolean] verification result.
35
+ # @raise [ArgumentError] If invalid arguments specified.
36
+ def verify_schnorr(data, signature, pubkey)
37
+ raise ArgumentError, "sig must be String." unless signature.is_a?(String)
38
+ raise ArgumentError, "pubkey must be String." unless pubkey.is_a?(String)
39
+ raise ArgumentError, "data must be String." unless data.is_a?(String)
40
+ data = hex2bin(data)
41
+ raise ArgumentError, "data must be 32 bytes." unless data.bytesize == 32
42
+ pubkey = hex2bin(pubkey)
43
+ signature = hex2bin(signature)
44
+ with_context do |context|
45
+ return false if data.bytesize == 0
46
+ pubkey = [full_pubkey_from_xonly_pubkey(pubkey)].pack('H*')
47
+ xonly_pubkey = FFI::MemoryPointer.new(:uchar, pubkey.bytesize).put_bytes(0, pubkey)
48
+ signature = FFI::MemoryPointer.new(:uchar, signature.bytesize).put_bytes(0, signature)
49
+ msg32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, data)
50
+ result = secp256k1_schnorrsig_verify(context, signature, msg32, 32, xonly_pubkey)
51
+ result == 1
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Secp256k1
4
+ VERSION = "0.1.0"
5
+ end
data/lib/secp256k1.rb ADDED
@@ -0,0 +1,285 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+ require_relative "secp256k1/version"
5
+ require_relative 'secp256k1/c'
6
+ require_relative 'secp256k1/recovery'
7
+ require_relative 'secp256k1/ellswift'
8
+ require_relative 'secp256k1/schnorrsig'
9
+
10
+ # Binding for secp256k1 (https://github.com/bitcoin-core/secp256k1/)
11
+ module Secp256k1
12
+
13
+ class Error < StandardError; end
14
+
15
+ include C
16
+ include Recover
17
+ include SchnorrSig
18
+ include ELLSwift
19
+
20
+ FLAGS_TYPE_MASK = ((1 << 8) - 1)
21
+ FLAGS_TYPE_CONTEXT = (1 << 0)
22
+ FLAGS_TYPE_COMPRESSION = (1 << 1)
23
+
24
+ FLAGS_BIT_CONTEXT_VERIFY = (1 << 8)
25
+ FLAGS_BIT_CONTEXT_SIGN = (1 << 9)
26
+ FLAGS_BIT_COMPRESSION = (1 << 8)
27
+
28
+ # Flags to pass to context_create.
29
+ CONTEXT_VERIFY = (FLAGS_TYPE_CONTEXT | FLAGS_BIT_CONTEXT_VERIFY)
30
+ CONTEXT_SIGN = (FLAGS_TYPE_CONTEXT | FLAGS_BIT_CONTEXT_SIGN)
31
+
32
+ # Flag to pass to ec_pubkey_serialize and ec_privkey_export.
33
+ EC_COMPRESSED = (FLAGS_TYPE_COMPRESSION | FLAGS_BIT_COMPRESSION)
34
+ EC_UNCOMPRESSED = (FLAGS_TYPE_COMPRESSION)
35
+
36
+ X_ONLY_PUBKEY_SIZE = 32
37
+ ELL_SWIFT_KEY_SIZE = 64
38
+
39
+ # Creates a secp256k1 context object, performs the operations passed in the block,
40
+ # and then ensures that the secp256k1 context object is destroyed at the end.
41
+ # @param [Integer] flags The flag to use when performing the operation.
42
+ # @raise [Secp256k1::Error] If secp256k1_context_randomize failed.
43
+ def with_context(flags: (CONTEXT_VERIFY | CONTEXT_SIGN))
44
+ begin
45
+ context = secp256k1_context_create(flags)
46
+ ret, tries, max = 0, 0, 20
47
+ while ret != 1
48
+ raise Error, 'secp256k1_context_randomize failed.' if tries >= max
49
+ tries += 1
50
+ ret = secp256k1_context_randomize(context, FFI::MemoryPointer.from_string(SecureRandom.random_bytes(32)))
51
+ end
52
+ yield(context) if block_given?
53
+ ensure
54
+ secp256k1_context_destroy(context)
55
+ end
56
+ end
57
+
58
+ # Randomly generate ec private key and public key.
59
+ # @param [Boolean] compressed Whether to generate a compressed public key.
60
+ # @return [Array] Array of public key and public key (Both are hex values).
61
+ # @raise [Secp256k1::Error] If secp256k1_ec_seckey_verify in generate_key_pair failed.
62
+ def generate_key_pair(compressed: true)
63
+ with_context do |context|
64
+ ret, tries, max = 0, 0, 20
65
+ while ret != 1
66
+ raise Error, 'secp256k1_ec_seckey_verify in generate_key_pair failed.' if tries >= max
67
+ tries += 1
68
+ private_key = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, SecureRandom.random_bytes(32))
69
+ ret = secp256k1_ec_seckey_verify(context, private_key)
70
+ end
71
+ private_key = private_key.read_string(32).unpack1('H*')
72
+ [private_key , generate_pubkey_in_context(context, private_key, compressed: compressed) ]
73
+ end
74
+ end
75
+
76
+ # Generate public key from +private_key+.
77
+ # @param [String] private_key Private key with hex format.
78
+ # @param [Boolean] compressed Whether to generate a compressed public key.
79
+ # @return [String] Public key with hex format.
80
+ # @raise [ArgumentError] If invalid arguments specified.
81
+ def generate_pubkey(private_key, compressed: true)
82
+ raise ArgumentError, "private_key must be String." unless private_key.is_a?(String)
83
+ private_key = hex2bin(private_key)
84
+ raise ArgumentError, "private_key must by 32 bytes." unless private_key.bytesize == 32
85
+ with_context do |context|
86
+ generate_pubkey_in_context(context, private_key, compressed: compressed)
87
+ end
88
+ end
89
+
90
+ # Sign to data.
91
+ # @param [String] data The 32-byte message hash being signed with binary format.
92
+ # @param [String] private_key a private key with hex format using sign.
93
+ # @param [String] extra_entropy a extra entropy with binary format for rfc6979.
94
+ # @param [Symbol] algo signature algorithm. ecdsa(default) or schnorr.
95
+ # @return [String] signature data with binary format. If unsupported algorithm specified, return nil.
96
+ # @raise [ArgumentError] If invalid arguments specified.
97
+ def sign_data(data, private_key, extra_entropy = nil, algo: :ecdsa)
98
+
99
+ case algo
100
+ when :ecdsa
101
+ sign_ecdsa(data, private_key, extra_entropy)
102
+ when :schnorr
103
+ sign_schnorr(data, private_key, extra_entropy)
104
+ else
105
+ raise ArgumentError, "unknown algo: #{algo}"
106
+ end
107
+ end
108
+
109
+
110
+ # Validate whether this is a valid public key.
111
+ # @param [String] pubkey public key with hex format.
112
+ # @param [Boolean] allow_hybrid whether support hybrid public key.
113
+ # @return [Boolean] If valid public key return true, otherwise false.
114
+ # @raise [ArgumentError] If invalid arguments specified.
115
+ def parse_ec_pubkey?(pubkey, allow_hybrid = false)
116
+ raise ArgumentError, "pubkey must be String." unless pubkey.is_a?(String)
117
+ pubkey = hex2bin(pubkey)
118
+ return false if !allow_hybrid && ![0x02, 0x03, 0x04].include?(pubkey[0].ord)
119
+ with_context do |context|
120
+ pubkey_size = pubkey.bytesize
121
+ pubkey = FFI::MemoryPointer.new(:uchar, pubkey_size).put_bytes(0, pubkey)
122
+ internal_pubkey = FFI::MemoryPointer.new(:uchar, 64)
123
+ result = secp256k1_ec_pubkey_parse(context, internal_pubkey, pubkey, pubkey_size)
124
+ result == 1
125
+ end
126
+ end
127
+
128
+ # Create key pair data from private key.
129
+ # @param [String] private_key with hex format
130
+ # @return [String] key pair data with hex format. data = private key(32 bytes) | public key(64 bytes).
131
+ # @raise [Secp256k1::Error] If private_key is invalid.
132
+ # @raise [ArgumentError] If invalid arguments specified.
133
+ def create_keypair(private_key)
134
+ raise ArgumentError, "private_key must be String." unless private_key.is_a?(String)
135
+ private_key = hex2bin(private_key)
136
+ raise ArgumentError, "private_key must be 32 bytes." unless private_key.bytesize == 32
137
+ with_context do |context|
138
+ secret = FFI::MemoryPointer.new(:uchar, private_key.bytesize).put_bytes(0, private_key)
139
+ raise Error, 'private_key is invalid.' unless secp256k1_ec_seckey_verify(context, secret)
140
+ keypair = FFI::MemoryPointer.new(:uchar, 96)
141
+ raise Error 'private_key is invalid.' unless secp256k1_keypair_create(context, keypair, secret) == 1
142
+ keypair.read_string(96).unpack1('H*')
143
+ end
144
+ end
145
+
146
+ # Check whether valid x-only public key or not.
147
+ # @param [String] pubkey x-only public key with hex format(32 bytes).
148
+ # @return [Boolean] result.
149
+ def valid_xonly_pubkey?(pubkey)
150
+ return false unless pubkey.is_a?(String)
151
+ begin
152
+ full_pubkey_from_xonly_pubkey(hex2bin(pubkey))
153
+ rescue Exception
154
+ return false
155
+ end
156
+ true
157
+ end
158
+
159
+ # Sign to data using ecdsa.
160
+ # @param [String] data The 32-byte message hash being signed with binary format.
161
+ # @param [String] private_key a private key with hex format using sign.
162
+ # @param [String] extra_entropy a extra entropy with binary format for rfc6979.
163
+ # @return [String] signature data with binary format. If unsupported algorithm specified, return nil.
164
+ # @raise [ArgumentError] If invalid arguments specified.
165
+ def sign_ecdsa(data, private_key, extra_entropy)
166
+ raise ArgumentError, "private_key must be String." unless private_key.is_a?(String)
167
+ raise ArgumentError, "data must by String." unless data.is_a?(String)
168
+ raise ArgumentError, "extra_entropy must be String." if !extra_entropy.nil? && !extra_entropy.is_a?(String)
169
+ private_key = hex2bin(private_key)
170
+ raise ArgumentError, "private_key must be 32 bytes." unless private_key.bytesize == 32
171
+ data = hex2bin(data)
172
+ raise ArgumentError, "data must be 32 bytes." unless data.bytesize == 32
173
+
174
+ with_context do |context|
175
+ secret = FFI::MemoryPointer.new(:uchar, private_key.bytesize).put_bytes(0, private_key)
176
+ raise Error, 'private_key is invalid' unless secp256k1_ec_seckey_verify(context, secret)
177
+
178
+ internal_signature = FFI::MemoryPointer.new(:uchar, 64)
179
+ msg32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, data)
180
+ entropy = extra_entropy ? FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, extra_entropy) : nil
181
+
182
+ ret, tries, max = 0, 0, 20
183
+
184
+ while ret != 1
185
+ raise Error, 'secp256k1_ecdsa_sign failed.' if tries >= max
186
+ tries += 1
187
+ ret = secp256k1_ecdsa_sign(context, internal_signature, msg32, secret, nil, entropy)
188
+ end
189
+
190
+ signature = FFI::MemoryPointer.new(:uchar, 72)
191
+ signature_len = FFI::MemoryPointer.new(:uint64).put_uint64(0, 72)
192
+ result = secp256k1_ecdsa_signature_serialize_der(context, signature, signature_len, internal_signature)
193
+ raise Error, 'secp256k1_ecdsa_signature_serialize_der failed' unless result
194
+
195
+ signature.read_string(signature_len.read_uint64)
196
+ end
197
+ end
198
+
199
+ # Verify ecdsa signature.
200
+ # @param [String] data The 32-byte message hash assumed to be signed.
201
+ # @param [String] signature signature data with binary format
202
+ # @param [String] pubkey a public key with hex format using verify.
203
+ # @return [Boolean] verification result.
204
+ # @raise [ArgumentError] If invalid arguments specified.
205
+ def verify_ecdsa(data, signature, pubkey)
206
+ raise ArgumentError, "sig must be String." unless signature.is_a?(String)
207
+ raise ArgumentError, "pubkey must be String." unless pubkey.is_a?(String)
208
+ raise ArgumentError, "data must be String." unless data.is_a?(String)
209
+ data = hex2bin(data)
210
+ raise ArgumentError, "data must be 32 bytes." unless data.bytesize == 32
211
+ pubkey = hex2bin(pubkey)
212
+ signature = hex2bin(signature)
213
+ with_context do |context|
214
+ return false if data.bytesize == 0
215
+ pubkey = FFI::MemoryPointer.new(:uchar, pubkey.bytesize).put_bytes(0, pubkey)
216
+ internal_pubkey = FFI::MemoryPointer.new(:uchar, 64)
217
+ result = secp256k1_ec_pubkey_parse(context, internal_pubkey, pubkey, pubkey.size)
218
+ return false unless result
219
+
220
+ signature = FFI::MemoryPointer.new(:uchar, signature.bytesize).put_bytes(0, signature)
221
+ internal_signature = FFI::MemoryPointer.new(:uchar, 64)
222
+ result = secp256k1_ecdsa_signature_parse_der(context, internal_signature, signature, signature.size)
223
+ return false unless result
224
+
225
+ # libsecp256k1's ECDSA verification requires lower-S signatures, which have not historically been enforced in Bitcoin, so normalize them first.
226
+ secp256k1_ecdsa_signature_normalize(context, internal_signature, internal_signature)
227
+
228
+ msg32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, data)
229
+ result = secp256k1_ecdsa_verify(context, internal_signature, msg32, internal_pubkey)
230
+
231
+ result == 1
232
+ end
233
+ end
234
+
235
+ private
236
+
237
+ # Calculate full public key(64 bytes) from public key(32 bytes).
238
+ # @param [String] pubkey x-only public key with hex format(32 bytes).
239
+ # @return [String] x-only public key with hex format(64 bytes).
240
+ # @raise ArgumentError
241
+ def full_pubkey_from_xonly_pubkey(pubkey)
242
+ with_context do |context|
243
+ raise ArgumentError, "Pubkey size must be #{X_ONLY_PUBKEY_SIZE} bytes." unless pubkey.bytesize == X_ONLY_PUBKEY_SIZE
244
+ xonly_pubkey = FFI::MemoryPointer.new(:uchar, pubkey.bytesize).put_bytes(0, pubkey)
245
+ full_pubkey = FFI::MemoryPointer.new(:uchar, 64)
246
+ raise ArgumentError, 'An invalid public key was specified.' unless secp256k1_xonly_pubkey_parse(context, full_pubkey, xonly_pubkey) == 1
247
+ full_pubkey.read_string(64).unpack1('H*')
248
+ end
249
+ end
250
+
251
+ def generate_pubkey_in_context(context, private_key, compressed: true)
252
+ internal_pubkey = FFI::MemoryPointer.new(:uchar, 64)
253
+ priv_ptr = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, hex2bin(private_key))
254
+ result = secp256k1_ec_pubkey_create(context, internal_pubkey, priv_ptr)
255
+ raise 'error creating pubkey' unless result
256
+ serialize_pubkey_internal(context, internal_pubkey, compressed)
257
+ end
258
+
259
+ # Serialize public key.
260
+ def serialize_pubkey_internal(context, pubkey_input, compressed)
261
+ pubkey = FFI::MemoryPointer.new(:uchar, 65)
262
+ pubkey_len = FFI::MemoryPointer.new(:uint64)
263
+ result = if compressed
264
+ pubkey_len.put_uint64(0, 33)
265
+ secp256k1_ec_pubkey_serialize(context, pubkey, pubkey_len, pubkey_input, EC_COMPRESSED)
266
+ else
267
+ pubkey_len.put_uint64(0, 65)
268
+ secp256k1_ec_pubkey_serialize(context, pubkey, pubkey_len, pubkey_input, EC_UNCOMPRESSED)
269
+ end
270
+ raise Error, 'error serialize pubkey' unless result || pubkey_len.read_uint64 > 0
271
+ pubkey.read_string(pubkey_len.read_uint64).unpack1('H*')
272
+ end
273
+
274
+ def hex_string?(str)
275
+ return false if str.bytes.any? { |b| b > 127 }
276
+ return false if str.length % 2 != 0
277
+ hex_chars = str.chars.to_a
278
+ hex_chars.all? { |c| c =~ /[0-9a-fA-F]/ }
279
+ end
280
+
281
+ def hex2bin(str)
282
+ hex_string?(str) ? [str].pack('H*') : str
283
+ end
284
+ end
285
+
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/secp256k1/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "secp256k1rb"
7
+ spec.version = Secp256k1::VERSION
8
+ spec.authors = ["azuchi"]
9
+ spec.email = ["azuchi@chaintope.com"]
10
+
11
+ spec.summary = "Ruby binding for libsecp256k1."
12
+ spec.description = spec.summary
13
+ spec.homepage = "https://github.com/azuchi/secp256k1rb"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.0.0"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = spec.homepage
19
+ spec.metadata["changelog_uri"] = spec.homepage
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
24
+ `git ls-files -z`.split("\x0").reject do |f|
25
+ (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
26
+ end
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ # Uncomment to register a new dependency of your gem
33
+ spec.add_dependency "ffi", ">= 1.16.3"
34
+
35
+ # For more information and examples about making a new gem, check out our
36
+ # guide at: https://bundler.io/guides/creating_gem.html
37
+ end
data/sig/secp256k1.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Secp256k1
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,77 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: secp256k1rb
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - azuchi
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-11-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ffi
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 1.16.3
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 1.16.3
27
+ description: Ruby binding for libsecp256k1.
28
+ email:
29
+ - azuchi@chaintope.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rspec"
35
+ - CHANGELOG.md
36
+ - CODE_OF_CONDUCT.md
37
+ - Gemfile
38
+ - LICENSE.txt
39
+ - README.md
40
+ - Rakefile
41
+ - bin/console
42
+ - bin/setup
43
+ - lib/secp256k1.rb
44
+ - lib/secp256k1/c.rb
45
+ - lib/secp256k1/ellswift.rb
46
+ - lib/secp256k1/recovery.rb
47
+ - lib/secp256k1/schnorrsig.rb
48
+ - lib/secp256k1/version.rb
49
+ - secp256k1rb.gemspec
50
+ - sig/secp256k1.rbs
51
+ homepage: https://github.com/azuchi/secp256k1rb
52
+ licenses:
53
+ - MIT
54
+ metadata:
55
+ homepage_uri: https://github.com/azuchi/secp256k1rb
56
+ source_code_uri: https://github.com/azuchi/secp256k1rb
57
+ changelog_uri: https://github.com/azuchi/secp256k1rb
58
+ post_install_message:
59
+ rdoc_options: []
60
+ require_paths:
61
+ - lib
62
+ required_ruby_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: 3.0.0
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ requirements: []
73
+ rubygems_version: 3.2.3
74
+ signing_key:
75
+ specification_version: 4
76
+ summary: Ruby binding for libsecp256k1.
77
+ test_files: []