Skip to main content

bsv/primitives/
public_key.rs

1//! Public key type derived from a secp256k1 private key.
2//!
3//! PublicKey wraps a Point on the secp256k1 curve and provides
4//! DER encoding/decoding, address derivation, and signature
5//! verification. Mirrors the TS SDK PublicKey.ts API.
6
7use crate::primitives::base_point::BasePoint;
8use crate::primitives::big_number::{BigNumber, Endian};
9use crate::primitives::ecdsa::ecdsa_verify;
10use crate::primitives::error::PrimitivesError;
11use crate::primitives::hash::{hash160, sha256, sha256_hmac};
12use crate::primitives::point::Point;
13use crate::primitives::private_key::PrivateKey;
14use crate::primitives::signature::Signature;
15use crate::primitives::utils::{base58_check_encode, from_hex, to_hex};
16
17/// A secp256k1 public key (a point on the curve).
18///
19/// Uses composition with Point, following Rust conventions.
20/// The TS SDK uses class inheritance (PublicKey extends Point);
21/// we mirror the public API names.
22#[derive(Clone, Debug)]
23pub struct PublicKey {
24    point: Point,
25}
26
27impl PublicKey {
28    /// Create a PublicKey from a Point.
29    pub fn from_point(point: Point) -> Self {
30        PublicKey { point }
31    }
32
33    /// Derive a public key from a private key.
34    pub fn from_private_key(key: &crate::primitives::private_key::PrivateKey) -> Self {
35        key.to_public_key()
36    }
37
38    /// Parse a public key from a hex string (compressed or uncompressed DER).
39    ///
40    /// Compressed: 33 bytes (66 hex chars), starts with 02 or 03
41    /// Uncompressed: 65 bytes (130 hex chars), starts with 04
42    pub fn from_string(s: &str) -> Result<Self, PrimitivesError> {
43        let bytes = from_hex(s)?;
44        Self::from_der_bytes(&bytes)
45    }
46
47    /// Parse a public key from DER-encoded bytes.
48    pub fn from_der_bytes(bytes: &[u8]) -> Result<Self, PrimitivesError> {
49        if bytes.is_empty() {
50            return Err(PrimitivesError::InvalidPublicKey(
51                "empty public key data".to_string(),
52            ));
53        }
54
55        match bytes[0] {
56            0x02 | 0x03 => {
57                // Compressed: prefix(1) + x(32) = 33 bytes
58                if bytes.len() != 33 {
59                    return Err(PrimitivesError::InvalidPublicKey(format!(
60                        "compressed key should be 33 bytes, got {}",
61                        bytes.len()
62                    )));
63                }
64                let odd = bytes[0] == 0x03;
65                let x = BigNumber::from_bytes(&bytes[1..], Endian::Big);
66                let point = Point::from_x(&x, odd)?;
67                Ok(PublicKey { point })
68            }
69            0x04 => {
70                // Uncompressed: prefix(1) + x(32) + y(32) = 65 bytes
71                if bytes.len() != 65 {
72                    return Err(PrimitivesError::InvalidPublicKey(format!(
73                        "uncompressed key should be 65 bytes, got {}",
74                        bytes.len()
75                    )));
76                }
77                let x = BigNumber::from_bytes(&bytes[1..33], Endian::Big);
78                let y = BigNumber::from_bytes(&bytes[33..], Endian::Big);
79                let point = Point::new(x, y);
80
81                if !point.validate() {
82                    return Err(PrimitivesError::InvalidPublicKey(
83                        "point not on curve".to_string(),
84                    ));
85                }
86
87                Ok(PublicKey { point })
88            }
89            prefix => Err(PrimitivesError::InvalidPublicKey(format!(
90                "unknown prefix byte: 0x{prefix:02x}"
91            ))),
92        }
93    }
94
95    /// Encode the public key in compressed DER format (33 bytes).
96    ///
97    /// Format: prefix(1) || x(32)
98    /// prefix = 0x02 if y is even, 0x03 if y is odd
99    pub fn to_der(&self) -> Vec<u8> {
100        self.point.to_der(true)
101    }
102
103    /// Encode the public key in compressed DER format as a hex string.
104    pub fn to_der_hex(&self) -> String {
105        to_hex(&self.to_der())
106    }
107
108    /// Encode the public key in uncompressed DER format (65 bytes).
109    ///
110    /// Format: 0x04 || x(32) || y(32)
111    pub fn to_der_uncompressed(&self) -> Vec<u8> {
112        self.point.to_der(false)
113    }
114
115    /// Hash the compressed public key with hash160 (RIPEMD-160(SHA-256)).
116    ///
117    /// Returns 20 bytes -- the public key hash used in P2PKH addresses.
118    pub fn to_hash(&self) -> Vec<u8> {
119        let der = self.to_der();
120        hash160(&der).to_vec()
121    }
122
123    /// Derive a P2PKH Bitcoin address from this public key.
124    ///
125    /// Format: Base58Check(prefix || hash160(compressed_der))
126    /// Default prefix `[0x00]` for mainnet.
127    pub fn to_address(&self, prefix: &[u8]) -> String {
128        let pkh = self.to_hash();
129        base58_check_encode(&pkh, prefix)
130    }
131
132    /// Verify a message signature using this public key.
133    ///
134    /// The message is hashed with SHA-256 before verification.
135    pub fn verify(&self, message: &[u8], signature: &Signature) -> bool {
136        let msg_hash = sha256(message);
137        ecdsa_verify(&msg_hash, signature, &self.point)
138    }
139
140    /// Compute ECDH shared secret: private_key.bn * self.point.
141    ///
142    /// Returns the resulting point on the curve.
143    pub fn derive_shared_secret(&self, private_key: &PrivateKey) -> Result<Point, PrimitivesError> {
144        private_key.derive_shared_secret(self)
145    }
146
147    /// Derive a child public key using Type-42 key derivation (BRC-42).
148    ///
149    /// Computes: child_point = self.point + G * HMAC-SHA256(shared_secret_compressed, invoice_number)
150    /// where shared_secret = private_key * self.
151    pub fn derive_child(
152        &self,
153        private_key: &PrivateKey,
154        invoice_number: &str,
155    ) -> Result<PublicKey, PrimitivesError> {
156        let shared_secret = private_key.derive_shared_secret(self)?;
157        self.derive_child_with_secret(&shared_secret, invoice_number)
158    }
159
160    /// Derive a child public key from a *precomputed* ECDH shared secret.
161    ///
162    /// The per-counterparty ECDH point-multiply (`private_key * self`) is the
163    /// caller's responsibility and is passed in as `shared_secret`; it does NOT
164    /// depend on `invoice_number`, so it can be cached and reused across
165    /// messages. Note this method still performs ONE per-message point-multiply
166    /// (`hmac * G`) and a point-add, which are NOT cacheable because the HMAC
167    /// embeds the per-message nonce via `invoice_number`. Output is
168    /// bit-identical to [`derive_child`] for the same inputs.
169    pub fn derive_child_with_secret(
170        &self,
171        shared_secret: &Point,
172        invoice_number: &str,
173    ) -> Result<PublicKey, PrimitivesError> {
174        let shared_secret_bytes = shared_secret.to_der(true); // 33-byte compressed
175        let hmac_result = sha256_hmac(&shared_secret_bytes, invoice_number.as_bytes());
176        let hmac_bn = BigNumber::from_bytes(&hmac_result, Endian::Big);
177        let base_point = BasePoint::instance();
178        let offset_point = base_point.mul(&hmac_bn);
179        let child_point = self.point.add(&offset_point);
180
181        Ok(PublicKey::from_point(child_point))
182    }
183
184    /// Access the underlying Point.
185    pub fn point(&self) -> &Point {
186        &self.point
187    }
188}
189
190impl PartialEq for PublicKey {
191    fn eq(&self, other: &Self) -> bool {
192        self.point.eq(&other.point)
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::primitives::private_key::PrivateKey;
200
201    // -----------------------------------------------------------------------
202    // PublicKey: from_private_key
203    // -----------------------------------------------------------------------
204
205    #[test]
206    fn test_public_key_from_private_key() {
207        let priv_key = PrivateKey::from_hex("1").unwrap();
208        let pub_key = PublicKey::from_private_key(&priv_key);
209
210        // G point compressed
211        assert_eq!(
212            pub_key.to_der_hex(),
213            "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
214        );
215    }
216
217    // -----------------------------------------------------------------------
218    // PublicKey: from_string (compressed and uncompressed)
219    // -----------------------------------------------------------------------
220
221    #[test]
222    fn test_public_key_from_string_compressed() {
223        let hex = "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
224        let pub_key = PublicKey::from_string(hex).unwrap();
225        assert_eq!(pub_key.to_der_hex(), hex);
226    }
227
228    #[test]
229    fn test_public_key_from_string_uncompressed() {
230        let hex = "0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8";
231        let pub_key = PublicKey::from_string(hex).unwrap();
232        // Should produce the same compressed key
233        assert_eq!(
234            pub_key.to_der_hex(),
235            "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
236        );
237    }
238
239    // -----------------------------------------------------------------------
240    // PublicKey: DER compression roundtrip
241    // -----------------------------------------------------------------------
242
243    #[test]
244    fn test_public_key_der_roundtrip() {
245        let priv_key = PrivateKey::from_hex("ff").unwrap();
246        let pub_key = PublicKey::from_private_key(&priv_key);
247
248        let der_hex = pub_key.to_der_hex();
249        let recovered = PublicKey::from_string(&der_hex).unwrap();
250        assert_eq!(pub_key, recovered, "DER compression roundtrip should work");
251    }
252
253    // -----------------------------------------------------------------------
254    // PublicKey: to_hash
255    // -----------------------------------------------------------------------
256
257    #[test]
258    fn test_public_key_to_hash() {
259        let priv_key = PrivateKey::from_hex("1").unwrap();
260        let pub_key = PublicKey::from_private_key(&priv_key);
261        let hash = pub_key.to_hash();
262        assert_eq!(hash.len(), 20, "hash160 should be 20 bytes");
263    }
264
265    // -----------------------------------------------------------------------
266    // PublicKey: to_address
267    // -----------------------------------------------------------------------
268
269    #[test]
270    fn test_public_key_to_address_mainnet() {
271        // Key = 1 -> G -> known address
272        let priv_key = PrivateKey::from_hex("1").unwrap();
273        let pub_key = PublicKey::from_private_key(&priv_key);
274        let address = pub_key.to_address(&[0x00]);
275        assert_eq!(address, "1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH");
276    }
277
278    // -----------------------------------------------------------------------
279    // PublicKey: verify
280    // -----------------------------------------------------------------------
281
282    #[test]
283    fn test_public_key_verify() {
284        let priv_key = PrivateKey::from_hex("1").unwrap();
285        let pub_key = PublicKey::from_private_key(&priv_key);
286        let sig = priv_key.sign(b"test verify", true).unwrap();
287
288        assert!(
289            pub_key.verify(b"test verify", &sig),
290            "Should verify valid signature"
291        );
292        assert!(
293            !pub_key.verify(b"wrong message", &sig),
294            "Should reject wrong message"
295        );
296    }
297
298    // -----------------------------------------------------------------------
299    // PublicKey: uncompressed encoding
300    // -----------------------------------------------------------------------
301
302    #[test]
303    fn test_public_key_uncompressed() {
304        let priv_key = PrivateKey::from_hex("1").unwrap();
305        let pub_key = PublicKey::from_private_key(&priv_key);
306        let uncompressed = pub_key.to_der_uncompressed();
307        assert_eq!(uncompressed.len(), 65);
308        assert_eq!(uncompressed[0], 0x04);
309    }
310
311    // -----------------------------------------------------------------------
312    // PublicKey: test vectors from JSON
313    // -----------------------------------------------------------------------
314
315    #[test]
316    fn test_public_key_der_vectors() {
317        use serde::Deserialize;
318
319        #[derive(Deserialize)]
320        struct DerVector {
321            private_key_hex: String,
322            public_key_compressed: String,
323            public_key_uncompressed: String,
324            address_mainnet: String,
325            #[allow(dead_code)]
326            address_prefix: String,
327            #[allow(dead_code)]
328            description: String,
329        }
330
331        let data = include_str!("../../test-vectors/public_key_der.json");
332        let vectors: Vec<DerVector> = serde_json::from_str(data).unwrap();
333
334        for (i, v) in vectors.iter().enumerate() {
335            let priv_key = PrivateKey::from_hex(&v.private_key_hex).unwrap();
336            let pub_key = PublicKey::from_private_key(&priv_key);
337
338            // Compressed DER
339            assert_eq!(
340                pub_key.to_der_hex(),
341                v.public_key_compressed,
342                "Vector {i}: compressed mismatch"
343            );
344
345            // Uncompressed DER
346            let uncompressed_hex = to_hex(&pub_key.to_der_uncompressed());
347            assert_eq!(
348                uncompressed_hex, v.public_key_uncompressed,
349                "Vector {i}: uncompressed mismatch"
350            );
351
352            // Address
353            let address = pub_key.to_address(&[0x00]);
354            assert_eq!(address, v.address_mainnet, "Vector {i}: address mismatch");
355        }
356    }
357
358    // -----------------------------------------------------------------------
359    // PublicKey: sign then verify roundtrip with multiple keys
360    // -----------------------------------------------------------------------
361
362    #[test]
363    fn test_sign_verify_roundtrip_multiple_keys() {
364        for i in 1..=5 {
365            let priv_key = PrivateKey::from_hex(&format!("{:064x}", i * 1000)).unwrap();
366            let pub_key = PublicKey::from_private_key(&priv_key);
367            let msg = format!("Message number {i}");
368
369            let sig = priv_key.sign(msg.as_bytes(), true).unwrap();
370            assert!(
371                pub_key.verify(msg.as_bytes(), &sig),
372                "Key {i} should verify"
373            );
374        }
375    }
376}