Struct cardano_serialization_lib::address::Address
source · pub struct Address(_);
Implementations§
source§impl Address
impl Address
pub fn from_bytes(data: Vec<u8>) -> Result<Address, DeserializeError>
source§impl Address
impl Address
pub fn to_hex(&self) -> String
pub fn from_hex(hex_str: &str) -> Result<Address, JsError>
sourcepub fn to_bytes(&self) -> Vec<u8>
pub fn to_bytes(&self) -> Vec<u8>
Examples found in repository?
src/address.rs (line 384)
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
pub fn to_hex(&self) -> String {
hex::encode(self.to_bytes())
}
pub fn from_hex(hex_str: &str) -> Result<Address, JsError> {
match hex::decode(hex_str) {
Ok(data) => Ok(Self::from_bytes_impl(data.as_ref())?),
Err(e) => Err(JsError::from_str(&e.to_string())),
}
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::new();
match &self.0 {
AddrType::Base(base) => {
let header: u8 = ((base.payment.kind() as u8) << 4)
| ((base.stake.kind() as u8) << 5)
| (base.network & 0xF);
buf.push(header);
buf.extend(base.payment.to_raw_bytes());
buf.extend(base.stake.to_raw_bytes());
}
AddrType::Ptr(ptr) => {
let header: u8 =
0b0100_0000 | ((ptr.payment.kind() as u8) << 4) | (ptr.network & 0xF);
buf.push(header);
buf.extend(ptr.payment.to_raw_bytes());
buf.extend(variable_nat_encode(from_bignum(&ptr.stake.slot)));
buf.extend(variable_nat_encode(from_bignum(&ptr.stake.tx_index)));
buf.extend(variable_nat_encode(from_bignum(&ptr.stake.cert_index)));
}
AddrType::Enterprise(enterprise) => {
let header: u8 = 0b0110_0000
| ((enterprise.payment.kind() as u8) << 4)
| (enterprise.network & 0xF);
buf.push(header);
buf.extend(enterprise.payment.to_raw_bytes());
}
AddrType::Reward(reward) => {
let header: u8 =
0b1110_0000 | ((reward.payment.kind() as u8) << 4) | (reward.network & 0xF);
buf.push(header);
buf.extend(reward.payment.to_raw_bytes());
}
AddrType::Byron(byron) => buf.extend(byron.to_bytes()),
}
buf
}
fn from_bytes_impl(data: &[u8]) -> Result<Address, DeserializeError> {
use std::convert::TryInto;
// header has 4 bits addr type discrim then 4 bits network discrim.
// Copied from shelley.cddl:
//
// shelley payment addresses:
// bit 7: 0
// bit 6: base/other
// bit 5: pointer/enterprise [for base: stake cred is keyhash/scripthash]
// bit 4: payment cred is keyhash/scripthash
// bits 3-0: network id
//
// reward addresses:
// bits 7-5: 111
// bit 4: credential is keyhash/scripthash
// bits 3-0: network id
//
// byron addresses:
// bits 7-4: 1000
(|| -> Result<Self, DeserializeError> {
let header = data[0];
let network = header & 0x0F;
const HASH_LEN: usize = Ed25519KeyHash::BYTE_COUNT;
// should be static assert but it's maybe not worth importing a whole external crate for it now
assert_eq!(ScriptHash::BYTE_COUNT, HASH_LEN);
// checks the /bit/ bit of the header for key vs scripthash then reads the credential starting at byte position /pos/
let read_addr_cred = |bit: u8, pos: usize| {
let hash_bytes: [u8; HASH_LEN] = data[pos..pos + HASH_LEN].try_into().unwrap();
let x = if header & (1 << bit) == 0 {
StakeCredential::from_keyhash(&Ed25519KeyHash::from(hash_bytes))
} else {
StakeCredential::from_scripthash(&ScriptHash::from(hash_bytes))
};
x
};
let addr = match (header & 0xF0) >> 4 {
// base
0b0000 | 0b0001 | 0b0010 | 0b0011 => {
const BASE_ADDR_SIZE: usize = 1 + HASH_LEN * 2;
if data.len() < BASE_ADDR_SIZE {
return Err(cbor_event::Error::NotEnough(data.len(), BASE_ADDR_SIZE).into());
}
if data.len() > BASE_ADDR_SIZE {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Base(BaseAddress::new(
network,
&read_addr_cred(4, 1),
&read_addr_cred(5, 1 + HASH_LEN),
))
}
// pointer
0b0100 | 0b0101 => {
// header + keyhash + 3 natural numbers (min 1 byte each)
const PTR_ADDR_MIN_SIZE: usize = 1 + HASH_LEN + 1 + 1 + 1;
if data.len() < PTR_ADDR_MIN_SIZE {
// possibly more, but depends on how many bytes the natural numbers are for the pointer
return Err(
cbor_event::Error::NotEnough(data.len(), PTR_ADDR_MIN_SIZE).into()
);
}
let mut byte_index = 1;
let payment_cred = read_addr_cred(4, 1);
byte_index += HASH_LEN;
let (slot, slot_bytes) =
variable_nat_decode(&data[byte_index..]).ok_or(DeserializeError::new(
"Address.Pointer.slot",
DeserializeFailure::VariableLenNatDecodeFailed,
))?;
byte_index += slot_bytes;
let (tx_index, tx_bytes) =
variable_nat_decode(&data[byte_index..]).ok_or(DeserializeError::new(
"Address.Pointer.tx_index",
DeserializeFailure::VariableLenNatDecodeFailed,
))?;
byte_index += tx_bytes;
let (cert_index, cert_bytes) =
variable_nat_decode(&data[byte_index..]).ok_or(DeserializeError::new(
"Address.Pointer.cert_index",
DeserializeFailure::VariableLenNatDecodeFailed,
))?;
byte_index += cert_bytes;
if byte_index < data.len() {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Ptr(PointerAddress::new(
network,
&payment_cred,
&Pointer::new_pointer(
&to_bignum(slot),
&to_bignum(tx_index),
&to_bignum(cert_index),
),
))
}
// enterprise
0b0110 | 0b0111 => {
const ENTERPRISE_ADDR_SIZE: usize = 1 + HASH_LEN;
if data.len() < ENTERPRISE_ADDR_SIZE {
return Err(
cbor_event::Error::NotEnough(data.len(), ENTERPRISE_ADDR_SIZE).into(),
);
}
if data.len() > ENTERPRISE_ADDR_SIZE {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Enterprise(EnterpriseAddress::new(network, &read_addr_cred(4, 1)))
}
// reward
0b1110 | 0b1111 => {
const REWARD_ADDR_SIZE: usize = 1 + HASH_LEN;
if data.len() < REWARD_ADDR_SIZE {
return Err(
cbor_event::Error::NotEnough(data.len(), REWARD_ADDR_SIZE).into()
);
}
if data.len() > REWARD_ADDR_SIZE {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Reward(RewardAddress::new(network, &read_addr_cred(4, 1)))
}
// byron
0b1000 => {
// note: 0b1000 was chosen because all existing Byron addresses actually start with 0b1000
// Therefore you can re-use Byron addresses as-is
match ByronAddress::from_bytes(data.to_vec()) {
Ok(addr) => AddrType::Byron(addr),
Err(e) => {
return Err(cbor_event::Error::CustomError(
e.as_string().unwrap_or_default(),
)
.into())
}
}
}
_ => return Err(DeserializeFailure::BadAddressType(header).into()),
};
Ok(Address(addr))
})()
.map_err(|e| e.annotate("Address"))
}
pub fn to_bech32(&self, prefix: Option<String>) -> Result<String, JsError> {
let final_prefix = match prefix {
Some(prefix) => prefix,
None => {
// see CIP5 for bech32 prefix rules
let prefix_header = match &self.0 {
AddrType::Reward(_) => "stake",
_ => "addr",
};
let prefix_tail = match self.network_id()? {
id if id == NetworkInfo::testnet().network_id() => "_test",
_ => "",
};
format!("{}{}", prefix_header, prefix_tail)
}
};
bech32::encode(&final_prefix, self.to_bytes().to_base32())
.map_err(|e| JsError::from_str(&format! {"{:?}", e}))
}
pub fn from_bech32(bech_str: &str) -> Result<Address, 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_impl(data.as_ref())?)
}
pub fn network_id(&self) -> Result<u8, JsError> {
match &self.0 {
AddrType::Base(a) => Ok(a.network),
AddrType::Enterprise(a) => Ok(a.network),
AddrType::Ptr(a) => Ok(a.network),
AddrType::Reward(a) => Ok(a.network),
AddrType::Byron(a) => a.network_id(),
}
}
}
impl cbor_event::se::Serialize for Address {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_bytes(self.to_bytes())
}
More examples
sourcepub fn to_bech32(&self, prefix: Option<String>) -> Result<String, JsError>
pub fn to_bech32(&self, prefix: Option<String>) -> Result<String, JsError>
Examples found in repository?
src/address.rs (line 345)
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
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let bech32 = self
.to_bech32(None)
.map_err(|e| serde::ser::Error::custom(format!("to_bech32: {:?}", e)))?;
serializer.serialize_str(&bech32)
}
}
impl<'de> serde::de::Deserialize<'de> for Address {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let bech32 = <String as serde::de::Deserialize>::deserialize(deserializer)?;
Address::from_bech32(&bech32).map_err(|_e| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&bech32),
&"bech32 address string",
)
})
}
}
impl JsonSchema for Address {
fn schema_name() -> String {
String::from("Address")
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
String::json_schema(gen)
}
fn is_referenceable() -> bool {
String::is_referenceable()
}
}
// to/from_bytes() are the raw encoding without a wrapping CBOR Bytes tag
// while Serialize and Deserialize traits include that for inclusion with
// other CBOR types
#[wasm_bindgen]
impl Address {
pub fn to_hex(&self) -> String {
hex::encode(self.to_bytes())
}
pub fn from_hex(hex_str: &str) -> Result<Address, JsError> {
match hex::decode(hex_str) {
Ok(data) => Ok(Self::from_bytes_impl(data.as_ref())?),
Err(e) => Err(JsError::from_str(&e.to_string())),
}
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::new();
match &self.0 {
AddrType::Base(base) => {
let header: u8 = ((base.payment.kind() as u8) << 4)
| ((base.stake.kind() as u8) << 5)
| (base.network & 0xF);
buf.push(header);
buf.extend(base.payment.to_raw_bytes());
buf.extend(base.stake.to_raw_bytes());
}
AddrType::Ptr(ptr) => {
let header: u8 =
0b0100_0000 | ((ptr.payment.kind() as u8) << 4) | (ptr.network & 0xF);
buf.push(header);
buf.extend(ptr.payment.to_raw_bytes());
buf.extend(variable_nat_encode(from_bignum(&ptr.stake.slot)));
buf.extend(variable_nat_encode(from_bignum(&ptr.stake.tx_index)));
buf.extend(variable_nat_encode(from_bignum(&ptr.stake.cert_index)));
}
AddrType::Enterprise(enterprise) => {
let header: u8 = 0b0110_0000
| ((enterprise.payment.kind() as u8) << 4)
| (enterprise.network & 0xF);
buf.push(header);
buf.extend(enterprise.payment.to_raw_bytes());
}
AddrType::Reward(reward) => {
let header: u8 =
0b1110_0000 | ((reward.payment.kind() as u8) << 4) | (reward.network & 0xF);
buf.push(header);
buf.extend(reward.payment.to_raw_bytes());
}
AddrType::Byron(byron) => buf.extend(byron.to_bytes()),
}
buf
}
fn from_bytes_impl(data: &[u8]) -> Result<Address, DeserializeError> {
use std::convert::TryInto;
// header has 4 bits addr type discrim then 4 bits network discrim.
// Copied from shelley.cddl:
//
// shelley payment addresses:
// bit 7: 0
// bit 6: base/other
// bit 5: pointer/enterprise [for base: stake cred is keyhash/scripthash]
// bit 4: payment cred is keyhash/scripthash
// bits 3-0: network id
//
// reward addresses:
// bits 7-5: 111
// bit 4: credential is keyhash/scripthash
// bits 3-0: network id
//
// byron addresses:
// bits 7-4: 1000
(|| -> Result<Self, DeserializeError> {
let header = data[0];
let network = header & 0x0F;
const HASH_LEN: usize = Ed25519KeyHash::BYTE_COUNT;
// should be static assert but it's maybe not worth importing a whole external crate for it now
assert_eq!(ScriptHash::BYTE_COUNT, HASH_LEN);
// checks the /bit/ bit of the header for key vs scripthash then reads the credential starting at byte position /pos/
let read_addr_cred = |bit: u8, pos: usize| {
let hash_bytes: [u8; HASH_LEN] = data[pos..pos + HASH_LEN].try_into().unwrap();
let x = if header & (1 << bit) == 0 {
StakeCredential::from_keyhash(&Ed25519KeyHash::from(hash_bytes))
} else {
StakeCredential::from_scripthash(&ScriptHash::from(hash_bytes))
};
x
};
let addr = match (header & 0xF0) >> 4 {
// base
0b0000 | 0b0001 | 0b0010 | 0b0011 => {
const BASE_ADDR_SIZE: usize = 1 + HASH_LEN * 2;
if data.len() < BASE_ADDR_SIZE {
return Err(cbor_event::Error::NotEnough(data.len(), BASE_ADDR_SIZE).into());
}
if data.len() > BASE_ADDR_SIZE {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Base(BaseAddress::new(
network,
&read_addr_cred(4, 1),
&read_addr_cred(5, 1 + HASH_LEN),
))
}
// pointer
0b0100 | 0b0101 => {
// header + keyhash + 3 natural numbers (min 1 byte each)
const PTR_ADDR_MIN_SIZE: usize = 1 + HASH_LEN + 1 + 1 + 1;
if data.len() < PTR_ADDR_MIN_SIZE {
// possibly more, but depends on how many bytes the natural numbers are for the pointer
return Err(
cbor_event::Error::NotEnough(data.len(), PTR_ADDR_MIN_SIZE).into()
);
}
let mut byte_index = 1;
let payment_cred = read_addr_cred(4, 1);
byte_index += HASH_LEN;
let (slot, slot_bytes) =
variable_nat_decode(&data[byte_index..]).ok_or(DeserializeError::new(
"Address.Pointer.slot",
DeserializeFailure::VariableLenNatDecodeFailed,
))?;
byte_index += slot_bytes;
let (tx_index, tx_bytes) =
variable_nat_decode(&data[byte_index..]).ok_or(DeserializeError::new(
"Address.Pointer.tx_index",
DeserializeFailure::VariableLenNatDecodeFailed,
))?;
byte_index += tx_bytes;
let (cert_index, cert_bytes) =
variable_nat_decode(&data[byte_index..]).ok_or(DeserializeError::new(
"Address.Pointer.cert_index",
DeserializeFailure::VariableLenNatDecodeFailed,
))?;
byte_index += cert_bytes;
if byte_index < data.len() {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Ptr(PointerAddress::new(
network,
&payment_cred,
&Pointer::new_pointer(
&to_bignum(slot),
&to_bignum(tx_index),
&to_bignum(cert_index),
),
))
}
// enterprise
0b0110 | 0b0111 => {
const ENTERPRISE_ADDR_SIZE: usize = 1 + HASH_LEN;
if data.len() < ENTERPRISE_ADDR_SIZE {
return Err(
cbor_event::Error::NotEnough(data.len(), ENTERPRISE_ADDR_SIZE).into(),
);
}
if data.len() > ENTERPRISE_ADDR_SIZE {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Enterprise(EnterpriseAddress::new(network, &read_addr_cred(4, 1)))
}
// reward
0b1110 | 0b1111 => {
const REWARD_ADDR_SIZE: usize = 1 + HASH_LEN;
if data.len() < REWARD_ADDR_SIZE {
return Err(
cbor_event::Error::NotEnough(data.len(), REWARD_ADDR_SIZE).into()
);
}
if data.len() > REWARD_ADDR_SIZE {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Reward(RewardAddress::new(network, &read_addr_cred(4, 1)))
}
// byron
0b1000 => {
// note: 0b1000 was chosen because all existing Byron addresses actually start with 0b1000
// Therefore you can re-use Byron addresses as-is
match ByronAddress::from_bytes(data.to_vec()) {
Ok(addr) => AddrType::Byron(addr),
Err(e) => {
return Err(cbor_event::Error::CustomError(
e.as_string().unwrap_or_default(),
)
.into())
}
}
}
_ => return Err(DeserializeFailure::BadAddressType(header).into()),
};
Ok(Address(addr))
})()
.map_err(|e| e.annotate("Address"))
}
pub fn to_bech32(&self, prefix: Option<String>) -> Result<String, JsError> {
let final_prefix = match prefix {
Some(prefix) => prefix,
None => {
// see CIP5 for bech32 prefix rules
let prefix_header = match &self.0 {
AddrType::Reward(_) => "stake",
_ => "addr",
};
let prefix_tail = match self.network_id()? {
id if id == NetworkInfo::testnet().network_id() => "_test",
_ => "",
};
format!("{}{}", prefix_header, prefix_tail)
}
};
bech32::encode(&final_prefix, self.to_bytes().to_base32())
.map_err(|e| JsError::from_str(&format! {"{:?}", e}))
}
pub fn from_bech32(bech_str: &str) -> Result<Address, 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_impl(data.as_ref())?)
}
pub fn network_id(&self) -> Result<u8, JsError> {
match &self.0 {
AddrType::Base(a) => Ok(a.network),
AddrType::Enterprise(a) => Ok(a.network),
AddrType::Ptr(a) => Ok(a.network),
AddrType::Reward(a) => Ok(a.network),
AddrType::Byron(a) => a.network_id(),
}
}
}
impl cbor_event::se::Serialize for Address {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_bytes(self.to_bytes())
}
}
impl Deserialize for Address {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
Self::from_bytes_impl(raw.bytes()?.as_ref())
}
}
#[wasm_bindgen]
#[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct BaseAddress {
network: u8,
payment: StakeCredential,
stake: StakeCredential,
}
#[wasm_bindgen]
impl BaseAddress {
pub fn new(network: u8, payment: &StakeCredential, stake: &StakeCredential) -> Self {
Self {
network,
payment: payment.clone(),
stake: stake.clone(),
}
}
pub fn payment_cred(&self) -> StakeCredential {
self.payment.clone()
}
pub fn stake_cred(&self) -> StakeCredential {
self.stake.clone()
}
pub fn to_address(&self) -> Address {
Address(AddrType::Base(self.clone()))
}
pub fn from_address(addr: &Address) -> Option<BaseAddress> {
match &addr.0 {
AddrType::Base(base) => Some(base.clone()),
_ => None,
}
}
}
#[wasm_bindgen]
#[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct EnterpriseAddress {
network: u8,
payment: StakeCredential,
}
#[wasm_bindgen]
impl EnterpriseAddress {
pub fn new(network: u8, payment: &StakeCredential) -> Self {
Self {
network,
payment: payment.clone(),
}
}
pub fn payment_cred(&self) -> StakeCredential {
self.payment.clone()
}
pub fn to_address(&self) -> Address {
Address(AddrType::Enterprise(self.clone()))
}
pub fn from_address(addr: &Address) -> Option<EnterpriseAddress> {
match &addr.0 {
AddrType::Enterprise(enterprise) => Some(enterprise.clone()),
_ => None,
}
}
}
#[wasm_bindgen]
#[derive(Debug, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RewardAddress {
network: u8,
payment: StakeCredential,
}
#[wasm_bindgen]
impl RewardAddress {
pub fn new(network: u8, payment: &StakeCredential) -> Self {
Self {
network,
payment: payment.clone(),
}
}
pub fn payment_cred(&self) -> StakeCredential {
self.payment.clone()
}
pub fn to_address(&self) -> Address {
Address(AddrType::Reward(self.clone()))
}
pub fn from_address(addr: &Address) -> Option<RewardAddress> {
match &addr.0 {
AddrType::Reward(reward) => Some(reward.clone()),
_ => None,
}
}
}
impl serde::Serialize for RewardAddress {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let bech32 = self
.to_address()
.to_bech32(None)
.map_err(|e| serde::ser::Error::custom(format!("to_bech32: {:?}", e)))?;
serializer.serialize_str(&bech32)
}
sourcepub fn from_bech32(bech_str: &str) -> Result<Address, JsError>
pub fn from_bech32(bech_str: &str) -> Result<Address, JsError>
Examples found in repository?
More examples
src/address.rs (line 357)
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
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let bech32 = <String as serde::de::Deserialize>::deserialize(deserializer)?;
Address::from_bech32(&bech32).map_err(|_e| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&bech32),
&"bech32 address string",
)
})
}
}
impl JsonSchema for Address {
fn schema_name() -> String {
String::from("Address")
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
String::json_schema(gen)
}
fn is_referenceable() -> bool {
String::is_referenceable()
}
}
// to/from_bytes() are the raw encoding without a wrapping CBOR Bytes tag
// while Serialize and Deserialize traits include that for inclusion with
// other CBOR types
#[wasm_bindgen]
impl Address {
pub fn to_hex(&self) -> String {
hex::encode(self.to_bytes())
}
pub fn from_hex(hex_str: &str) -> Result<Address, JsError> {
match hex::decode(hex_str) {
Ok(data) => Ok(Self::from_bytes_impl(data.as_ref())?),
Err(e) => Err(JsError::from_str(&e.to_string())),
}
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::new();
match &self.0 {
AddrType::Base(base) => {
let header: u8 = ((base.payment.kind() as u8) << 4)
| ((base.stake.kind() as u8) << 5)
| (base.network & 0xF);
buf.push(header);
buf.extend(base.payment.to_raw_bytes());
buf.extend(base.stake.to_raw_bytes());
}
AddrType::Ptr(ptr) => {
let header: u8 =
0b0100_0000 | ((ptr.payment.kind() as u8) << 4) | (ptr.network & 0xF);
buf.push(header);
buf.extend(ptr.payment.to_raw_bytes());
buf.extend(variable_nat_encode(from_bignum(&ptr.stake.slot)));
buf.extend(variable_nat_encode(from_bignum(&ptr.stake.tx_index)));
buf.extend(variable_nat_encode(from_bignum(&ptr.stake.cert_index)));
}
AddrType::Enterprise(enterprise) => {
let header: u8 = 0b0110_0000
| ((enterprise.payment.kind() as u8) << 4)
| (enterprise.network & 0xF);
buf.push(header);
buf.extend(enterprise.payment.to_raw_bytes());
}
AddrType::Reward(reward) => {
let header: u8 =
0b1110_0000 | ((reward.payment.kind() as u8) << 4) | (reward.network & 0xF);
buf.push(header);
buf.extend(reward.payment.to_raw_bytes());
}
AddrType::Byron(byron) => buf.extend(byron.to_bytes()),
}
buf
}
fn from_bytes_impl(data: &[u8]) -> Result<Address, DeserializeError> {
use std::convert::TryInto;
// header has 4 bits addr type discrim then 4 bits network discrim.
// Copied from shelley.cddl:
//
// shelley payment addresses:
// bit 7: 0
// bit 6: base/other
// bit 5: pointer/enterprise [for base: stake cred is keyhash/scripthash]
// bit 4: payment cred is keyhash/scripthash
// bits 3-0: network id
//
// reward addresses:
// bits 7-5: 111
// bit 4: credential is keyhash/scripthash
// bits 3-0: network id
//
// byron addresses:
// bits 7-4: 1000
(|| -> Result<Self, DeserializeError> {
let header = data[0];
let network = header & 0x0F;
const HASH_LEN: usize = Ed25519KeyHash::BYTE_COUNT;
// should be static assert but it's maybe not worth importing a whole external crate for it now
assert_eq!(ScriptHash::BYTE_COUNT, HASH_LEN);
// checks the /bit/ bit of the header for key vs scripthash then reads the credential starting at byte position /pos/
let read_addr_cred = |bit: u8, pos: usize| {
let hash_bytes: [u8; HASH_LEN] = data[pos..pos + HASH_LEN].try_into().unwrap();
let x = if header & (1 << bit) == 0 {
StakeCredential::from_keyhash(&Ed25519KeyHash::from(hash_bytes))
} else {
StakeCredential::from_scripthash(&ScriptHash::from(hash_bytes))
};
x
};
let addr = match (header & 0xF0) >> 4 {
// base
0b0000 | 0b0001 | 0b0010 | 0b0011 => {
const BASE_ADDR_SIZE: usize = 1 + HASH_LEN * 2;
if data.len() < BASE_ADDR_SIZE {
return Err(cbor_event::Error::NotEnough(data.len(), BASE_ADDR_SIZE).into());
}
if data.len() > BASE_ADDR_SIZE {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Base(BaseAddress::new(
network,
&read_addr_cred(4, 1),
&read_addr_cred(5, 1 + HASH_LEN),
))
}
// pointer
0b0100 | 0b0101 => {
// header + keyhash + 3 natural numbers (min 1 byte each)
const PTR_ADDR_MIN_SIZE: usize = 1 + HASH_LEN + 1 + 1 + 1;
if data.len() < PTR_ADDR_MIN_SIZE {
// possibly more, but depends on how many bytes the natural numbers are for the pointer
return Err(
cbor_event::Error::NotEnough(data.len(), PTR_ADDR_MIN_SIZE).into()
);
}
let mut byte_index = 1;
let payment_cred = read_addr_cred(4, 1);
byte_index += HASH_LEN;
let (slot, slot_bytes) =
variable_nat_decode(&data[byte_index..]).ok_or(DeserializeError::new(
"Address.Pointer.slot",
DeserializeFailure::VariableLenNatDecodeFailed,
))?;
byte_index += slot_bytes;
let (tx_index, tx_bytes) =
variable_nat_decode(&data[byte_index..]).ok_or(DeserializeError::new(
"Address.Pointer.tx_index",
DeserializeFailure::VariableLenNatDecodeFailed,
))?;
byte_index += tx_bytes;
let (cert_index, cert_bytes) =
variable_nat_decode(&data[byte_index..]).ok_or(DeserializeError::new(
"Address.Pointer.cert_index",
DeserializeFailure::VariableLenNatDecodeFailed,
))?;
byte_index += cert_bytes;
if byte_index < data.len() {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Ptr(PointerAddress::new(
network,
&payment_cred,
&Pointer::new_pointer(
&to_bignum(slot),
&to_bignum(tx_index),
&to_bignum(cert_index),
),
))
}
// enterprise
0b0110 | 0b0111 => {
const ENTERPRISE_ADDR_SIZE: usize = 1 + HASH_LEN;
if data.len() < ENTERPRISE_ADDR_SIZE {
return Err(
cbor_event::Error::NotEnough(data.len(), ENTERPRISE_ADDR_SIZE).into(),
);
}
if data.len() > ENTERPRISE_ADDR_SIZE {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Enterprise(EnterpriseAddress::new(network, &read_addr_cred(4, 1)))
}
// reward
0b1110 | 0b1111 => {
const REWARD_ADDR_SIZE: usize = 1 + HASH_LEN;
if data.len() < REWARD_ADDR_SIZE {
return Err(
cbor_event::Error::NotEnough(data.len(), REWARD_ADDR_SIZE).into()
);
}
if data.len() > REWARD_ADDR_SIZE {
return Err(cbor_event::Error::TrailingData.into());
}
AddrType::Reward(RewardAddress::new(network, &read_addr_cred(4, 1)))
}
// byron
0b1000 => {
// note: 0b1000 was chosen because all existing Byron addresses actually start with 0b1000
// Therefore you can re-use Byron addresses as-is
match ByronAddress::from_bytes(data.to_vec()) {
Ok(addr) => AddrType::Byron(addr),
Err(e) => {
return Err(cbor_event::Error::CustomError(
e.as_string().unwrap_or_default(),
)
.into())
}
}
}
_ => return Err(DeserializeFailure::BadAddressType(header).into()),
};
Ok(Address(addr))
})()
.map_err(|e| e.annotate("Address"))
}
pub fn to_bech32(&self, prefix: Option<String>) -> Result<String, JsError> {
let final_prefix = match prefix {
Some(prefix) => prefix,
None => {
// see CIP5 for bech32 prefix rules
let prefix_header = match &self.0 {
AddrType::Reward(_) => "stake",
_ => "addr",
};
let prefix_tail = match self.network_id()? {
id if id == NetworkInfo::testnet().network_id() => "_test",
_ => "",
};
format!("{}{}", prefix_header, prefix_tail)
}
};
bech32::encode(&final_prefix, self.to_bytes().to_base32())
.map_err(|e| JsError::from_str(&format! {"{:?}", e}))
}
pub fn from_bech32(bech_str: &str) -> Result<Address, 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_impl(data.as_ref())?)
}
pub fn network_id(&self) -> Result<u8, JsError> {
match &self.0 {
AddrType::Base(a) => Ok(a.network),
AddrType::Enterprise(a) => Ok(a.network),
AddrType::Ptr(a) => Ok(a.network),
AddrType::Reward(a) => Ok(a.network),
AddrType::Byron(a) => a.network_id(),
}
}
}
impl cbor_event::se::Serialize for Address {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_bytes(self.to_bytes())
}
}
impl Deserialize for Address {
fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
Self::from_bytes_impl(raw.bytes()?.as_ref())
}
}
#[wasm_bindgen]
#[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct BaseAddress {
network: u8,
payment: StakeCredential,
stake: StakeCredential,
}
#[wasm_bindgen]
impl BaseAddress {
pub fn new(network: u8, payment: &StakeCredential, stake: &StakeCredential) -> Self {
Self {
network,
payment: payment.clone(),
stake: stake.clone(),
}
}
pub fn payment_cred(&self) -> StakeCredential {
self.payment.clone()
}
pub fn stake_cred(&self) -> StakeCredential {
self.stake.clone()
}
pub fn to_address(&self) -> Address {
Address(AddrType::Base(self.clone()))
}
pub fn from_address(addr: &Address) -> Option<BaseAddress> {
match &addr.0 {
AddrType::Base(base) => Some(base.clone()),
_ => None,
}
}
}
#[wasm_bindgen]
#[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct EnterpriseAddress {
network: u8,
payment: StakeCredential,
}
#[wasm_bindgen]
impl EnterpriseAddress {
pub fn new(network: u8, payment: &StakeCredential) -> Self {
Self {
network,
payment: payment.clone(),
}
}
pub fn payment_cred(&self) -> StakeCredential {
self.payment.clone()
}
pub fn to_address(&self) -> Address {
Address(AddrType::Enterprise(self.clone()))
}
pub fn from_address(addr: &Address) -> Option<EnterpriseAddress> {
match &addr.0 {
AddrType::Enterprise(enterprise) => Some(enterprise.clone()),
_ => None,
}
}
}
#[wasm_bindgen]
#[derive(Debug, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RewardAddress {
network: u8,
payment: StakeCredential,
}
#[wasm_bindgen]
impl RewardAddress {
pub fn new(network: u8, payment: &StakeCredential) -> Self {
Self {
network,
payment: payment.clone(),
}
}
pub fn payment_cred(&self) -> StakeCredential {
self.payment.clone()
}
pub fn to_address(&self) -> Address {
Address(AddrType::Reward(self.clone()))
}
pub fn from_address(addr: &Address) -> Option<RewardAddress> {
match &addr.0 {
AddrType::Reward(reward) => Some(reward.clone()),
_ => None,
}
}
}
impl serde::Serialize for RewardAddress {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let bech32 = self
.to_address()
.to_bech32(None)
.map_err(|e| serde::ser::Error::custom(format!("to_bech32: {:?}", e)))?;
serializer.serialize_str(&bech32)
}
}
impl<'de> serde::de::Deserialize<'de> for RewardAddress {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let bech32 = <String as serde::de::Deserialize>::deserialize(deserializer)?;
match Address::from_bech32(&bech32)
.ok()
.map(|addr| RewardAddress::from_address(&addr))
{
Some(Some(ra)) => Ok(ra),
_ => Err(serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&bech32),
&"bech32 reward address string",
)),
}
}
sourcepub fn network_id(&self) -> Result<u8, JsError>
pub fn network_id(&self) -> Result<u8, JsError>
Examples found in repository?
src/address.rs (line 583)
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
pub fn to_bech32(&self, prefix: Option<String>) -> Result<String, JsError> {
let final_prefix = match prefix {
Some(prefix) => prefix,
None => {
// see CIP5 for bech32 prefix rules
let prefix_header = match &self.0 {
AddrType::Reward(_) => "stake",
_ => "addr",
};
let prefix_tail = match self.network_id()? {
id if id == NetworkInfo::testnet().network_id() => "_test",
_ => "",
};
format!("{}{}", prefix_header, prefix_tail)
}
};
bech32::encode(&final_prefix, self.to_bytes().to_base32())
.map_err(|e| JsError::from_str(&format! {"{:?}", e}))
}
Trait Implementations§
source§impl<'de> Deserialize<'de> for Address
impl<'de> Deserialize<'de> for Address
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 Deserialize for Address
impl Deserialize for Address
fn deserialize<R: BufRead>(
raw: &mut Deserializer<R>
) -> Result<Self, DeserializeError>
source§impl JsonSchema for Address
impl JsonSchema for Address
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 moresource§impl Ord for Address
impl Ord for Address
source§impl PartialEq<Address> for Address
impl PartialEq<Address> for Address
source§impl PartialOrd<Address> for Address
impl PartialOrd<Address> for Address
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 more