Struct cardano_serialization_lib::crypto::PublicKey
source · pub struct PublicKey(_);
Expand description
ED25519 key used as public key
Implementations§
source§impl PublicKey
impl PublicKey
sourcepub fn from_bech32(bech32_str: &str) -> Result<PublicKey, JsError>
pub fn from_bech32(bech32_str: &str) -> Result<PublicKey, JsError>
Get public key from its bech32 representation Example:
const pkey = PublicKey.from_bech32('ed25519_pk1dgaagyh470y66p899txcl3r0jaeaxu6yd7z2dxyk55qcycdml8gszkxze2');
Examples found in repository?
src/crypto.rs (line 400)
395 396 397 398 399 400 401 402 403 404 405 406
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let s = <String as serde::de::Deserialize>::deserialize(deserializer)?;
PublicKey::from_bech32(&s).map_err(|_e| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&s),
&"bech32 public key string",
)
})
}
sourcepub fn as_bytes(&self) -> Vec<u8>
pub fn as_bytes(&self) -> Vec<u8>
Examples found in repository?
src/crypto.rs (line 78)
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
pub fn to_128_xprv(&self) -> Vec<u8> {
let prv_key = self.to_raw_key().as_bytes();
let pub_key = self.to_public().to_raw_key().as_bytes();
let cc = self.chaincode();
let mut buf = [0; 128];
buf[0..64].clone_from_slice(&prv_key);
buf[64..96].clone_from_slice(&pub_key);
buf[96..128].clone_from_slice(&cc);
buf.to_vec()
}
pub fn generate_ed25519_bip32() -> Result<Bip32PrivateKey, JsError> {
OsRng::new()
.map(crypto::SecretKey::<crypto::Ed25519Bip32>::generate)
.map(Bip32PrivateKey)
.map_err(|e| JsError::from_str(&format!("{}", e)))
}
pub fn to_raw_key(&self) -> PrivateKey {
PrivateKey(key::EitherEd25519SecretKey::Extended(
crypto::derive::to_raw_sk(&self.0),
))
}
pub fn to_public(&self) -> Bip32PublicKey {
Bip32PublicKey(self.0.to_public().into())
}
pub fn from_bytes(bytes: &[u8]) -> Result<Bip32PrivateKey, JsError> {
crypto::SecretKey::<crypto::Ed25519Bip32>::from_binary(bytes)
.map_err(|e| JsError::from_str(&format!("{}", e)))
.map(Bip32PrivateKey)
}
pub fn as_bytes(&self) -> Vec<u8> {
self.0.as_ref().to_vec()
}
pub fn from_bech32(bech32_str: &str) -> Result<Bip32PrivateKey, JsError> {
crypto::SecretKey::try_from_bech32_str(&bech32_str)
.map(Bip32PrivateKey)
.map_err(|_| JsError::from_str("Invalid secret key"))
}
pub fn to_bech32(&self) -> String {
self.0.to_bech32_str()
}
pub fn from_bip39_entropy(entropy: &[u8], password: &[u8]) -> Bip32PrivateKey {
Bip32PrivateKey(crypto::derive::from_bip39_entropy(&entropy, &password))
}
pub fn chaincode(&self) -> Vec<u8> {
const ED25519_PRIVATE_KEY_LENGTH: usize = 64;
const XPRV_SIZE: usize = 96;
self.0.as_ref()[ED25519_PRIVATE_KEY_LENGTH..XPRV_SIZE].to_vec()
}
pub fn to_hex(&self) -> String {
hex::encode(self.as_bytes())
}
pub fn from_hex(hex_str: &str) -> Result<Bip32PrivateKey, JsError> {
match hex::decode(hex_str) {
Ok(data) => Ok(Self::from_bytes(data.as_ref())?),
Err(e) => Err(JsError::from_str(&e.to_string())),
}
}
}
#[wasm_bindgen]
pub struct Bip32PublicKey(crypto::PublicKey<crypto::Ed25519Bip32>);
#[wasm_bindgen]
impl Bip32PublicKey {
/// derive this public key with the given index.
///
/// # Errors
///
/// If the index is not a soft derivation index (< 0x80000000) then
/// calling this method will fail.
///
/// # Security considerations
///
/// * hard derivation index cannot be soft derived with the public key
///
/// # Hard derivation vs Soft derivation
///
/// If you pass an index below 0x80000000 then it is a soft derivation.
/// The advantage of soft derivation is that it is possible to derive the
/// public key too. I.e. derivation the private key with a soft derivation
/// index and then retrieving the associated public key is equivalent to
/// deriving the public key associated to the parent private key.
///
/// Hard derivation index does not allow public key derivation.
///
/// This is why deriving the private key should not fail while deriving
/// the public key may fail (if the derivation index is invalid).
///
pub fn derive(&self, index: u32) -> Result<Bip32PublicKey, JsError> {
crypto::derive::derive_pk_ed25519(&self.0, index)
.map(Bip32PublicKey)
.map_err(|e| JsError::from_str(&format! {"{:?}", e}))
}
pub fn to_raw_key(&self) -> PublicKey {
PublicKey(crypto::derive::to_raw_pk(&self.0))
}
pub fn from_bytes(bytes: &[u8]) -> Result<Bip32PublicKey, JsError> {
crypto::PublicKey::<crypto::Ed25519Bip32>::from_binary(bytes)
.map_err(|e| JsError::from_str(&format!("{}", e)))
.map(Bip32PublicKey)
}
pub fn as_bytes(&self) -> Vec<u8> {
self.0.as_ref().to_vec()
}
pub fn from_bech32(bech32_str: &str) -> Result<Bip32PublicKey, JsError> {
crypto::PublicKey::try_from_bech32_str(&bech32_str)
.map(Bip32PublicKey)
.map_err(|e| JsError::from_str(&format!("{}", e)))
}
pub fn to_bech32(&self) -> String {
self.0.to_bech32_str()
}
pub fn chaincode(&self) -> Vec<u8> {
const ED25519_PUBLIC_KEY_LENGTH: usize = 32;
const XPUB_SIZE: usize = 64;
self.0.as_ref()[ED25519_PUBLIC_KEY_LENGTH..XPUB_SIZE].to_vec()
}
pub fn to_hex(&self) -> String {
hex::encode(self.as_bytes())
}
pub fn from_hex(hex_str: &str) -> Result<Bip32PublicKey, JsError> {
match hex::decode(hex_str) {
Ok(data) => Ok(Self::from_bytes(data.as_ref())?),
Err(e) => Err(JsError::from_str(&e.to_string())),
}
}
}
#[wasm_bindgen]
pub struct PrivateKey(key::EitherEd25519SecretKey);
impl From<key::EitherEd25519SecretKey> for PrivateKey {
fn from(secret_key: key::EitherEd25519SecretKey) -> PrivateKey {
PrivateKey(secret_key)
}
}
#[wasm_bindgen]
impl PrivateKey {
pub fn to_public(&self) -> PublicKey {
self.0.to_public().into()
}
pub fn generate_ed25519() -> Result<PrivateKey, JsError> {
OsRng::new()
.map(crypto::SecretKey::<crypto::Ed25519>::generate)
.map(key::EitherEd25519SecretKey::Normal)
.map(PrivateKey)
.map_err(|e| JsError::from_str(&format!("{}", e)))
}
pub fn generate_ed25519extended() -> Result<PrivateKey, JsError> {
OsRng::new()
.map(crypto::SecretKey::<crypto::Ed25519Extended>::generate)
.map(key::EitherEd25519SecretKey::Extended)
.map(PrivateKey)
.map_err(|e| JsError::from_str(&format!("{}", e)))
}
/// Get private key from its bech32 representation
/// ```javascript
/// PrivateKey.from_bech32('ed25519_sk1ahfetf02qwwg4dkq7mgp4a25lx5vh9920cr5wnxmpzz9906qvm8qwvlts0');
/// ```
/// For an extended 25519 key
/// ```javascript
/// PrivateKey.from_bech32('ed25519e_sk1gqwl4szuwwh6d0yk3nsqcc6xxc3fpvjlevgwvt60df59v8zd8f8prazt8ln3lmz096ux3xvhhvm3ca9wj2yctdh3pnw0szrma07rt5gl748fp');
/// ```
pub fn from_bech32(bech32_str: &str) -> Result<PrivateKey, JsError> {
crypto::SecretKey::try_from_bech32_str(&bech32_str)
.map(key::EitherEd25519SecretKey::Extended)
.or_else(|_| {
crypto::SecretKey::try_from_bech32_str(&bech32_str)
.map(key::EitherEd25519SecretKey::Normal)
})
.map(PrivateKey)
.map_err(|_| JsError::from_str("Invalid secret key"))
}
pub fn to_bech32(&self) -> String {
match self.0 {
key::EitherEd25519SecretKey::Normal(ref secret) => secret.to_bech32_str(),
key::EitherEd25519SecretKey::Extended(ref secret) => secret.to_bech32_str(),
}
}
pub fn as_bytes(&self) -> Vec<u8> {
match self.0 {
key::EitherEd25519SecretKey::Normal(ref secret) => secret.as_ref().to_vec(),
key::EitherEd25519SecretKey::Extended(ref secret) => secret.as_ref().to_vec(),
}
}
pub fn from_extended_bytes(bytes: &[u8]) -> Result<PrivateKey, JsError> {
crypto::SecretKey::from_binary(bytes)
.map(key::EitherEd25519SecretKey::Extended)
.map(PrivateKey)
.map_err(|_| JsError::from_str("Invalid extended secret key"))
}
pub fn from_normal_bytes(bytes: &[u8]) -> Result<PrivateKey, JsError> {
crypto::SecretKey::from_binary(bytes)
.map(key::EitherEd25519SecretKey::Normal)
.map(PrivateKey)
.map_err(|_| JsError::from_str("Invalid normal secret key"))
}
pub fn sign(&self, message: &[u8]) -> Ed25519Signature {
Ed25519Signature(self.0.sign(&message.to_vec()))
}
pub fn to_hex(&self) -> String {
hex::encode(self.as_bytes())
}
pub fn from_hex(hex_str: &str) -> Result<PrivateKey, JsError> {
let data: Vec<u8> = match hex::decode(hex_str) {
Ok(d) => d,
Err(e) => return Err(JsError::from_str(&e.to_string())),
};
let data_slice: &[u8] = data.as_slice();
crypto::SecretKey::from_binary(data_slice)
.map(key::EitherEd25519SecretKey::Normal)
.or_else(|_| {
crypto::SecretKey::from_binary(data_slice)
.map(key::EitherEd25519SecretKey::Extended)
})
.map(PrivateKey)
.map_err(|_| JsError::from_str("Invalid secret key"))
}
}
/// ED25519 key used as public key
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PublicKey(crypto::PublicKey<crypto::Ed25519>);
impl From<crypto::PublicKey<crypto::Ed25519>> for PublicKey {
fn from(key: crypto::PublicKey<crypto::Ed25519>) -> PublicKey {
PublicKey(key)
}
}
#[wasm_bindgen]
impl PublicKey {
/// Get public key from its bech32 representation
/// Example:
/// ```javascript
/// const pkey = PublicKey.from_bech32('ed25519_pk1dgaagyh470y66p899txcl3r0jaeaxu6yd7z2dxyk55qcycdml8gszkxze2');
/// ```
pub fn from_bech32(bech32_str: &str) -> Result<PublicKey, JsError> {
crypto::PublicKey::try_from_bech32_str(&bech32_str)
.map(PublicKey)
.map_err(|_| JsError::from_str("Malformed public key"))
}
pub fn to_bech32(&self) -> String {
self.0.to_bech32_str()
}
pub fn as_bytes(&self) -> Vec<u8> {
self.0.as_ref().to_vec()
}
pub fn from_bytes(bytes: &[u8]) -> Result<PublicKey, JsError> {
crypto::PublicKey::from_binary(bytes)
.map_err(|e| JsError::from_str(&format!("{}", e)))
.map(PublicKey)
}
pub fn verify(&self, data: &[u8], signature: &Ed25519Signature) -> bool {
signature.0.verify_slice(&self.0, data) == crypto::Verification::Success
}
pub fn hash(&self) -> Ed25519KeyHash {
Ed25519KeyHash::from(blake2b224(self.as_bytes().as_ref()))
}
pub fn to_hex(&self) -> String {
hex::encode(self.as_bytes())
}
pub fn from_hex(hex_str: &str) -> Result<PublicKey, JsError> {
match hex::decode(hex_str) {
Ok(data) => Ok(Self::from_bytes(data.as_ref())?),
Err(e) => Err(JsError::from_str(&e.to_string())),
}
}
}
impl serde::Serialize for PublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_bech32())
}
}
impl<'de> serde::de::Deserialize<'de> for PublicKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let s = <String as serde::de::Deserialize>::deserialize(deserializer)?;
PublicKey::from_bech32(&s).map_err(|_e| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&s),
&"bech32 public key string",
)
})
}
}
impl JsonSchema for PublicKey {
fn schema_name() -> String {
String::from("PublicKey")
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
String::json_schema(gen)
}
fn is_referenceable() -> bool {
String::is_referenceable()
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, JsonSchema)]
pub struct Vkey(PublicKey);
impl_to_from!(Vkey);
#[wasm_bindgen]
impl Vkey {
pub fn new(pk: &PublicKey) -> Self {
Self(pk.clone())
}
pub fn public_key(&self) -> PublicKey {
self.0.clone()
}
}
impl cbor_event::se::Serialize for Vkey {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_bytes(&self.0.as_bytes())
}
sourcepub fn from_bytes(bytes: &[u8]) -> Result<PublicKey, JsError>
pub fn from_bytes(bytes: &[u8]) -> Result<PublicKey, JsError>
Examples found in repository?
More examples
pub fn verify(&self, data: &[u8], signature: &Ed25519Signature) -> bool
sourcepub fn hash(&self) -> Ed25519KeyHash
pub fn hash(&self) -> Ed25519KeyHash
Examples found in repository?
src/utils.rs (line 1532)
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
fn encode_template_to_native_script(
template: &serde_json::Value,
cosigners: &HashMap<String, String>,
) -> Result<NativeScript, JsError> {
match template {
serde_json::Value::String(cosigner) => {
if let Some(xpub) = cosigners.get(cosigner) {
let bytes = Vec::from_hex(xpub).map_err(|e| JsError::from_str(&e.to_string()))?;
let public_key = Bip32PublicKey::from_bytes(&bytes)?;
Ok(NativeScript::new_script_pubkey(&ScriptPubkey::new(
&public_key.to_raw_key().hash(),
)))
} else {
Err(JsError::from_str(&format!(
"cosigner {} not found",
cosigner
)))
}
}
serde_json::Value::Object(map) if map.contains_key("all") => {
let mut all = NativeScripts::new();
if let serde_json::Value::Array(array) = map.get("all").unwrap() {
for val in array {
all.add(&encode_template_to_native_script(val, cosigners)?);
}
} else {
return Err(JsError::from_str("all must be an array"));
}
Ok(NativeScript::new_script_all(&ScriptAll::new(&all)))
}
serde_json::Value::Object(map) if map.contains_key("any") => {
let mut any = NativeScripts::new();
if let serde_json::Value::Array(array) = map.get("any").unwrap() {
for val in array {
any.add(&encode_template_to_native_script(val, cosigners)?);
}
} else {
return Err(JsError::from_str("any must be an array"));
}
Ok(NativeScript::new_script_any(&ScriptAny::new(&any)))
}
serde_json::Value::Object(map) if map.contains_key("some") => {
if let serde_json::Value::Object(some) = map.get("some").unwrap() {
if some.contains_key("at_least") && some.contains_key("from") {
let n = if let serde_json::Value::Number(at_least) =
some.get("at_least").unwrap()
{
if let Some(n) = at_least.as_u64() {
n as u32
} else {
return Err(JsError::from_str("at_least must be an integer"));
}
} else {
return Err(JsError::from_str("at_least must be an integer"));
};
let mut from_scripts = NativeScripts::new();
if let serde_json::Value::Array(array) = some.get("from").unwrap() {
for val in array {
from_scripts.add(&encode_template_to_native_script(val, cosigners)?);
}
} else {
return Err(JsError::from_str("from must be an array"));
}
Ok(NativeScript::new_script_n_of_k(&ScriptNOfK::new(
n,
&from_scripts,
)))
} else {
Err(JsError::from_str("some must contain at_least and from"))
}
} else {
Err(JsError::from_str("some must be an object"))
}
}
serde_json::Value::Object(map) if map.contains_key("active_from") => {
if let serde_json::Value::Number(active_from) = map.get("active_from").unwrap() {
if let Some(n) = active_from.as_u64() {
let slot: SlotBigNum = n.into();
let time_lock_start = TimelockStart::new_timelockstart(&slot);
Ok(NativeScript::new_timelock_start(&time_lock_start))
} else {
Err(JsError::from_str(
"active_from slot must be an integer greater than or equal to 0",
))
}
} else {
Err(JsError::from_str("active_from slot must be a number"))
}
}
serde_json::Value::Object(map) if map.contains_key("active_until") => {
if let serde_json::Value::Number(active_until) = map.get("active_until").unwrap() {
if let Some(n) = active_until.as_u64() {
let slot: SlotBigNum = n.into();
let time_lock_expiry = TimelockExpiry::new_timelockexpiry(&slot);
Ok(NativeScript::new_timelock_expiry(&time_lock_expiry))
} else {
Err(JsError::from_str(
"active_until slot must be an integer greater than or equal to 0",
))
}
} else {
Err(JsError::from_str("active_until slot must be a number"))
}
}
_ => Err(JsError::from_str("invalid template format")),
}
}
pub fn to_hex(&self) -> String
pub fn from_hex(hex_str: &str) -> Result<PublicKey, JsError>
Trait Implementations§
source§impl<'de> Deserialize<'de> for PublicKey
impl<'de> Deserialize<'de> for PublicKey
source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
source§impl JsonSchema for PublicKey
impl JsonSchema for PublicKey
source§fn schema_name() -> String
fn schema_name() -> String
The name of the generated JSON Schema. Read more
source§fn json_schema(gen: &mut SchemaGenerator) -> Schema
fn json_schema(gen: &mut SchemaGenerator) -> Schema
Generates a JSON Schema for this type. Read more
source§fn is_referenceable() -> bool
fn is_referenceable() -> bool
Whether JSON Schemas generated for this type should be re-used where possible using the
$ref
keyword. Read more