From 6fbf16b36c5de3d0bfd6595ab23ae82183c29cb1 Mon Sep 17 00:00:00 2001 From: azuchi Date: Fri, 15 Dec 2023 17:48:26 +0900 Subject: [PATCH] Add Key#decompress_pubkey that return uncompressed public key with hex format --- lib/bitcoin/key.rb | 6 ++++++ spec/bitcoin/key_spec.rb | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/lib/bitcoin/key.rb b/lib/bitcoin/key.rb index a886737..515a8b8 100644 --- a/lib/bitcoin/key.rb +++ b/lib/bitcoin/key.rb @@ -261,6 +261,12 @@ def xonly_pubkey pubkey[2..65] end + # Convert this key to decompress key. + # @return [String] decompress public key with hex format. + def decompress_pubkey + pubkey.htb.bytesize == PUBLIC_KEY_SIZE ? pubkey : to_point.to_hex(false) + end + # check +pubkey+ (hex) is compress or uncompress pubkey. def self.compress_or_uncompress_pubkey?(pubkey) p = pubkey.htb diff --git a/spec/bitcoin/key_spec.rb b/spec/bitcoin/key_spec.rb index ddc7f53..90f2117 100644 --- a/spec/bitcoin/key_spec.rb +++ b/spec/bitcoin/key_spec.rb @@ -318,4 +318,26 @@ def test_generate end end + describe '#decompress_pubkey' do + context 'pure ruby' do + it 'return decompressed public key' do + test_decompress + end + end + + context 'libsecp256k1', use_secp256k1: true do + it 'return decompressed public key' do + test_decompress + end + end + + def test_decompress + compress_key = Bitcoin::Key.generate(Bitcoin::Key::TYPES[:compressed]) + uncompressed_pubkey = Bitcoin::Key.new(priv_key: compress_key.priv_key, key_type: Bitcoin::Key::TYPES[:uncompressed]) + expect(compress_key.decompress_pubkey).to eq(uncompressed_pubkey.pubkey) + + uncompressed_key = Bitcoin::Key.generate(Bitcoin::Key::TYPES[:uncompressed]) + expect(uncompressed_key.decompress_pubkey).to eq(uncompressed_key.pubkey) + end + end end