@nuggetslife/vc 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Cargo.toml CHANGED
@@ -10,6 +10,7 @@ crate-type = ["cdylib"]
10
10
  # Default enable napi4 feature, see https://nodejs.org/api/n-api.html#node-api-version-matrix
11
11
  base64 = "0.22.1"
12
12
  bs58 = "0.5.1"
13
+ hex = "0.4.3"
13
14
  # Default enable napi4 feature, see https://nodejs.org/api/n-api.html#node-api-version-matrix
14
15
  napi = { version = "2.12.2", default-features = false, features = ["napi4", "tokio_rt"] }
15
16
  napi-derive = "2.12.2"
package/index.d.ts CHANGED
@@ -15,6 +15,14 @@ export interface JwkKeyPairOptions {
15
15
  privateKeyJwk?: JsonWebKey
16
16
  publicKeyJwk?: JsonWebKey
17
17
  }
18
+ export interface FingerPrintFromPublicKeyOptions {
19
+ publicKeyBase58: string
20
+ }
21
+ export interface KeyPairFromFingerPrintOptions {
22
+ id?: string
23
+ controller?: string
24
+ fingerprint: string
25
+ }
18
26
  export interface JsonWebKey {
19
27
  /**
20
28
  * Indicates the key type used
@@ -89,17 +97,25 @@ export interface KeyPairVerifierOptions {
89
97
  export class Bls12381G2KeyPair {
90
98
  id?: string
91
99
  controller?: string
92
- privateKeyBuffer?: Array<number>
93
- publicKeyBuffer?: Array<number>
100
+ privateKeyInner?: Array<number>
101
+ publicKeyInner?: Array<number>
94
102
  type: string
95
103
  constructor(options?: KeyPairOptions | undefined | null)
96
104
  static generate(options?: GenerateKeyPairOptions | undefined | null): Promise<Bls12381G2KeyPair>
97
105
  static from(options: KeyPairOptions): Promise<Bls12381G2KeyPair>
98
106
  static fromJwk(options: JwkKeyPairOptions): Promise<Bls12381G2KeyPair>
107
+ static fromFingerprint(options: KeyPairFromFingerPrintOptions): Promise<Bls12381G2KeyPair>
99
108
  get publicKey(): string | null
109
+ get publicKeyBuffer(): Buffer
110
+ get privateKeyBuffer(): Buffer
111
+ publicKeyJwk(): JsonWebKey
100
112
  get privateKey(): string | null
113
+ privateKeyJwk(): JsonWebKey
101
114
  signer(): KeyPairSigner
102
115
  verifier(): KeyPairVerifier
116
+ fingerprint(): string
117
+ static fingerprintFromPublicKey(options: FingerPrintFromPublicKeyOptions): string
118
+ verifyFingerprint(fingerprint: string): void
103
119
  }
104
120
  export class KeyPairSigner {
105
121
  sign(options: KeyPairSignerOptions): Promise<Uint8Array>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuggetslife/vc",
3
- "version": "0.0.7",
3
+ "version": "0.0.9",
4
4
  "main": "index.js",
5
5
  "types": "index.d.ts",
6
6
  "napi": {
@@ -38,6 +38,6 @@
38
38
  },
39
39
  "packageManager": "yarn@4.3.1",
40
40
  "optionalDependencies": {
41
- "@nuggetslife/vc-darwin-arm64": "0.0.7"
41
+ "@nuggetslife/vc-darwin-arm64": "0.0.9"
42
42
  }
43
43
  }
package/src/lib.rs CHANGED
@@ -3,12 +3,19 @@
3
3
  #[macro_use]
4
4
  extern crate napi_derive;
5
5
 
6
- use base64::{engine::general_purpose::URL_SAFE, Engine as _};
6
+ use base64::{
7
+ engine::general_purpose::URL_SAFE, engine::general_purpose::URL_SAFE_NO_PAD, Engine as _,
8
+ };
7
9
  use napi::bindgen_prelude::*;
8
- use types::{Bls12381G2KeyPair, GenerateKeyPairOptions, JwkKeyPairOptions, KeyPairOptions};
10
+ use types::{
11
+ Bls12381G2KeyPair, BlsCurveName, FingerPrintFromPublicKeyOptions, GenerateKeyPairOptions,
12
+ JsonWebKey, JwkKeyPairOptions, JwkKty, KeyPairFromFingerPrintOptions, KeyPairOptions,
13
+ };
9
14
  use validators::{assert_bls_12381_g2_private_jwk, assert_bls_12381_g2_public_jwk};
10
15
  use vc::bbs_signatures::bls12381::{
11
16
  bls_generate_g2_key, bls_sign, bls_verify, BlsBbsSignRequest, BlsBbsVerifyRequest, BlsKeyPair,
17
+ BLS12381G2_MULTICODEC_IDENTIFIER, DEFAULT_BLS12381_G2_PUBLIC_KEY_LENGTH,
18
+ MULTIBASE_ENCODED_BASE58_IDENTIFIER, VARIABLE_INTEGER_TRAILING_BYTE,
12
19
  };
13
20
 
14
21
  pub mod types;
@@ -45,26 +52,26 @@ impl Bls12381G2KeyPair {
45
52
  // }
46
53
  // };
47
54
 
48
- let private_key_buffer = o
55
+ let private_key_inner = o
49
56
  .private_key_base58
50
57
  .map(|v| bs58::decode(v).into_vec().unwrap());
51
- let public_key_buffer = o
58
+ let public_key_inner = o
52
59
  .public_key_base58
53
60
  .map(|v| bs58::decode(v).into_vec().unwrap());
54
61
 
55
62
  Self {
56
63
  id: o.id,
57
64
  controller: o.controller,
58
- private_key_buffer,
59
- public_key_buffer,
65
+ private_key_inner,
66
+ public_key_inner,
60
67
  type_: String::from("Bls12381G2Key2020"),
61
68
  }
62
69
  }
63
70
  None => Self {
64
71
  id: None,
65
72
  controller: None,
66
- private_key_buffer: None,
67
- public_key_buffer: None,
73
+ private_key_inner: None,
74
+ public_key_inner: None,
68
75
  type_: String::from("Bls12381G2Key2020"),
69
76
  },
70
77
  }
@@ -151,30 +158,239 @@ impl Bls12381G2KeyPair {
151
158
  }
152
159
  }
153
160
 
161
+ #[napi(factory)]
162
+ pub async fn from_fingerprint(
163
+ options: KeyPairFromFingerPrintOptions,
164
+ ) -> Result<Bls12381G2KeyPair> {
165
+ let KeyPairFromFingerPrintOptions {
166
+ id,
167
+ controller,
168
+ fingerprint,
169
+ } = options;
170
+ let mut chars = fingerprint.chars();
171
+ let head = chars
172
+ .next()
173
+ .ok_or(napi::Error::from_reason("fingerprint string is empty"))?
174
+ .to_string();
175
+
176
+ if head != MULTIBASE_ENCODED_BASE58_IDENTIFIER {
177
+ return Err(napi::Error::from_reason(
178
+ format!("Unsupported fingerprint type: expected first character to be `z` indicating base58 encoding, received {head}")
179
+ ));
180
+ };
181
+
182
+ let rest = chars.collect::<String>();
183
+ let buffer = bs58::decode(rest).into_vec().map_err(|err| {
184
+ napi::Error::from_reason(format!(
185
+ "failed to decode bs58 fingerprint to bytes. error: {err}"
186
+ ))
187
+ })?;
188
+
189
+ if buffer.len() != BLS12381G2_MULTICODEC_IDENTIFIER as usize {
190
+ return Err(napi::Error::from_reason(
191
+ format!("Unsupported public key length: expected `${DEFAULT_BLS12381_G2_PUBLIC_KEY_LENGTH}` received {}", buffer.len())
192
+ ));
193
+ }
194
+
195
+ if buffer[0] != DEFAULT_BLS12381_G2_PUBLIC_KEY_LENGTH {
196
+ return Err(napi::Error::from_reason(
197
+ format!("Unsupported public key identifier: expected second character to be {BLS12381G2_MULTICODEC_IDENTIFIER} indicating BLS12381G2 key pair, received {}", buffer[0])
198
+ ));
199
+ }
200
+
201
+ if buffer[1] != VARIABLE_INTEGER_TRAILING_BYTE {
202
+ return Err(napi::Error::from_reason(
203
+ format!("Missing variable integer trailing byte: expected third character to be {BLS12381G2_MULTICODEC_IDENTIFIER} indicating BLS12381G2 key pair, received {}", buffer[1])
204
+ ));
205
+ }
206
+
207
+ let pubkey_base58 = bs58::encode(buffer).into_string();
208
+ let opts = FingerPrintFromPublicKeyOptions {
209
+ public_key_base58: pubkey_base58.clone(),
210
+ };
211
+ let fingerprint = Bls12381G2KeyPair::fingerprint_from_public_key(opts).map_err(|err| {
212
+ napi::Error::from_reason(format!("fingerprint_from_public_key failed. error: {err}"))
213
+ })?;
214
+ let mapped_controller = match controller {
215
+ Some(v) => v,
216
+ None => {
217
+ format!("did:key:{fingerprint}",)
218
+ }
219
+ };
220
+
221
+ let mapped_id = match id {
222
+ Some(v) => v,
223
+ None => {
224
+ format!("#{fingerprint}",)
225
+ }
226
+ };
227
+
228
+ let kp = Bls12381G2KeyPair::new(Some(KeyPairOptions {
229
+ id: Some(mapped_id),
230
+ controller: Some(mapped_controller),
231
+ public_key_base58: Some(pubkey_base58),
232
+ private_key_base58: None,
233
+ }))
234
+ .await;
235
+
236
+ Ok(kp)
237
+ }
238
+
154
239
  #[napi(getter)]
155
240
  pub fn public_key(&self) -> Option<String> {
156
241
  self
157
- .public_key_buffer
242
+ .public_key_inner
158
243
  .clone()
159
244
  .map(|b| bs58::encode(b).into_string())
160
245
  }
161
246
 
247
+ #[napi(getter)]
248
+ pub fn public_key_buffer(&self) -> Buffer {
249
+ self.public_key_inner.clone().unwrap().into()
250
+ }
251
+
252
+ #[napi(getter)]
253
+ pub fn private_key_buffer(&self) -> Buffer {
254
+ self.private_key_inner.clone().unwrap().into()
255
+ }
256
+
257
+ #[napi]
258
+ pub fn public_key_jwk(&self) -> Result<JsonWebKey> {
259
+ let Some(ref public_key_inner) = self.public_key_inner else {
260
+ return Err(napi::Error::from_reason("no public_key_inner"));
261
+ };
262
+
263
+ Ok(JsonWebKey {
264
+ kid: self.id.to_owned(),
265
+ kty: JwkKty::EC.into(),
266
+ crv: BlsCurveName::G2.into(),
267
+ x: URL_SAFE_NO_PAD.encode(public_key_inner),
268
+ use_: None,
269
+ key_ops: None,
270
+ alg: None,
271
+ d: None,
272
+ y: None,
273
+ ext: None,
274
+ })
275
+ }
276
+
162
277
  #[napi(getter)]
163
278
  pub fn private_key(&self) -> Option<String> {
164
279
  self
165
- .private_key_buffer
280
+ .private_key_inner
166
281
  .clone()
167
282
  .map(|b| bs58::encode(b).into_string())
168
283
  }
169
284
 
285
+ #[napi]
286
+ pub fn private_key_jwk(&self) -> Result<JsonWebKey> {
287
+ let Some(ref public_key_inner) = self.public_key_inner else {
288
+ return Err(napi::Error::from_reason("no public_key_inner"));
289
+ };
290
+
291
+ let Some(ref private_key_inner) = self.private_key_inner else {
292
+ return Err(napi::Error::from_reason("no private_key_inner"));
293
+ };
294
+
295
+ Ok(JsonWebKey {
296
+ kid: self.id.to_owned(),
297
+ kty: JwkKty::EC.into(),
298
+ crv: BlsCurveName::G2.into(),
299
+ x: URL_SAFE_NO_PAD.encode(public_key_inner),
300
+ d: Some(URL_SAFE_NO_PAD.encode(private_key_inner)),
301
+ use_: None,
302
+ key_ops: None,
303
+ alg: None,
304
+ y: None,
305
+ ext: None,
306
+ })
307
+ }
308
+
170
309
  #[napi]
171
310
  pub fn signer(&self) -> KeyPairSigner {
172
311
  KeyPairSigner { key: self.clone() }
173
312
  }
313
+
174
314
  #[napi]
175
315
  pub fn verifier(&self) -> KeyPairVerifier {
176
316
  KeyPairVerifier { key: self.clone() }
177
317
  }
318
+
319
+ #[napi]
320
+ pub fn fingerprint(&self) -> Result<String> {
321
+ let Some(public_key_base58) = self.public_key() else {
322
+ return Err(napi::Error::from_reason("no public key"));
323
+ };
324
+ Bls12381G2KeyPair::fingerprint_from_public_key(FingerPrintFromPublicKeyOptions {
325
+ public_key_base58,
326
+ })
327
+ }
328
+
329
+ #[napi]
330
+ pub fn fingerprint_from_public_key(options: FingerPrintFromPublicKeyOptions) -> Result<String> {
331
+ let FingerPrintFromPublicKeyOptions { public_key_base58 } = options;
332
+ let mut key_bytes = bs58::decode(public_key_base58).into_vec().map_err(|err| {
333
+ napi::Error::from_reason(format!(
334
+ "failed to decode public_key_base58 value. error: {err}"
335
+ ))
336
+ })?;
337
+
338
+ let mut buffer = vec![
339
+ BLS12381G2_MULTICODEC_IDENTIFIER,
340
+ VARIABLE_INTEGER_TRAILING_BYTE,
341
+ ];
342
+ buffer.append(&mut key_bytes);
343
+
344
+ Ok(format!(
345
+ "{}{}",
346
+ MULTIBASE_ENCODED_BASE58_IDENTIFIER,
347
+ bs58::encode(buffer).into_string()
348
+ ))
349
+ }
350
+
351
+ #[napi]
352
+ pub fn verify_fingerprint(&self, fingerprint: String) -> Result<()> {
353
+ // fingerprint should have `z` prefix indicating
354
+ // that it's multi-base encoded
355
+ let mut chars = fingerprint.chars();
356
+ let head = chars
357
+ .next()
358
+ .ok_or(napi::Error::from_reason("fingerprint string is empty"))?
359
+ .to_string();
360
+
361
+ let rest = chars.collect::<String>();
362
+
363
+ if head != MULTIBASE_ENCODED_BASE58_IDENTIFIER {
364
+ return Err(napi::Error::from_reason(
365
+ "`fingerprint` must be a multibase encoded string.",
366
+ ));
367
+ };
368
+
369
+ let fingerprint_buffer = bs58::decode(rest).into_vec().map_err(|err| {
370
+ napi::Error::from_reason(format!("failed to decode bs58 value: error: {err}"))
371
+ })?;
372
+
373
+ let public_key_inner = self
374
+ .public_key_inner
375
+ .clone()
376
+ .ok_or(napi::Error::from_reason("public key buffer is missing"))?;
377
+
378
+ let leader = hex::encode(&fingerprint_buffer[..2]);
379
+ let leader_match = if leader == "eb01" { true } else { false };
380
+ let bytes_match = if &public_key_inner == &fingerprint_buffer[2..] {
381
+ true
382
+ } else {
383
+ false
384
+ };
385
+
386
+ if leader_match && bytes_match {
387
+ Ok(())
388
+ } else {
389
+ Err(napi::Error::from_reason(
390
+ "The fingerprint does not match the public key",
391
+ ))
392
+ }
393
+ }
178
394
  }
179
395
 
180
396
  pub fn convert_base64_url_to_base58(value: String) -> Result<String> {
@@ -198,14 +414,14 @@ pub struct KeyPairSignerOptions {
198
414
  impl KeyPairSigner {
199
415
  #[napi]
200
416
  pub async fn sign(&self, options: KeyPairSignerOptions) -> Result<Uint8Array> {
201
- if self.key.private_key_buffer.is_none() {
417
+ if self.key.private_key_inner.is_none() {
202
418
  return Err(napi::Error::from_reason("No private key to sign with."));
203
419
  }
204
420
 
205
421
  let messages: Vec<Vec<u8>> = options.data.into_iter().map(|x| x.to_vec()).collect();
206
422
  let key_pair = BlsKeyPair {
207
- public_key: self.key.public_key_buffer.clone(),
208
- secret_key: self.key.private_key_buffer.clone(),
423
+ public_key: self.key.public_key_inner.clone(),
424
+ secret_key: self.key.private_key_inner.clone(),
209
425
  };
210
426
  let sig = bls_sign(BlsBbsSignRequest { messages, key_pair })
211
427
  .await
@@ -231,7 +447,7 @@ impl KeyPairVerifier {
231
447
  #[napi]
232
448
  pub async fn verify(&self, options: KeyPairVerifierOptions) -> Result<bool> {
233
449
  let KeyPairVerifierOptions { data, signature } = options;
234
- let Some(public_key) = self.key.public_key_buffer.clone() else {
450
+ let Some(public_key) = self.key.public_key_inner.clone() else {
235
451
  return Err(napi::Error::from_reason(
236
452
  "key.public_key is required for verify",
237
453
  ));
package/src/types.rs CHANGED
@@ -5,8 +5,8 @@ use napi::bindgen_prelude::*;
5
5
  pub struct Bls12381G2KeyPair {
6
6
  pub id: Option<String>,
7
7
  pub controller: Option<String>,
8
- pub private_key_buffer: Option<Vec<u8>>,
9
- pub public_key_buffer: Option<Vec<u8>>,
8
+ pub private_key_inner: Option<Vec<u8>>,
9
+ pub public_key_inner: Option<Vec<u8>>,
10
10
  #[napi(js_name = "type")]
11
11
  pub type_: String,
12
12
  }
@@ -27,6 +27,18 @@ pub struct JwkKeyPairOptions {
27
27
  pub public_key_jwk: Option<JsonWebKey>,
28
28
  }
29
29
 
30
+ #[napi(object)]
31
+ pub struct FingerPrintFromPublicKeyOptions {
32
+ pub public_key_base58: String,
33
+ }
34
+
35
+ #[napi(object)]
36
+ pub struct KeyPairFromFingerPrintOptions {
37
+ pub id: Option<String>,
38
+ pub controller: Option<String>,
39
+ pub fingerprint: String,
40
+ }
41
+
30
42
  #[napi(object)]
31
43
  pub struct JsonWebKey {
32
44
  /////
@@ -130,6 +142,17 @@ impl TryFrom<&str> for BlsCurveName {
130
142
  }
131
143
  }
132
144
 
145
+ impl Into<String> for BlsCurveName {
146
+ fn into(self) -> String {
147
+ match self {
148
+ BlsCurveName::DeprecatedG1 => String::from("BLS12381_G1"),
149
+ BlsCurveName::DeprecatedG2 => String::from("BLS12381_G2"),
150
+ BlsCurveName::G1 => String::from("Bls12381G1"),
151
+ BlsCurveName::G2 => String::from("Bls12381G2"),
152
+ }
153
+ }
154
+ }
155
+
133
156
  #[derive(PartialEq)]
134
157
  pub enum JwkKty {
135
158
  OctetKeyPair,
@@ -152,3 +175,13 @@ impl TryFrom<&str> for JwkKty {
152
175
  }
153
176
  }
154
177
  }
178
+
179
+ impl Into<String> for JwkKty {
180
+ fn into(self) -> String {
181
+ match self {
182
+ JwkKty::OctetKeyPair => String::from("OKP"),
183
+ JwkKty::EC => String::from("EC"),
184
+ JwkKty::RSA => String::from("RSA"),
185
+ }
186
+ }
187
+ }
package/test.mjs CHANGED
@@ -76,3 +76,17 @@ test('sign and verify', async () => {
76
76
  assert.equal(ms_verify_ms_sig, true)
77
77
  assert.equal(ms_verify_hs_sig, true)
78
78
  })
79
+
80
+ test('issuer jwk', async () => {
81
+
82
+ const mattr = await Bls12381G2KeyPair.generate({ seed, });
83
+ const harry = await NewKeyPairClass.generate({ seed })
84
+ console.log(mattr.publicKeyBuffer)
85
+ console.log(mattr.privateKeyBuffer)
86
+
87
+ console.log(harry.publicKeyBuffer)
88
+ console.log(harry.publicKeyBuffer2)
89
+ console.log(harry.privateKeyBuffer)
90
+
91
+
92
+ })