bsv/primitives/
public_key.rs1use 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#[derive(Clone, Debug)]
23pub struct PublicKey {
24 point: Point,
25}
26
27impl PublicKey {
28 pub fn from_point(point: Point) -> Self {
30 PublicKey { point }
31 }
32
33 pub fn from_private_key(key: &crate::primitives::private_key::PrivateKey) -> Self {
35 key.to_public_key()
36 }
37
38 pub fn from_string(s: &str) -> Result<Self, PrimitivesError> {
43 let bytes = from_hex(s)?;
44 Self::from_der_bytes(&bytes)
45 }
46
47 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 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 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 pub fn to_der(&self) -> Vec<u8> {
100 self.point.to_der(true)
101 }
102
103 pub fn to_der_hex(&self) -> String {
105 to_hex(&self.to_der())
106 }
107
108 pub fn to_der_uncompressed(&self) -> Vec<u8> {
112 self.point.to_der(false)
113 }
114
115 pub fn to_hash(&self) -> Vec<u8> {
119 let der = self.to_der();
120 hash160(&der).to_vec()
121 }
122
123 pub fn to_address(&self, prefix: &[u8]) -> String {
128 let pkh = self.to_hash();
129 base58_check_encode(&pkh, prefix)
130 }
131
132 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 pub fn derive_shared_secret(&self, private_key: &PrivateKey) -> Result<Point, PrimitivesError> {
144 private_key.derive_shared_secret(self)
145 }
146
147 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 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); 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 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 #[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 assert_eq!(
212 pub_key.to_der_hex(),
213 "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
214 );
215 }
216
217 #[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 assert_eq!(
234 pub_key.to_der_hex(),
235 "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
236 );
237 }
238
239 #[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 #[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 #[test]
270 fn test_public_key_to_address_mainnet() {
271 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 #[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 #[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 #[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 assert_eq!(
340 pub_key.to_der_hex(),
341 v.public_key_compressed,
342 "Vector {i}: compressed mismatch"
343 );
344
345 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 let address = pub_key.to_address(&[0x00]);
354 assert_eq!(address, v.address_mainnet, "Vector {i}: address mismatch");
355 }
356 }
357
358 #[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}