Struct cardano_serialization_lib::chain_crypto::SecretKey
source · pub struct SecretKey<A: AsymmetricKey>(_);
Implementations§
source§impl<A: AsymmetricKey> SecretKey<A>
impl<A: AsymmetricKey> SecretKey<A>
sourcepub fn to_public(&self) -> PublicKey<A::PubAlg>
pub fn to_public(&self) -> PublicKey<A::PubAlg>
Examples found in repository?
More examples
src/utils.rs (line 1191)
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
pub fn make_daedalus_bootstrap_witness(
tx_body_hash: &TransactionHash,
addr: &ByronAddress,
key: &LegacyDaedalusPrivateKey,
) -> BootstrapWitness {
let chain_code = key.chaincode();
let pubkey = Bip32PublicKey::from_bytes(&key.0.to_public().as_ref()).unwrap();
let vkey = Vkey::new(&pubkey.to_raw_key());
let signature =
Ed25519Signature::from_bytes(key.0.sign(&tx_body_hash.to_bytes()).as_ref().to_vec())
.unwrap();
BootstrapWitness::new(&vkey, &signature, chain_code, addr.attributes())
}
sourcepub fn from_binary(data: &[u8]) -> Result<Self, SecretKeyError>
pub fn from_binary(data: &[u8]) -> Result<Self, SecretKeyError>
Examples found in repository?
More examples
src/crypto.rs (line 106)
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 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
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())
}
}
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(),
)?)))
}
}
#[wasm_bindgen]
#[derive(Clone)]
pub struct Vkeys(Vec<Vkey>);
#[wasm_bindgen]
impl Vkeys {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> Vkey {
self.0[index].clone()
}
pub fn add(&mut self, elem: &Vkey) {
self.0.push(elem.clone());
}
}
impl cbor_event::se::Serialize for Vkeys {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(self.0.len() as u64))?;
for element in &self.0 {
element.serialize(serializer)?;
}
Ok(serializer)
}
}
impl Deserialize for Vkeys {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut arr = Vec::new();
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
while match len {
cbor_event::Len::Len(n) => arr.len() < n as usize,
cbor_event::Len::Indefinite => true,
} {
if raw.cbor_type()? == CBORType::Special {
assert_eq!(raw.special()?, CBORSpecial::Break);
break;
}
arr.push(Vkey::deserialize(raw)?);
}
Ok(())
})()
.map_err(|e| e.annotate("Vkeys"))?;
Ok(Self(arr))
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, JsonSchema)]
pub struct Vkeywitness {
vkey: Vkey,
signature: Ed25519Signature,
}
impl_to_from!(Vkeywitness);
#[wasm_bindgen]
impl Vkeywitness {
pub fn new(vkey: &Vkey, signature: &Ed25519Signature) -> Self {
Self {
vkey: vkey.clone(),
signature: signature.clone(),
}
}
pub fn vkey(&self) -> Vkey {
self.vkey.clone()
}
pub fn signature(&self) -> Ed25519Signature {
self.signature.clone()
}
}
impl cbor_event::se::Serialize for Vkeywitness {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(2))?;
self.vkey.serialize(serializer)?;
self.signature.serialize(serializer)
}
}
impl Deserialize for Vkeywitness {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
let vkey = (|| -> Result<_, DeserializeError> { Ok(Vkey::deserialize(raw)?) })()
.map_err(|e| e.annotate("vkey"))?;
let signature =
(|| -> Result<_, DeserializeError> { Ok(Ed25519Signature::deserialize(raw)?) })()
.map_err(|e| e.annotate("signature"))?;
let ret = Ok(Vkeywitness::new(&vkey, &signature));
match len {
cbor_event::Len::Len(n) => match n {
2 => (),
_ => {
return Err(DeserializeFailure::CBOR(cbor_event::Error::WrongLen(
2, len, "",
))
.into())
}
},
cbor_event::Len::Indefinite => match raw.special()? {
cbor_event::Special::Break =>
/* it's ok */
{
()
}
_ => return Err(DeserializeFailure::EndingBreakMissing.into()),
},
}
ret
})()
.map_err(|e| e.annotate("Vkeywitness"))
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, JsonSchema)]
pub struct Vkeywitnesses(pub(crate) Vec<Vkeywitness>);
impl_to_from!(Vkeywitnesses);
#[wasm_bindgen]
impl Vkeywitnesses {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> Vkeywitness {
self.0[index].clone()
}
pub fn add(&mut self, elem: &Vkeywitness) {
self.0.push(elem.clone());
}
}
impl cbor_event::se::Serialize for Vkeywitnesses {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(self.0.len() as u64))?;
for element in &self.0 {
element.serialize(serializer)?;
}
Ok(serializer)
}
}
impl Deserialize for Vkeywitnesses {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut arr = Vec::new();
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
while match len {
cbor_event::Len::Len(n) => arr.len() < n as usize,
cbor_event::Len::Indefinite => true,
} {
if raw.cbor_type()? == cbor_event::Type::Special {
assert_eq!(raw.special()?, cbor_event::Special::Break);
break;
}
arr.push(Vkeywitness::deserialize(raw)?);
}
Ok(())
})()
.map_err(|e| e.annotate("Vkeywitnesses"))?;
Ok(Self(arr))
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, JsonSchema)]
pub struct BootstrapWitness {
vkey: Vkey,
signature: Ed25519Signature,
chain_code: Vec<u8>,
attributes: Vec<u8>,
}
impl_to_from!(BootstrapWitness);
#[wasm_bindgen]
impl BootstrapWitness {
pub fn vkey(&self) -> Vkey {
self.vkey.clone()
}
pub fn signature(&self) -> Ed25519Signature {
self.signature.clone()
}
pub fn chain_code(&self) -> Vec<u8> {
self.chain_code.clone()
}
pub fn attributes(&self) -> Vec<u8> {
self.attributes.clone()
}
pub fn new(
vkey: &Vkey,
signature: &Ed25519Signature,
chain_code: Vec<u8>,
attributes: Vec<u8>,
) -> Self {
Self {
vkey: vkey.clone(),
signature: signature.clone(),
chain_code: chain_code,
attributes: attributes,
}
}
}
impl cbor_event::se::Serialize for BootstrapWitness {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(4))?;
self.vkey.serialize(serializer)?;
self.signature.serialize(serializer)?;
serializer.write_bytes(&self.chain_code)?;
serializer.write_bytes(&self.attributes)?;
Ok(serializer)
}
}
impl Deserialize for BootstrapWitness {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
let ret = Self::deserialize_as_embedded_group(raw, len);
match len {
cbor_event::Len::Len(_) =>
/* TODO: check finite len somewhere */
{
()
}
cbor_event::Len::Indefinite => match raw.special()? {
CBORSpecial::Break =>
/* it's ok */
{
()
}
_ => return Err(DeserializeFailure::EndingBreakMissing.into()),
},
}
ret
})()
.map_err(|e| e.annotate("BootstrapWitness"))
}
}
impl DeserializeEmbeddedGroup for BootstrapWitness {
fn deserialize_as_embedded_group<R: BufRead + Seek>(
raw: &mut Deserializer<R>,
_: cbor_event::Len,
) -> Result<Self, DeserializeError> {
let vkey = (|| -> Result<_, DeserializeError> { Ok(Vkey::deserialize(raw)?) })()
.map_err(|e| e.annotate("vkey"))?;
let signature =
(|| -> Result<_, DeserializeError> { Ok(Ed25519Signature::deserialize(raw)?) })()
.map_err(|e| e.annotate("signature"))?;
let chain_code = (|| -> Result<_, DeserializeError> { Ok(raw.bytes()?) })()
.map_err(|e| e.annotate("chain_code"))?;
let attributes = (|| -> Result<_, DeserializeError> { Ok(raw.bytes()?) })()
.map_err(|e| e.annotate("attributes"))?;
Ok(BootstrapWitness {
vkey,
signature,
chain_code,
attributes,
})
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, JsonSchema)]
pub struct BootstrapWitnesses(Vec<BootstrapWitness>);
#[wasm_bindgen]
impl BootstrapWitnesses {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> BootstrapWitness {
self.0[index].clone()
}
pub fn add(&mut self, elem: &BootstrapWitness) {
self.0.push(elem.clone());
}
}
impl cbor_event::se::Serialize for BootstrapWitnesses {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(self.0.len() as u64))?;
for element in &self.0 {
element.serialize(serializer)?;
}
Ok(serializer)
}
}
impl Deserialize for BootstrapWitnesses {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut arr = Vec::new();
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
while match len {
cbor_event::Len::Len(n) => arr.len() < n as usize,
cbor_event::Len::Indefinite => true,
} {
if raw.cbor_type()? == cbor_event::Type::Special {
assert_eq!(raw.special()?, cbor_event::Special::Break);
break;
}
arr.push(BootstrapWitness::deserialize(raw)?);
}
Ok(())
})()
.map_err(|e| e.annotate("BootstrapWitnesses"))?;
Ok(Self(arr))
}
}
#[wasm_bindgen]
pub struct PublicKeys(Vec<PublicKey>);
#[wasm_bindgen]
impl PublicKeys {
#[wasm_bindgen(constructor)]
pub fn new() -> PublicKeys {
PublicKeys(vec![])
}
pub fn size(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> PublicKey {
self.0[index].clone()
}
pub fn add(&mut self, key: &PublicKey) {
self.0.push(key.clone());
}
}
macro_rules! impl_signature {
($name:ident, $signee_type:ty, $verifier_type:ty) => {
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct $name(crypto::Signature<$signee_type, $verifier_type>);
#[wasm_bindgen]
impl $name {
pub fn to_bytes(&self) -> Vec<u8> {
self.0.as_ref().to_vec()
}
pub fn to_bech32(&self) -> String {
self.0.to_bech32_str()
}
pub fn to_hex(&self) -> String {
hex::encode(&self.0.as_ref())
}
pub fn from_bech32(bech32_str: &str) -> Result<$name, JsError> {
crypto::Signature::try_from_bech32_str(&bech32_str)
.map($name)
.map_err(|e| JsError::from_str(&format!("{}", e)))
}
pub fn from_hex(input: &str) -> Result<$name, JsError> {
crypto::Signature::from_str(input)
.map_err(|e| JsError::from_str(&format!("{:?}", e)))
.map($name)
}
}
from_bytes!($name, bytes, {
crypto::Signature::from_binary(bytes.as_ref())
.map_err(|e| {
DeserializeError::new(stringify!($name), DeserializeFailure::SignatureError(e))
})
.map($name)
});
impl cbor_event::se::Serialize for $name {
fn serialize<'se, W: std::io::Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_bytes(self.0.as_ref())
}
}
impl Deserialize for $name {
fn deserialize<R: std::io::BufRead>(
raw: &mut Deserializer<R>,
) -> Result<Self, DeserializeError> {
Ok(Self(crypto::Signature::from_binary(raw.bytes()?.as_ref())?))
}
}
impl serde::Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_hex())
}
}
impl<'de> serde::de::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let s = <String as serde::de::Deserialize>::deserialize(deserializer)?;
$name::from_hex(&s).map_err(|_e| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&s),
&"hex bytes for signature",
)
})
}
}
impl JsonSchema for $name {
fn schema_name() -> String {
String::from(stringify!($name))
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
String::json_schema(gen)
}
fn is_referenceable() -> bool {
String::is_referenceable()
}
}
};
}
impl_signature!(Ed25519Signature, Vec<u8>, crypto::Ed25519);
macro_rules! impl_hash_type {
($name:ident, $byte_count:expr) => {
#[wasm_bindgen]
#[derive(Debug, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct $name(pub(crate) [u8; $byte_count]);
// hash types are the only types in this library to not expect the entire CBOR structure.
// There is no CBOR binary tag here just the raw hash bytes.
from_bytes!($name, bytes, {
use std::convert::TryInto;
match bytes.len() {
$byte_count => Ok($name(bytes[..$byte_count].try_into().unwrap())),
other_len => {
let cbor_error = cbor_event::Error::WrongLen(
$byte_count,
cbor_event::Len::Len(other_len as u64),
"hash length",
);
Err(DeserializeError::new(
stringify!($name),
DeserializeFailure::CBOR(cbor_error),
))
}
}
});
#[wasm_bindgen]
impl $name {
// hash types are the only types in this library to not give the entire CBOR structure.
// There is no CBOR binary tag here just the raw hash bytes.
pub fn to_bytes(&self) -> Vec<u8> {
self.0.to_vec()
}
pub fn to_bech32(&self, prefix: &str) -> Result<String, JsError> {
bech32::encode(&prefix, self.to_bytes().to_base32())
.map_err(|e| JsError::from_str(&format! {"{:?}", e}))
}
pub fn from_bech32(bech_str: &str) -> Result<$name, JsError> {
let (_hrp, u5data) =
bech32::decode(bech_str).map_err(|e| JsError::from_str(&e.to_string()))?;
let data: Vec<u8> = bech32::FromBase32::from_base32(&u5data).unwrap();
Ok(Self::from_bytes(data)?)
}
pub fn to_hex(&self) -> String {
hex::encode(&self.0)
}
pub fn from_hex(hex: &str) -> Result<$name, JsError> {
let bytes = hex::decode(hex)
.map_err(|e| JsError::from_str(&format!("hex decode failed: {}", e)))?;
Self::from_bytes(bytes).map_err(|e| JsError::from_str(&format!("{:?}", e)))
}
}
// associated consts are not supported in wasm_bindgen
impl $name {
pub const BYTE_COUNT: usize = $byte_count;
}
// can't expose [T; N] to wasm for new() but it's useful internally so we implement From trait
impl From<[u8; $byte_count]> for $name {
fn from(bytes: [u8; $byte_count]) -> Self {
Self(bytes)
}
}
impl cbor_event::se::Serialize for $name {
fn serialize<'se, W: std::io::Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_bytes(self.0)
}
}
impl Deserialize for $name {
fn deserialize<R: std::io::BufRead>(
raw: &mut Deserializer<R>,
) -> Result<Self, DeserializeError> {
use std::convert::TryInto;
(|| -> Result<Self, DeserializeError> {
let bytes = raw.bytes()?;
if bytes.len() != $byte_count {
return Err(DeserializeFailure::CBOR(cbor_event::Error::WrongLen(
$byte_count,
cbor_event::Len::Len(bytes.len() as u64),
"hash length",
))
.into());
}
Ok($name(bytes[..$byte_count].try_into().unwrap()))
})()
.map_err(|e| e.annotate(stringify!($name)))
}
}
impl serde::Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_hex())
}
}
impl<'de> serde::de::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let s = <String as serde::de::Deserialize>::deserialize(deserializer)?;
$name::from_hex(&s).map_err(|_e| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&s),
&"hex bytes for hash",
)
})
}
}
impl JsonSchema for $name {
fn schema_name() -> String {
String::from(stringify!($name))
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
String::json_schema(gen)
}
fn is_referenceable() -> bool {
String::is_referenceable()
}
}
impl Display for $name {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_hex())
}
}
};
}
#[wasm_bindgen]
pub struct LegacyDaedalusPrivateKey(pub(crate) crypto::SecretKey<crypto::LegacyDaedalus>);
#[wasm_bindgen]
impl LegacyDaedalusPrivateKey {
pub fn from_bytes(bytes: &[u8]) -> Result<LegacyDaedalusPrivateKey, JsError> {
crypto::SecretKey::<crypto::LegacyDaedalus>::from_binary(bytes)
.map_err(|e| JsError::from_str(&format!("{}", e)))
.map(LegacyDaedalusPrivateKey)
}
source§impl<A: SigningAlgorithm> SecretKey<A>where
<A as AsymmetricKey>::PubAlg: VerificationAlgorithm,
impl<A: SigningAlgorithm> SecretKey<A>where
<A as AsymmetricKey>::PubAlg: VerificationAlgorithm,
sourcepub fn sign<T: AsRef<[u8]>>(&self, object: &T) -> Signature<T, A::PubAlg>
pub fn sign<T: AsRef<[u8]>>(&self, object: &T) -> Signature<T, A::PubAlg>
Examples found in repository?
src/impl_mockchain/key.rs (line 32)
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 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
pub fn sign<T: AsRef<[u8]>>(&self, dat: &T) -> crypto::Signature<T, crypto::Ed25519> {
match self {
EitherEd25519SecretKey::Extended(sk) => sk.sign(dat),
EitherEd25519SecretKey::Normal(sk) => sk.sign(dat),
}
}
pub fn sign_slice<T: ?Sized>(&self, dat: &[u8]) -> crypto::Signature<T, crypto::Ed25519> {
match self {
EitherEd25519SecretKey::Extended(sk) => sk.sign_slice(dat),
EitherEd25519SecretKey::Normal(sk) => sk.sign_slice(dat),
}
}
}
pub type SpendingPublicKey = crypto::PublicKey<crypto::Ed25519>;
pub type SpendingSignature<T> = crypto::Signature<T, crypto::Ed25519>;
pub type Ed25519Signature<T> = crypto::Signature<T, crypto::Ed25519>;
fn chain_crypto_pub_err(e: crypto::PublicKeyError) -> ReadError {
match e {
crypto::PublicKeyError::SizeInvalid => {
ReadError::StructureInvalid("publickey size invalid".to_string())
}
crypto::PublicKeyError::StructureInvalid => {
ReadError::StructureInvalid("publickey structure invalid".to_string())
}
}
}
fn chain_crypto_sig_err(e: crypto::SignatureError) -> ReadError {
match e {
crypto::SignatureError::SizeInvalid { expected, got } => ReadError::StructureInvalid(
format!("signature size invalid, expected {} got {}", expected, got),
),
crypto::SignatureError::StructureInvalid => {
ReadError::StructureInvalid("signature structure invalid".to_string())
}
}
}
#[inline]
pub fn serialize_public_key<A: AsymmetricPublicKey, W: std::io::Write>(
key: &crypto::PublicKey<A>,
mut writer: W,
) -> Result<(), std::io::Error> {
writer.write_all(key.as_ref())
}
#[inline]
pub fn serialize_signature<A: VerificationAlgorithm, T, W: std::io::Write>(
signature: &crypto::Signature<T, A>,
mut writer: W,
) -> Result<(), std::io::Error> {
writer.write_all(signature.as_ref())
}
#[inline]
pub fn deserialize_public_key<'a, A>(
buf: &mut ReadBuf<'a>,
) -> Result<crypto::PublicKey<A>, ReadError>
where
A: AsymmetricPublicKey,
{
let mut bytes = vec![0u8; A::PUBLIC_KEY_SIZE];
read_mut_slice(buf, &mut bytes[..])?;
crypto::PublicKey::from_binary(&bytes).map_err(chain_crypto_pub_err)
}
#[inline]
pub fn deserialize_signature<'a, A, T>(
buf: &mut ReadBuf<'a>,
) -> Result<crypto::Signature<T, A>, ReadError>
where
A: VerificationAlgorithm,
{
let mut bytes = vec![0u8; A::SIGNATURE_SIZE];
read_mut_slice(buf, &mut bytes[..])?;
crypto::Signature::from_binary(&bytes).map_err(chain_crypto_sig_err)
}
pub fn make_signature<T, A>(
spending_key: &crypto::SecretKey<A>,
data: &T,
) -> crypto::Signature<T, A::PubAlg>
where
A: SigningAlgorithm,
<A as AsymmetricKey>::PubAlg: VerificationAlgorithm,
T: property::Serialize,
{
let bytes = data.serialize_as_vec().unwrap();
spending_key.sign(&bytes).coerce()
}
pub fn verify_signature<T, A>(
signature: &crypto::Signature<T, A>,
public_key: &crypto::PublicKey<A>,
data: &T,
) -> crypto::Verification
where
A: VerificationAlgorithm,
T: property::Serialize,
{
let bytes = data.serialize_as_vec().unwrap();
signature.clone().coerce().verify(public_key, &bytes)
}
/// A serializable type T with a signature.
pub struct Signed<T, A: VerificationAlgorithm> {
pub data: T,
pub sig: crypto::Signature<T, A>,
}
pub fn signed_new<T: property::Serialize, A: SigningAlgorithm>(
secret_key: &crypto::SecretKey<A>,
data: T,
) -> Signed<T, A::PubAlg>
where
A::PubAlg: VerificationAlgorithm,
{
let bytes = data.serialize_as_vec().unwrap();
let signature = secret_key.sign(&bytes).coerce();
Signed {
data: data,
sig: signature,
}
}
More examples
src/utils.rs (line 1194)
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
pub fn make_daedalus_bootstrap_witness(
tx_body_hash: &TransactionHash,
addr: &ByronAddress,
key: &LegacyDaedalusPrivateKey,
) -> BootstrapWitness {
let chain_code = key.chaincode();
let pubkey = Bip32PublicKey::from_bytes(&key.0.to_public().as_ref()).unwrap();
let vkey = Vkey::new(&pubkey.to_raw_key());
let signature =
Ed25519Signature::from_bytes(key.0.sign(&tx_body_hash.to_bytes()).as_ref().to_vec())
.unwrap();
BootstrapWitness::new(&vkey, &signature, chain_code, addr.attributes())
}
Trait Implementations§
source§impl<A: AsymmetricKey> Bech32 for SecretKey<A>
impl<A: AsymmetricKey> Bech32 for SecretKey<A>
const BECH32_HRP: &'static str = A::SECRET_BECH32_HRP
fn try_from_bech32_str(bech32_str: &str) -> Result<Self, Error>
fn to_bech32_str(&self) -> String
source§impl<A: AsymmetricKey> Clone for SecretKey<A>
impl<A: AsymmetricKey> Clone for SecretKey<A>
Auto Trait Implementations§
impl<A> RefUnwindSafe for SecretKey<A>where
<A as AsymmetricKey>::Secret: RefUnwindSafe,
impl<A> Send for SecretKey<A>where
<A as AsymmetricKey>::Secret: Send,
impl<A> Sync for SecretKey<A>where
<A as AsymmetricKey>::Secret: Sync,
impl<A> Unpin for SecretKey<A>where
<A as AsymmetricKey>::Secret: Unpin,
impl<A> UnwindSafe for SecretKey<A>where
<A as AsymmetricKey>::Secret: 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
)