Struct cardano_serialization_lib::chain_crypto::PublicKey
source · pub struct PublicKey<A: AsymmetricPublicKey>(_);
Implementations§
source§impl<A: AsymmetricPublicKey> PublicKey<A>
impl<A: AsymmetricPublicKey> PublicKey<A>
sourcepub fn from_binary(data: &[u8]) -> Result<Self, PublicKeyError>
pub fn from_binary(data: &[u8]) -> Result<Self, PublicKeyError>
Examples found in repository?
src/chain_crypto/key.rs (line 102)
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
fn from_str(hex: &str) -> Result<Self, Self::Err> {
let bytes = hex::decode(hex).map_err(PublicKeyFromStrError::HexMalformed)?;
Self::from_binary(&bytes).map_err(PublicKeyFromStrError::KeyInvalid)
}
}
impl fmt::Display for SecretKeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SecretKeyError::SizeInvalid => write!(f, "Invalid Secret Key size"),
SecretKeyError::StructureInvalid => write!(f, "Invalid Secret Key structure"),
}
}
}
impl fmt::Display for PublicKeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PublicKeyError::SizeInvalid => write!(f, "Invalid Public Key size"),
PublicKeyError::StructureInvalid => write!(f, "Invalid Public Key structure"),
}
}
}
impl fmt::Display for PublicKeyFromStrError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PublicKeyFromStrError::HexMalformed(_) => "hex encoding malformed",
PublicKeyFromStrError::KeyInvalid(_) => "invalid public key data",
}
.fmt(f)
}
}
impl std::error::Error for SecretKeyError {}
impl std::error::Error for PublicKeyError {}
impl std::error::Error for PublicKeyFromStrError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
PublicKeyFromStrError::HexMalformed(e) => Some(e),
PublicKeyFromStrError::KeyInvalid(e) => Some(e),
}
}
}
impl<A: AsymmetricPublicKey> AsRef<[u8]> for PublicKey<A> {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl<A: AsymmetricKey> AsRef<[u8]> for SecretKey<A> {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl<A: AsymmetricKey> From<SecretKey<A>> for KeyPair<A> {
fn from(secret_key: SecretKey<A>) -> Self {
let public_key = secret_key.to_public();
KeyPair(secret_key, public_key)
}
}
impl<A: AsymmetricKey> SecretKey<A> {
pub fn generate<T: RngCore + CryptoRng>(rng: T) -> Self {
SecretKey(A::generate(rng))
}
pub fn to_public(&self) -> PublicKey<A::PubAlg> {
PublicKey(<A as AsymmetricKey>::compute_public(&self.0))
}
pub fn from_binary(data: &[u8]) -> Result<Self, SecretKeyError> {
Ok(SecretKey(<A as AsymmetricKey>::secret_from_binary(data)?))
}
}
impl<A: AsymmetricPublicKey> PublicKey<A> {
pub fn from_binary(data: &[u8]) -> Result<Self, PublicKeyError> {
Ok(PublicKey(<A as AsymmetricPublicKey>::public_from_binary(
data,
)?))
}
}
impl<A: AsymmetricKey> Clone for SecretKey<A> {
fn clone(&self) -> Self {
SecretKey(self.0.clone())
}
}
impl<A: AsymmetricPublicKey> Clone for PublicKey<A> {
fn clone(&self) -> Self {
PublicKey(self.0.clone())
}
}
impl<A: AsymmetricKey> Clone for KeyPair<A> {
fn clone(&self) -> Self {
KeyPair(self.0.clone(), self.1.clone())
}
}
impl<A: AsymmetricPublicKey> std::cmp::PartialEq<Self> for PublicKey<A> {
fn eq(&self, other: &Self) -> bool {
self.0.as_ref().eq(other.0.as_ref())
}
}
impl<A: AsymmetricPublicKey> std::cmp::Eq for PublicKey<A> {}
impl<A: AsymmetricPublicKey> std::cmp::PartialOrd<Self> for PublicKey<A> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.0.as_ref().partial_cmp(other.0.as_ref())
}
}
impl<A: AsymmetricPublicKey> std::cmp::Ord for PublicKey<A> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.as_ref().cmp(other.0.as_ref())
}
}
impl<A: AsymmetricPublicKey> Hash for PublicKey<A> {
fn hash<H>(&self, state: &mut H)
where
H: std::hash::Hasher,
{
self.0.as_ref().hash(state)
}
}
impl<A: AsymmetricPublicKey> Bech32 for PublicKey<A> {
const BECH32_HRP: &'static str = A::PUBLIC_BECH32_HRP;
fn try_from_bech32_str(bech32_str: &str) -> Result<Self, bech32::Error> {
let bytes = bech32::try_from_bech32_to_bytes::<Self>(bech32_str)?;
Self::from_binary(&bytes).map_err(bech32::Error::data_invalid)
}
More examples
src/crypto.rs (line 187)
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 445 446 447 448 449 450 451 452
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())
}
}
impl Deserialize for Vkey {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
Ok(Self(PublicKey(crypto::PublicKey::from_binary(
raw.bytes()?.as_ref(),
)?)))
}
Trait Implementations§
source§impl<A: AsymmetricPublicKey> Bech32 for PublicKey<A>
impl<A: AsymmetricPublicKey> Bech32 for PublicKey<A>
const BECH32_HRP: &'static str = A::PUBLIC_BECH32_HRP
fn try_from_bech32_str(bech32_str: &str) -> Result<Self, Error>
fn to_bech32_str(&self) -> String
source§impl<A: AsymmetricPublicKey> Clone for PublicKey<A>
impl<A: AsymmetricPublicKey> Clone for PublicKey<A>
source§impl<A: AsymmetricPublicKey> Debug for PublicKey<A>
impl<A: AsymmetricPublicKey> Debug for PublicKey<A>
source§impl<A: AsymmetricPublicKey> Display for PublicKey<A>
impl<A: AsymmetricPublicKey> Display for PublicKey<A>
source§impl<A: AsymmetricPublicKey> FromStr for PublicKey<A>
impl<A: AsymmetricPublicKey> FromStr for PublicKey<A>
source§impl<A: AsymmetricPublicKey> Hash for PublicKey<A>
impl<A: AsymmetricPublicKey> Hash for PublicKey<A>
source§impl<A: AsymmetricPublicKey> Ord for PublicKey<A>
impl<A: AsymmetricPublicKey> Ord for PublicKey<A>
source§impl<A: AsymmetricPublicKey> PartialEq<PublicKey<A>> for PublicKey<A>
impl<A: AsymmetricPublicKey> PartialEq<PublicKey<A>> for PublicKey<A>
source§impl<A: AsymmetricPublicKey> PartialOrd<PublicKey<A>> for PublicKey<A>
impl<A: AsymmetricPublicKey> PartialOrd<PublicKey<A>> for PublicKey<A>
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for
self
and other
) and is used by the <=
operator. Read moreimpl<A: AsymmetricPublicKey> Eq for PublicKey<A>
Auto Trait Implementations§
impl<A> RefUnwindSafe for PublicKey<A>where
<A as AsymmetricPublicKey>::Public: RefUnwindSafe,
impl<A> Send for PublicKey<A>where
<A as AsymmetricPublicKey>::Public: Send,
impl<A> Sync for PublicKey<A>where
<A as AsymmetricPublicKey>::Public: Sync,
impl<A> Unpin for PublicKey<A>where
<A as AsymmetricPublicKey>::Public: Unpin,
impl<A> UnwindSafe for PublicKey<A>where
<A as AsymmetricPublicKey>::Public: UnwindSafe,
Blanket Implementations§
source§impl<T> Base32Len for Twhere
T: AsRef<[u8]>,
impl<T> Base32Len for Twhere
T: AsRef<[u8]>,
source§fn base32_len(&self) -> usize
fn base32_len(&self) -> usize
Calculate the base32 serialized length
source§impl<T> ToBase32 for Twhere
T: AsRef<[u8]>,
impl<T> ToBase32 for Twhere
T: AsRef<[u8]>,
source§fn write_base32<W>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err>where
W: WriteBase32,
fn write_base32<W>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err>where
W: WriteBase32,
Encode as base32 and write it to the supplied writer
Implementations shouldn’t allocate.
source§impl<T> ToHex for Twhere
T: AsRef<[u8]>,
impl<T> ToHex for Twhere
T: AsRef<[u8]>,
source§fn encode_hex<U>(&self) -> Uwhere
U: FromIterator<char>,
fn encode_hex<U>(&self) -> Uwhere
U: FromIterator<char>,
Encode the hex strict representing
self
into the result. Lower case
letters are used (e.g. f9b4ca
)source§fn encode_hex_upper<U>(&self) -> Uwhere
U: FromIterator<char>,
fn encode_hex_upper<U>(&self) -> Uwhere
U: FromIterator<char>,
Encode the hex strict representing
self
into the result. Upper case
letters are used (e.g. F9B4CA
)