The personal finance app for everyone (by everyone)
Ruby
Add watch-only Bitcoin public keys and address validation (#4615)
Artem Danilovf3d404c5d61d
diff --git a/Gemfile b/Gemfileindex ac97a8e009..9272c4755d 100644--- a/Gemfile+++ b/Gemfile@@ -9,6 +9,9 @@ gem "rails", "~> 8.1.0"gem "pg", "~> 1.5"gem "redis", "~> 5.4"+# Bech32/Bech32m encoding for watch-only Bitcoin addresses.+gem "bech32", "1.5.1"+# Deploymentgem "puma", ">= 7.2.1"gem "bootsnap", require: falsediff --git a/Gemfile.lock b/Gemfile.lockindex 2808b2dfab..4b13c731c8 100644--- a/Gemfile.lock+++ b/Gemfile.lock@@ -121,6 +121,8 @@ GEMaws-eventstream (~> 1, >= 1.0.2)base64 (0.3.0)bcrypt (3.1.22)+ bech32 (1.5.1)+ thor (>= 1.1.0)benchmark (0.5.0)benchmark-ips (2.14.0)better_html (2.1.1)@@ -923,6 +925,7 @@ DEPENDENCIESapnotic (~> 1.8)aws-sdk-s3 (~> 1.208.0)bcrypt (~> 3.1)+ bech32 (= 1.5.1)benchmark-ipsbootsnapbrakemandiff --git a/app/models/onchain/bitcoin_adapter.rb b/app/models/onchain/bitcoin_adapter.rbindex b804c90558..32082773a0 100644--- a/app/models/onchain/bitcoin_adapter.rb+++ b/app/models/onchain/bitcoin_adapter.rb@@ -18,27 +18,20 @@ class Onchain::BitcoinAdapterSATS_PER_BTC = 100_000_000.to_d- # P2PKH ("1…") and P2SH ("3…"), Base58Check: no 0, O, I or l.- BASE58_PATTERN = /\A[13][1-9A-HJ-NP-Za-km-z]{25,39}\z/- # Bech32 (P2WPKH/P2WSH, "bc1q…") and Bech32m (Taproot, "bc1p…"). The bech32- # character set excludes 1, b, i and o after the separator.- BECH32_PATTERN = /\Abc1[ac-hj-np-z02-9]{11,87}\z/i-def initialize(credentials: {})@credentials = credentialsend+ # Checksum-verified, so a mistyped address is refused instead of syncing as empty.def valid_address?(address)- candidate = address.to_s.strip- BASE58_PATTERN.match?(candidate) || BECH32_PATTERN.match?(candidate)+ Onchain::BitcoinPublicKey.valid_address?(address.to_s.strip)end# Bech32 is case-insensitive and canonically lowercase — and the API reports it# that way, so an uppercase input would otherwise match no output and silently# produce zero movements. Base58 is case-sensitive and must be left alone.def canonical_address(address)- candidate = address.to_s.strip- BECH32_PATTERN.match?(candidate) ? candidate.downcase : candidate+ Onchain::BitcoinPublicKey.canonical_address(address)enddef fetch_snapshot(address)diff --git a/app/models/onchain/bitcoin_public_key.rb b/app/models/onchain/bitcoin_public_key.rbnew file mode 100644index 0000000000..31ee8e8afe--- /dev/null+++ b/app/models/onchain/bitcoin_public_key.rb@@ -0,0 +1,103 @@+# frozen_string_literal: true++module Onchain+ # An account-level mainnet key, interpreted explicitly as BIP84. An xpub's+ # version cannot tell us its script type, so the linking flow also verifies+ # an address the owner obtained independently from their hardware wallet.+ class BitcoinPublicKey+ class InvalidKey < ArgumentError; end++ VERSIONS = %w[0488b21e 04b24746].freeze # mainnet xpub, zpub+ BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"+ CURVE = OpenSSL::PKey::EC::Group.new("secp256k1")++ # Parse a mainnet account-level xpub/zpub and reject private keys, wrong+ # depths and unsupported encodings before any address derivation occurs.+ def initialize(value)+ text = value.to_s.strip+ raise InvalidKey, "Use a mainnet account xpub or zpub" unless text.length <= 112 && text.start_with?("xpub", "zpub")++ # version(4) depth(1) parent fingerprint(4) child number(4) chain code(32) key(33)+ payload = self.class.base58check_decode(text)+ raise InvalidKey, "Invalid extended public key" unless payload&.bytesize == 78 && VERSIONS.include?(payload[0, 4].unpack1("H*"))+ # Hardened account node: BIP84 m/84'/0'/n' (depth 3) or Electrum's segwit m/0' (depth 1).+ depth, child = payload.getbyte(4), payload[9, 4].unpack1("N")+ raise InvalidKey, "Use an account-level extended public key" unless depth == 3 ? child >= 0x80000000 : depth == 1 && child == 0x80000000++ @chain_code = payload[13, 32]+ @pub = payload[45, 33]+ OpenSSL::PKey::EC::Point.new(CURVE, @pub) # rejects private keys and off-curve points+ rescue StandardError => error+ raise InvalidKey, "Invalid extended public key" unless error.is_a?(InvalidKey)+ raise+ end++ # Derive a Native SegWit address on receive (0) or change (1), allowing only+ # non-hardened child indices obtainable from an account public key.+ def address(branch, index)+ raise InvalidKey, "Invalid derivation branch" unless [ 0, 1 ].include?(branch)+ raise InvalidKey, "Invalid address index" unless index.between?(0, 0x7fffffff)++ @branches ||= {}+ child, = derive(*(@branches[branch] ||= derive(@pub, @chain_code, branch)), index)+ segwit = Bech32::SegwitAddr.new+ segwit.ver = 0+ segwit.prog = OpenSSL::Digest.digest("RIPEMD160", OpenSSL::Digest.digest("SHA256", child)).bytes+ segwit.addr+ end++ # Identify public key material independently of its xpub/zpub version bytes,+ # so equivalent encodings cannot create duplicate sources. The key is hashed+ # as hex and the chain code as bytes, matching fingerprints already stored+ # by the #3753 preview.+ def fingerprint+ Digest::SHA256.hexdigest(@pub.unpack1("H*") + @chain_code)+ end++ # Validate the checksum and a standard mainnet output (P2PKH, P2SH, P2WPKH,+ # P2WSH, P2TR); malformed addresses and other networks return false.+ def self.valid_address?(value)+ text = value.to_s+ return false unless text.length.between?(26, 90)++ if text.match?(/\Abc1/i)+ segwit = Bech32::SegwitAddr.new(text)+ segwit.hrp == "bc" && (segwit.ver.zero? ? [ 20, 32 ].include?(segwit.prog.size) : segwit.ver == 1 && segwit.prog.size == 32)+ else+ payload = base58check_decode(text)+ payload&.bytesize == 21 && [ 0x00, 0x05 ].include?(payload.getbyte(0))+ end+ rescue StandardError+ false+ end++ # Trim input and normalize uniformly cased Bech32 addresses. Keep mixed case+ # unchanged so checksum validation rejects it rather than silently repairing it.+ def self.canonical_address(value)+ text = value.to_s.strip+ text.start_with?("BC1") && text == text.upcase ? text.downcase : text+ end++ # Decode Base58Check, returning nil when the checksum does not match.+ def self.base58check_decode(text)+ number = text.each_char.reduce(0) { |sum, char| sum * 58 + (BASE58.index(char) || raise(ArgumentError, "Invalid Base58")) }+ hex = number.zero? ? "" : number.to_s(16)+ bytes = ("\x00" * text[/\A1*/].size + [ hex.rjust(hex.size + hex.size % 2, "0") ].pack("H*")).b+ payload = bytes[0...-4]+ payload if bytes.bytesize > 4 && bytes[-4..] == OpenSSL::Digest.digest("SHA256", OpenSSL::Digest.digest("SHA256", payload))[0, 4]+ end++ private+ # BIP32 public child derivation (CKDpub) for a non-hardened index.+ def derive(pub, chain_code, index)+ digest = OpenSSL::HMAC.digest("SHA512", chain_code, pub + [ index ].pack("N"))+ tweak = OpenSSL::BN.new(digest[0, 32], 2)+ raise InvalidKey, "Invalid derived key" if tweak >= CURVE.order++ point = CURVE.generator.mul(tweak).add(OpenSSL::PKey::EC::Point.new(CURVE, pub))+ raise InvalidKey, "Invalid derived key" if point.infinity?++ [ point.to_octet_string(:compressed), digest[32, 32] ]+ end+ end+enddiff --git a/test/models/onchain/bitcoin_adapter_test.rb b/test/models/onchain/bitcoin_adapter_test.rbindex aa74d37b75..4637cb7d60 100644--- a/test/models/onchain/bitcoin_adapter_test.rb+++ b/test/models/onchain/bitcoin_adapter_test.rb@@ -25,6 +25,7 @@ class Onchain::BitcoinAdapterTest < ActiveSupport::TestCase"not-an-address","1A1zP1eP5QGefi2DMPTfTL5SLmv7Divf0a", # Base58 excludes 0"bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdb", # bech32 excludes b+ "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdz", # last character mistyped: checksum fails"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", # an EVM address"xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz"].each do |address|diff --git a/test/models/onchain/bitcoin_public_key_test.rb b/test/models/onchain/bitcoin_public_key_test.rbnew file mode 100644index 0000000000..b90a58dec5--- /dev/null+++ b/test/models/onchain/bitcoin_public_key_test.rb@@ -0,0 +1,96 @@+require "test_helper"++class Onchain::BitcoinPublicKeyTest < ActiveSupport::TestCase+ # Public BIP84 test vectors (BIP84 spec), never a user's keys.+ ZPUB = "zpub6rFR7y4Q2AijBEqTUquhVz398htDFrtymD9xYYfG1m4wAcvPhXNfE3EfH1r1ADqtfSdVCToUG868RvUUkgDKf31mGDtKsAYz2oz2AGutZYs"+ RECEIVE = "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"+ SECOND = "bc1qnjg0jd8228aq7egyzacy8cys3knf9xvrerkf9g"+ CHANGE = "bc1q8c6fshw2dlwun7ekn9qwf37cu2rn755upcp6el"++ # The same BIP84 test account key with xpub version bytes instead of zpub.+ XPUB = "xpub6CatWdiZiodmUeTDp8LT5or8nmbKNcuyvz7WyksVFkKB4RHwCD3XyuvPEbvqAQY3rAPshWcMLoP2fMFMKHPJ4ZeZXYVUhLv1VMrjPC7PW6V"++ test "derives official BIP84 receive and change addresses" do+ key = Onchain::BitcoinPublicKey.new(ZPUB)+ assert_equal RECEIVE, key.address(0, 0)+ assert_equal SECOND, key.address(0, 1)+ assert_equal CHANGE, key.address(1, 0)+ end++ test "derives only receive and change branches at non-hardened indices" do+ # An account public key cannot derive hardened children; 0x80000000 would be one.+ key = Onchain::BitcoinPublicKey.new(ZPUB)+ [ [ 2, 0 ], [ 0, -1 ], [ 0, 0x80000000 ] ].each do |branch, index|+ assert_raises(Onchain::BitcoinPublicKey::InvalidKey) { key.address(branch, index) }+ end+ end++ test "derives the official BIP32 public child" do+ # Test vector 1: m/0H/1/2H and its non-hardened child m/0H/1/2H/2.+ key = Onchain::BitcoinPublicKey.new("xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5")+ pub, chain_code = key.send(:derive, key.instance_variable_get(:@pub), key.instance_variable_get(:@chain_code), 2)+ assert_equal "02e8445082a72f29b75ca48748a914df60622a609cacfce8ed0e35804560741d29", pub.unpack1("H*")+ assert_equal "cfb71883f01676f587d023cc53a35bc7f88f724b1f8c2892ac1275ac822a3edd", chain_code.unpack1("H*")+ end++ test "xpub and zpub versions identify the same source" do+ plain = Onchain::BitcoinPublicKey.new(XPUB)+ assert_equal RECEIVE, plain.address(0, 0)+ assert_equal Onchain::BitcoinPublicKey.new(ZPUB).fingerprint, plain.fingerprint+ end++ test "fingerprints stay compatible with stored sources" do+ assert_equal "e9c5945c1ed8fb33780fc09caf0a79b8852eed6df035db9e04c340dacce83d97", Onchain::BitcoinPublicKey.new(ZPUB).fingerprint+ end++ test "rejects private keys unsupported networks and corrupt checksums" do+ %w[xprv123 zprv123 tpub123 seed].each do |value|+ assert_raises(Onchain::BitcoinPublicKey::InvalidKey) { Onchain::BitcoinPublicKey.new(value) }+ end+ assert_raises(Onchain::BitcoinPublicKey::InvalidKey) { Onchain::BitcoinPublicKey.new(ZPUB.chop + "a") }+ end++ test "accepts only hardened account-level keys" do+ # BIP32 test vectors: m/0H is the depth-1 node Electrum segwit seeds export;+ # the master key (depth 0), non-hardened m/0 and a BIP84 purpose node m/84H+ # (the m/0H vector with its child number changed) are not accounts.+ assert Onchain::BitcoinPublicKey.new("xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw").address(0, 0).start_with?("bc1q")+ %w[+ xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8+ xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH+ xpub68Gmy5Edvgif6b9GUbbRxC2yTApQqvEp4tR6sWsV64xvZHvxaK2K6L3RrMXA2Ez3ksVVecgaCJVKdJH2adWJWoXdBCzrHhqxf1B8KqK6TZG+ ].each do |value|+ error = assert_raises(Onchain::BitcoinPublicKey::InvalidKey) { Onchain::BitcoinPublicKey.new(value) }+ assert_equal "Use an account-level extended public key", error.message+ end+ end++ test "validates Bitcoin addresses using their checksum" do+ assert Onchain::BitcoinPublicKey.valid_address?(RECEIVE)+ refute Onchain::BitcoinPublicKey.valid_address?(RECEIVE.chop + "a")+ refute Onchain::BitcoinPublicKey.valid_address?("tb1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu")+ end++ test "canonicalizes only uniformly cased Bech32 addresses" do+ assert_equal RECEIVE, Onchain::BitcoinPublicKey.canonical_address(" #{RECEIVE.upcase} ")+ # BIP173: mixed case is invalid, so it is kept for validation to reject, not repaired.+ mixed = RECEIVE.sub("bc1q", "bc1Q")+ assert_equal mixed, Onchain::BitcoinPublicKey.canonical_address(mixed)+ refute Onchain::BitcoinPublicKey.valid_address?(mixed)+ end++ test "accepts every standard mainnet output type and nothing else" do+ %w[+ 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2+ 3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy+ bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3+ bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr+ ].each { |address| assert Onchain::BitcoinPublicKey.valid_address?(address), address }++ %w[+ 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN3+ mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn+ bc1qcr8te4kr609gcawutmrza0j4xv80jy8z3hvhsj+ ].each { |address| refute Onchain::BitcoinPublicKey.valid_address?(address), address }+ end+end