feat(primitives): Enable serde of ledger structs (#169)

This commit is contained in:
Santiago Carmuega 2022-08-12 19:43:56 -03:00 committed by GitHub
parent 1f0eb3bfc0
commit 9845fc4040
22 changed files with 584 additions and 270 deletions

View file

@ -12,7 +12,7 @@ pub type Blake2b224 = Hash<28>;
pub type AddressId = Blake2b224; pub type AddressId = Blake2b224;
pub type StakeholderId = Blake2b224; pub type StakeholderId = Blake2b224;
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum AddrDistr { pub enum AddrDistr {
Variant0(StakeholderId), Variant0(StakeholderId),
Variant1, Variant1,
@ -57,7 +57,7 @@ impl minicbor::Encode<()> for AddrDistr {
} }
} }
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum AddrType { pub enum AddrType {
PubKey, PubKey,
Script, Script,
@ -98,7 +98,7 @@ impl<C> minicbor::Encode<C> for AddrType {
} }
} }
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum AddrAttrProperty { pub enum AddrAttrProperty {
AddrDistr(AddrDistr), AddrDistr(AddrDistr),
Bytes(ByteVec), Bytes(ByteVec),
@ -148,7 +148,7 @@ impl<C> minicbor::Encode<C> for AddrAttrProperty {
pub type AddrAttr = OrderPreservingProperties<AddrAttrProperty>; pub type AddrAttr = OrderPreservingProperties<AddrAttrProperty>;
#[derive(Debug, Encode, Decode, Clone, PartialEq, PartialOrd)] #[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, PartialOrd)]
pub struct AddressPayload { pub struct AddressPayload {
#[n(0)] #[n(0)]
pub root: AddressId, pub root: AddressId,
@ -161,7 +161,7 @@ pub struct AddressPayload {
} }
/// New type wrapping a Byron address primitive /// New type wrapping a Byron address primitive
#[derive(Debug, Encode, Decode, Clone, PartialEq, PartialOrd)] #[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ByronAddress { pub struct ByronAddress {
#[n(0)] #[n(0)]
payload: TagWrap<ByteVec, 24>, payload: TagWrap<ByteVec, 24>,

View file

@ -63,7 +63,7 @@ pub type TxIdx = u64;
pub type CertIdx = u64; pub type CertIdx = u64;
/// An on-chain pointer to a stake key /// An on-chain pointer to a stake key
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Pointer(Slot, TxIdx, CertIdx); pub struct Pointer(Slot, TxIdx, CertIdx);
fn slice_to_hash(slice: &[u8]) -> Result<Hash<28>, Error> { fn slice_to_hash(slice: &[u8]) -> Result<Hash<28>, Error> {
@ -113,7 +113,7 @@ impl Pointer {
} }
/// The payment part of a Shelley address /// The payment part of a Shelley address
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub enum ShelleyPaymentPart { pub enum ShelleyPaymentPart {
Key(PaymentKeyHash), Key(PaymentKeyHash),
Script(ScriptHash), Script(ScriptHash),
@ -151,7 +151,7 @@ impl ShelleyPaymentPart {
} }
/// The delegation part of a Shelley address /// The delegation part of a Shelley address
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub enum ShelleyDelegationPart { pub enum ShelleyDelegationPart {
Key(StakeKeyHash), Key(StakeKeyHash),
Script(ScriptHash), Script(ScriptHash),
@ -212,7 +212,7 @@ impl StakePayload {
} }
/// The network tag of an address /// The network tag of an address
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub enum Network { pub enum Network {
Testnet, Testnet,
Mainnet, Mainnet,
@ -230,24 +230,24 @@ impl From<u8> for Network {
} }
/// A decoded Shelley address /// A decoded Shelley address
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub struct ShelleyAddress(Network, ShelleyPaymentPart, ShelleyDelegationPart); pub struct ShelleyAddress(Network, ShelleyPaymentPart, ShelleyDelegationPart);
/// The payload of a Stake address /// The payload of a Stake address
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub enum StakePayload { pub enum StakePayload {
Stake(StakeKeyHash), Stake(StakeKeyHash),
Script(ScriptHash), Script(ScriptHash),
} }
/// A decoded Stake address /// A decoded Stake address
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub struct StakeAddress(Network, StakePayload); pub struct StakeAddress(Network, StakePayload);
pub use byron::ByronAddress; pub use byron::ByronAddress;
/// A decoded Cardano address of any type /// A decoded Cardano address of any type
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub enum Address { pub enum Address {
Byron(ByronAddress), Byron(ByronAddress),
Shelley(ShelleyAddress), Shelley(ShelleyAddress),
@ -345,7 +345,7 @@ parse_stake_fn!(parse_type_14, stake_key);
parse_stake_fn!(parse_type_15, script); parse_stake_fn!(parse_type_15, script);
fn bytes_to_address(bytes: &[u8]) -> Result<Address, Error> { fn bytes_to_address(bytes: &[u8]) -> Result<Address, Error> {
let header = *bytes.get(0).ok_or(Error::MissingHeader)?; let header = *bytes.first().ok_or(Error::MissingHeader)?;
let payload = &bytes[1..]; let payload = &bytes[1..];
match header & 0b1111_0000 { match header & 0b1111_0000 {

View file

@ -13,5 +13,7 @@ authors = [
] ]
[dependencies] [dependencies]
hex = "0.4.3"
minicbor = { version = "0.17", features = ["std", "half", "derive"] } minicbor = { version = "0.17", features = ["std", "half", "derive"] }
serde = { version = "1.0.143", features = ["derive"] }

View file

@ -1,6 +1,6 @@
use std::ops::Deref;
use minicbor::{data::Tag, Decode, Encode}; use minicbor::{data::Tag, Decode, Encode};
use serde::{Deserialize, Serialize};
use std::ops::Deref;
/// Utility for skipping parts of the CBOR payload, use only for debugging /// Utility for skipping parts of the CBOR payload, use only for debugging
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord)] #[derive(Debug, PartialEq, PartialOrd, Eq, Ord)]
@ -43,6 +43,21 @@ pub enum KeyValuePairs<K, V> {
Indef(Vec<(K, V)>), Indef(Vec<(K, V)>),
} }
impl<K, V> KeyValuePairs<K, V> {
pub fn to_vec(self) -> Vec<(K, V)> {
self.into()
}
}
impl<K, V> From<KeyValuePairs<K, V>> for Vec<(K, V)> {
fn from(other: KeyValuePairs<K, V>) -> Self {
match other {
KeyValuePairs::Def(x) => x,
KeyValuePairs::Indef(x) => x,
}
}
}
impl<K, V> Deref for KeyValuePairs<K, V> { impl<K, V> Deref for KeyValuePairs<K, V> {
type Target = Vec<(K, V)>; type Target = Vec<(K, V)>;
@ -117,6 +132,12 @@ pub enum MaybeIndefArray<A> {
Indef(Vec<A>), Indef(Vec<A>),
} }
impl<A> MaybeIndefArray<A> {
pub fn to_vec(self) -> Vec<A> {
self.into()
}
}
impl<A> Deref for MaybeIndefArray<A> { impl<A> Deref for MaybeIndefArray<A> {
type Target = Vec<A>; type Target = Vec<A>;
@ -128,6 +149,15 @@ impl<A> Deref for MaybeIndefArray<A> {
} }
} }
impl<A> From<MaybeIndefArray<A>> for Vec<A> {
fn from(other: MaybeIndefArray<A>) -> Self {
match other {
MaybeIndefArray::Def(x) => x,
MaybeIndefArray::Indef(x) => x,
}
}
}
impl<'b, C, A> minicbor::decode::Decode<'b, C> for MaybeIndefArray<A> impl<'b, C, A> minicbor::decode::Decode<'b, C> for MaybeIndefArray<A>
where where
A: minicbor::decode::Decode<'b, C>, A: minicbor::decode::Decode<'b, C>,
@ -186,7 +216,7 @@ where
/// transform key-value structures into an orderer vec of `properties`, where /// transform key-value structures into an orderer vec of `properties`, where
/// each entry represents a a cbor-encodable variant of an attribute of the /// each entry represents a a cbor-encodable variant of an attribute of the
/// struct. /// struct.
#[derive(Debug, PartialEq, Clone, PartialOrd)] #[derive(Debug, PartialEq, Eq, Clone, PartialOrd)]
pub struct OrderPreservingProperties<P>(Vec<P>); pub struct OrderPreservingProperties<P>(Vec<P>);
impl<P> Deref for OrderPreservingProperties<P> { impl<P> Deref for OrderPreservingProperties<P> {
@ -229,7 +259,8 @@ where
} }
/// Wraps a struct so that it is encoded/decoded as a cbor bytes /// Wraps a struct so that it is encoded/decoded as a cbor bytes
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd)]
#[serde(transparent)]
pub struct CborWrap<T>(pub T); pub struct CborWrap<T>(pub T);
impl<'b, C, T> minicbor::Decode<'b, C> for CborWrap<T> impl<'b, C, T> minicbor::Decode<'b, C> for CborWrap<T>
@ -273,7 +304,7 @@ impl<T> Deref for CborWrap<T> {
} }
} }
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct TagWrap<I, const T: u64>(pub I); pub struct TagWrap<I, const T: u64>(pub I);
impl<I, const T: u64> TagWrap<I, T> { impl<I, const T: u64> TagWrap<I, T> {
@ -526,7 +557,7 @@ impl From<&AnyUInt> for u64 {
/// let confirm: (u16, u16) = minicbor::decode(keeper.raw_cbor()).unwrap(); /// let confirm: (u16, u16) = minicbor::decode(keeper.raw_cbor()).unwrap();
/// assert_eq!(confirm, (456u16, 789u16)); /// assert_eq!(confirm, (456u16, 789u16));
/// ``` /// ```
#[derive(Debug, PartialEq, PartialOrd, Clone)] #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct KeepRaw<'b, T> { pub struct KeepRaw<'b, T> {
raw: &'b [u8], raw: &'b [u8],
inner: T, inner: T,
@ -536,6 +567,10 @@ impl<'b, T> KeepRaw<'b, T> {
pub fn raw_cbor(&self) -> &'b [u8] { pub fn raw_cbor(&self) -> &'b [u8] {
self.raw self.raw
} }
pub fn unwrap(self) -> T {
self.inner
}
} }
impl<'b, T> Deref for KeepRaw<'b, T> { impl<'b, T> Deref for KeepRaw<'b, T> {
@ -575,16 +610,37 @@ impl<C, T> minicbor::Encode<C> for KeepRaw<'_, T> {
} }
} }
#[derive(Clone, Debug)] #[derive(Serialize, Deserialize, Clone, Debug)]
pub enum Nullable<T> { #[serde(from = "Option::<T>", into = "Option::<T>")]
pub enum Nullable<T>
where
T: std::clone::Clone,
{
Some(T), Some(T),
Null, Null,
Undefined, Undefined,
} }
impl<T> Nullable<T>
where
T: std::clone::Clone,
{
pub fn map<F, O>(self, f: F) -> Nullable<O>
where
O: std::clone::Clone,
F: Fn(T) -> O,
{
match self {
Nullable::Some(x) => Nullable::Some(f(x)),
Nullable::Null => Nullable::Null,
Nullable::Undefined => Nullable::Undefined,
}
}
}
impl<'b, C, T> minicbor::Decode<'b, C> for Nullable<T> impl<'b, C, T> minicbor::Decode<'b, C> for Nullable<T>
where where
T: minicbor::Decode<'b, C>, T: minicbor::Decode<'b, C> + std::clone::Clone,
{ {
fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> { fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
match d.datatype()? { match d.datatype()? {
@ -606,7 +662,7 @@ where
impl<C, T> minicbor::Encode<C> for Nullable<T> impl<C, T> minicbor::Encode<C> for Nullable<T>
where where
T: minicbor::Encode<C>, T: minicbor::Encode<C> + std::clone::Clone,
{ {
fn encode<W: minicbor::encode::Write>( fn encode<W: minicbor::encode::Write>(
&self, &self,
@ -630,7 +686,10 @@ where
} }
} }
impl<T> From<Option<T>> for Nullable<T> { impl<T> From<Option<T>> for Nullable<T>
where
T: std::clone::Clone,
{
fn from(x: Option<T>) -> Self { fn from(x: Option<T>) -> Self {
match x { match x {
Some(x) => Nullable::Some(x), Some(x) => Nullable::Some(x),
@ -638,3 +697,92 @@ impl<T> From<Option<T>> for Nullable<T> {
} }
} }
} }
impl<T> From<Nullable<T>> for Option<T>
where
T: std::clone::Clone,
{
fn from(other: Nullable<T>) -> Self {
match other {
Nullable::Some(x) => Some(x),
_ => None,
}
}
}
#[derive(Serialize, Deserialize, Clone, Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cbor(transparent)]
#[serde(into = "String")]
#[serde(try_from = "String")]
pub struct Bytes(#[n(0)] minicbor::bytes::ByteVec);
impl From<Vec<u8>> for Bytes {
fn from(xs: Vec<u8>) -> Self {
Bytes(minicbor::bytes::ByteVec::from(xs))
}
}
impl From<Bytes> for Vec<u8> {
fn from(b: Bytes) -> Self {
b.0.into()
}
}
impl Deref for Bytes {
type Target = Vec<u8>;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
impl TryFrom<String> for Bytes {
type Error = hex::FromHexError;
fn try_from(value: String) -> Result<Self, Self::Error> {
let v = hex::decode(value)?;
Ok(Bytes(minicbor::bytes::ByteVec::from(v)))
}
}
impl From<Bytes> for String {
fn from(b: Bytes) -> Self {
hex::encode(b.deref())
}
}
#[derive(Serialize, Deserialize, Clone, Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cbor(transparent)]
#[serde(into = "i128")]
#[serde(try_from = "i128")]
pub struct Int(#[n(0)] pub minicbor::data::Int);
impl Deref for Int {
type Target = minicbor::data::Int;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<Int> for i128 {
fn from(value: Int) -> Self {
i128::from(value.0)
}
}
impl From<i64> for Int {
fn from(x: i64) -> Self {
let inner = minicbor::data::Int::from(x);
Self(inner)
}
}
impl TryFrom<i128> for Int {
type Error = minicbor::data::TryFromIntError;
fn try_from(value: i128) -> Result<Self, Self::Error> {
let inner = minicbor::data::Int::try_from(value)?;
Ok(Self(inner))
}
}

View file

@ -18,8 +18,10 @@ cryptoxide = { version = "0.4.1" }
thiserror = "1.0" thiserror = "1.0"
rand_core = "0.6" rand_core = "0.6"
pallas-codec = { version = "0.13.0", path = "../pallas-codec" } pallas-codec = { version = "0.13.0", path = "../pallas-codec" }
serde = "1.0.143"
[dev-dependencies] [dev-dependencies]
quickcheck = "1.0" quickcheck = "1.0"
quickcheck_macros = "1.0" quickcheck_macros = "1.0"
rand = "0.8" rand = "0.8"
serde_test = "1.0.143"

View file

@ -2,10 +2,9 @@
//! //!
//! we expose two helper objects: //! we expose two helper objects:
//! //!
//! * [`Hasher`] to help streaming objects or bytes into a hasher //! * [`Hasher`] to help streaming objects or bytes into a hasher and computing
//! and computing a hash without allocating extra memory due to //! a hash without allocating extra memory due to the required **CBOR**
//! the required **CBOR** encoding for everything by the cardano //! encoding for everything by the cardano protocol
//! protocol
//! * [`struct@Hash`] a conveniently strongly typed byte array //! * [`struct@Hash`] a conveniently strongly typed byte array
//! //!
//! The algorithm exposed here is `Blake2b`. We currently support two //! The algorithm exposed here is `Blake2b`. We currently support two
@ -30,5 +29,6 @@
#[allow(clippy::module_inception)] #[allow(clippy::module_inception)]
mod hash; mod hash;
mod hasher; mod hasher;
mod serde;
pub use self::{hash::Hash, hasher::Hasher}; pub use self::{hash::Hash, hasher::Hasher};

View file

@ -0,0 +1,97 @@
use std::fmt;
use std::str::FromStr;
use serde::de::{Error, Unexpected, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use super::Hash;
impl<const BYTES: usize> Serialize for Hash<BYTES> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
struct HashVisitor<const BYTES: usize> {}
impl<'de, const BYTES: usize> Visitor<'de> for HashVisitor<BYTES> {
type Value = Hash<BYTES>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a hex string representing {} bytes", BYTES)
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
match Hash::<BYTES>::from_str(s) {
Ok(x) => Ok(x),
Err(_) => Err(Error::invalid_value(Unexpected::Str(s), &self)),
}
}
}
impl<'de, const BYTES: usize> Deserialize<'de> for Hash<BYTES> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(HashVisitor::<BYTES> {})
}
}
#[cfg(test)]
mod tests {
use serde_test::{assert_de_tokens_error, assert_tokens, Token};
use super::*;
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
struct Dummy {
hash1: Hash<28>,
hash2: Hash<32>,
}
#[test]
fn output_tokens() {
let dummy = Dummy {
hash1: "276fd18711931e2c0e21430192dbeac0e458093cd9d1fcd7210f64b3"
.parse()
.unwrap(),
hash2: "0d8d00cdd4657ac84d82f0a56067634a7adfdf43da41cb534bcaa45060973d21"
.parse()
.unwrap(),
};
assert_tokens(
&dummy,
&[
Token::Struct {
name: "Dummy",
len: 2,
},
Token::Str("hash1"),
Token::Str("276fd18711931e2c0e21430192dbeac0e458093cd9d1fcd7210f64b3"),
Token::Str("hash2"),
Token::Str("0d8d00cdd4657ac84d82f0a56067634a7adfdf43da41cb534bcaa45060973d21"),
Token::StructEnd,
],
);
}
#[test]
fn invalid_str() {
assert_de_tokens_error::<Dummy>(
&[
Token::Map { len: Some(2) },
Token::Str("hash1"),
Token::Str("27"),
],
"invalid value: string \"27\", expected a hex string representing 28 bytes",
);
}
}

View file

@ -5,7 +5,7 @@ use crate::common::Point;
use pallas_codec::minicbor::{decode, encode, Decode, Decoder, Encode, Encoder}; use pallas_codec::minicbor::{decode, encode, Decode, Decoder, Encode, Encoder};
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub enum State { pub enum State {
Idle, Idle,
Busy, Busy,

View file

@ -10,7 +10,7 @@ use crate::common::Point;
use super::{BlockContent, HeaderContent, Message, SkippedContent, State, Tip}; use super::{BlockContent, HeaderContent, Message, SkippedContent, State, Tip};
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq, Eq)]
pub enum Continuation { pub enum Continuation {
Proceed, Proceed,
DropOut, DropOut,

View file

@ -5,7 +5,7 @@ use crate::common::Point;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Tip(pub Point, pub u64); pub struct Tip(pub Point, pub u64);
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub enum State { pub enum State {
Idle, Idle,
CanAwait, CanAwait,

View file

@ -9,7 +9,7 @@ use crate::machines::{Agent, MachineError, Transition};
use crate::common::Point; use crate::common::Point;
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub enum State { pub enum State {
Idle, Idle,
Acquiring, Acquiring,

View file

@ -8,14 +8,14 @@ type Slot = u64;
type TxId = String; type TxId = String;
type Tx = String; type Tx = String;
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub enum StBusyKind { pub enum StBusyKind {
NextTx, NextTx,
HasTx, HasTx,
GetSizes, GetSizes,
} }
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub enum State { pub enum State {
StIdle, StIdle,
StAcquiring, StAcquiring,
@ -24,7 +24,7 @@ pub enum State {
StDone, StDone,
} }
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub struct MempoolSizeAndCapacity { pub struct MempoolSizeAndCapacity {
pub capacity_in_bytes: u32, pub capacity_in_bytes: u32,
pub size_in_bytes: u32, pub size_in_bytes: u32,

View file

@ -6,7 +6,7 @@ use pallas_codec::minicbor::{decode, encode, Decode, Decoder, Encode, Encoder};
use crate::machines::{Agent, MachineError, Transition}; use crate::machines::{Agent, MachineError, Transition};
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub enum State { pub enum State {
Idle, Idle,
TxIdsNonBlocking, TxIdsNonBlocking,

View file

@ -20,8 +20,8 @@ pallas-crypto = { version = "0.13.0", path = "../pallas-crypto" }
pallas-codec = { version = "0.13.0", path = "../pallas-codec" } pallas-codec = { version = "0.13.0", path = "../pallas-codec" }
base58 = "0.2.0" base58 = "0.2.0"
bech32 = "0.9.0" bech32 = "0.9.0"
serde = { version ="1.0.136", optional = true } serde = { version = "1.0.136", optional = true, features = ["derive"] }
serde_json = { version ="1.0.79", optional = true } serde_json = { version = "1.0.79", optional = true }
[features] [features]
json = ["serde", "serde_json"] json = ["serde", "serde_json"]

View file

@ -51,8 +51,7 @@ mod tests {
use std::str::FromStr; use std::str::FromStr;
use pallas_codec::minicbor; use pallas_codec::minicbor;
use pallas_codec::minicbor::data::Int; use pallas_codec::utils::Int;
use pallas_codec::utils::MaybeIndefArray;
use pallas_crypto::hash::Hash; use pallas_crypto::hash::Hash;
use crate::alonzo::{BigInt, Constr, MintedBlock, NativeScript, PlutusData, PlutusScript}; use crate::alonzo::{BigInt, Constr, MintedBlock, NativeScript, PlutusData, PlutusScript};
@ -88,13 +87,13 @@ mod tests {
#[test] #[test]
fn native_script_hashes_as_cardano_cli() { fn native_script_hashes_as_cardano_cli() {
// construct an arbitrary script to use as example // construct an arbitrary script to use as example
let ns = NativeScript::ScriptAll(MaybeIndefArray::Def(vec![ let ns = NativeScript::ScriptAll(vec![
NativeScript::ScriptPubkey( NativeScript::ScriptPubkey(
Hash::<28>::from_str("4d04380dcb9fbad5aff8e2f4e19394ef4e5e11b37932838f01984a12") Hash::<28>::from_str("4d04380dcb9fbad5aff8e2f4e19394ef4e5e11b37932838f01984a12")
.unwrap(), .unwrap(),
), ),
NativeScript::InvalidBefore(112500819), NativeScript::InvalidBefore(112500819),
])); ]);
// hash that we assume correct since it was generated through the cardano-cli // hash that we assume correct since it was generated through the cardano-cli
let cardano_cli_output = "d6a8ced01ecdfbb26c90850010a06fbc20a7c23632fc92f531667f36"; let cardano_cli_output = "d6a8ced01ecdfbb26c90850010a06fbc20a7c23632fc92f531667f36";
@ -111,26 +110,26 @@ mod tests {
let pd = PlutusData::Constr(Constr::<PlutusData> { let pd = PlutusData::Constr(Constr::<PlutusData> {
tag: 1280, tag: 1280,
any_constructor: None, any_constructor: None,
fields: MaybeIndefArray::Indef(vec![ fields: vec![
PlutusData::BigInt(BigInt::Int(Int::from(4))), PlutusData::BigInt(BigInt::Int(Int::from(4))),
PlutusData::Constr(Constr::<PlutusData> { PlutusData::Constr(Constr::<PlutusData> {
tag: 124, tag: 124,
any_constructor: None, any_constructor: None,
fields: MaybeIndefArray::Indef(vec![ fields: vec![
PlutusData::BigInt(BigInt::Int(Int::from(-4))), PlutusData::BigInt(BigInt::Int(Int::from(-4))),
PlutusData::Constr(Constr::<PlutusData> { PlutusData::Constr(Constr::<PlutusData> {
tag: 102, tag: 102,
any_constructor: Some(453), any_constructor: Some(453),
fields: MaybeIndefArray::Indef(vec![ fields: vec![
PlutusData::BigInt(BigInt::Int(Int::from(2))), PlutusData::BigInt(BigInt::Int(Int::from(2))),
PlutusData::BigInt(BigInt::Int(Int::from(3434))), PlutusData::BigInt(BigInt::Int(Int::from(3434))),
]), ],
}), }),
PlutusData::BigInt(BigInt::Int(Int::from(-11828293))), PlutusData::BigInt(BigInt::Int(Int::from(-11828293))),
]), ],
}), }),
PlutusData::BigInt(BigInt::Int(Int::from(11828293))), PlutusData::BigInt(BigInt::Int(Int::from(11828293))),
]), ],
}); });
// if you need to try this out in the cardano-cli, uncomment this line to see // if you need to try this out in the cardano-cli, uncomment this line to see

View file

@ -1,3 +1,5 @@
use std::ops::Deref;
use serde_json::json; use serde_json::json;
use crate::ToCanonicalJson; use crate::ToCanonicalJson;
@ -29,9 +31,11 @@ impl ToCanonicalJson for super::PlutusData {
json!({ "map": map }) json!({ "map": map })
} }
super::PlutusData::BigInt(int) => match int { super::PlutusData::BigInt(int) => match int {
super::BigInt::Int(n) => match i64::try_from(*n) { super::BigInt::Int(n) => match i64::try_from(*n.deref()) {
Ok(x) => json!({ "int": x }), Ok(x) => json!({ "int": x }),
Err(_) => json!({ "bignint": hex::encode(i128::from(*n).to_be_bytes()) }), Err(_) => {
json!({ "bignint": hex::encode(i128::from(*n.deref()).to_be_bytes()) })
}
}, },
// WARNING / TODO: the CDDL shows a bignum variants of arbitrary length expressed as // WARNING / TODO: the CDDL shows a bignum variants of arbitrary length expressed as
// bytes, but I can't find the corresponding mapping to JSON in the // bytes, but I can't find the corresponding mapping to JSON in the
@ -46,10 +50,6 @@ impl ToCanonicalJson for super::PlutusData {
let list: Vec<_> = x.iter().map(|i| i.to_json()).collect(); let list: Vec<_> = x.iter().map(|i| i.to_json()).collect();
json!({ "list": list }) json!({ "list": list })
} }
super::PlutusData::ArrayIndef(x) => {
let list: Vec<_> = x.iter().map(|i| i.to_json()).collect();
json!({ "list": list })
}
} }
} }
} }

View file

@ -2,18 +2,22 @@
//! //!
//! Handcrafted, idiomatic rust artifacts based on based on the [Alonzo CDDL](https://github.com/input-output-hk/cardano-ledger/blob/master/eras/alonzo/test-suite/cddl-files/alonzo.cddl) file in IOHK repo. //! Handcrafted, idiomatic rust artifacts based on based on the [Alonzo CDDL](https://github.com/input-output-hk/cardano-ledger/blob/master/eras/alonzo/test-suite/cddl-files/alonzo.cddl) file in IOHK repo.
use pallas_codec::minicbor::{bytes::ByteVec, data::Int, data::Tag, Decode, Encode}; use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use pallas_codec::minicbor::{data::Tag, Decode, Encode};
use pallas_crypto::hash::Hash; use pallas_crypto::hash::Hash;
use pallas_codec::utils::{AnyUInt, KeepRaw, KeyValuePairs, MaybeIndefArray, Nullable}; use pallas_codec::utils::{Bytes, Int, KeepRaw, KeyValuePairs, MaybeIndefArray, Nullable};
// required for derive attrs to work // required for derive attrs to work
use pallas_codec::minicbor; use pallas_codec::minicbor;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct VrfCert(#[n(0)] pub ByteVec, #[n(1)] pub ByteVec); pub struct VrfCert(#[n(0)] pub Bytes, #[n(1)] pub Bytes);
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct HeaderBody { pub struct HeaderBody {
#[n(0)] #[n(0)]
pub block_number: u64, pub block_number: u64,
@ -25,10 +29,10 @@ pub struct HeaderBody {
pub prev_hash: Option<Hash<32>>, pub prev_hash: Option<Hash<32>>,
#[n(3)] #[n(3)]
pub issuer_vkey: ByteVec, pub issuer_vkey: Bytes,
#[n(4)] #[n(4)]
pub vrf_vkey: ByteVec, pub vrf_vkey: Bytes,
#[n(5)] #[n(5)]
pub nonce_vrf: VrfCert, pub nonce_vrf: VrfCert,
@ -43,7 +47,7 @@ pub struct HeaderBody {
pub block_body_hash: Hash<32>, pub block_body_hash: Hash<32>,
#[n(9)] #[n(9)]
pub operational_cert_hot_vkey: ByteVec, pub operational_cert_hot_vkey: Bytes,
#[n(10)] #[n(10)]
pub operational_cert_sequence_number: u64, pub operational_cert_sequence_number: u64,
@ -52,7 +56,7 @@ pub struct HeaderBody {
pub operational_cert_kes_period: u64, pub operational_cert_kes_period: u64,
#[n(12)] #[n(12)]
pub operational_cert_sigma: ByteVec, pub operational_cert_sigma: Bytes,
#[n(13)] #[n(13)]
pub protocol_major: u64, pub protocol_major: u64,
@ -63,19 +67,19 @@ pub struct HeaderBody {
pub type ProtocolVersion = (u64, u64); pub type ProtocolVersion = (u64, u64);
#[derive(Encode, Decode, Debug, PartialEq)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq)]
pub struct KesSignature {} pub struct KesSignature {}
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct Header { pub struct Header {
#[n(0)] #[n(0)]
pub header_body: HeaderBody, pub header_body: HeaderBody,
#[n(1)] #[n(1)]
pub body_signature: ByteVec, pub body_signature: Bytes,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct TransactionInput { pub struct TransactionInput {
#[n(0)] #[n(0)]
pub transaction_id: Hash<32>, pub transaction_id: Hash<32>,
@ -86,7 +90,7 @@ pub struct TransactionInput {
// $nonce /= [ 0 // 1, bytes .size 32 ] // $nonce /= [ 0 // 1, bytes .size 32 ]
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
#[cbor(index_only)] #[cbor(index_only)]
pub enum NonceVariant { pub enum NonceVariant {
#[n(0)] #[n(0)]
@ -96,7 +100,7 @@ pub enum NonceVariant {
Nonce, Nonce,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct Nonce { pub struct Nonce {
#[n(0)] #[n(0)]
pub variant: NonceVariant, pub variant: NonceVariant,
@ -105,19 +109,19 @@ pub struct Nonce {
pub hash: Option<Hash<32>>, pub hash: Option<Hash<32>>,
} }
pub type ScriptHash = ByteVec; pub type ScriptHash = Bytes;
pub type PolicyId = ScriptHash; pub type PolicyId = Hash<28>;
pub type AssetName = ByteVec; pub type AssetName = Bytes;
pub type Multiasset<A> = KeyValuePairs<PolicyId, KeyValuePairs<AssetName, A>>; pub type Multiasset<A> = BTreeMap<PolicyId, BTreeMap<AssetName, A>>;
pub type Mint = Multiasset<i64>; pub type Mint = Multiasset<i64>;
pub type Coin = AnyUInt; pub type Coin = u64;
#[derive(Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum Value { pub enum Value {
Coin(Coin), Coin(Coin),
Multiasset(Coin, Multiasset<Coin>), Multiasset(Coin, Multiasset<Coin>),
@ -163,10 +167,10 @@ impl<C> minicbor::encode::Encode<C> for Value {
} }
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct TransactionOutput { pub struct TransactionOutput {
#[n(0)] #[n(0)]
pub address: ByteVec, pub address: Bytes,
#[n(1)] #[n(1)]
pub amount: Value, pub amount: Value,
@ -177,8 +181,8 @@ pub struct TransactionOutput {
pub type PoolKeyhash = Hash<28>; pub type PoolKeyhash = Hash<28>;
pub type Epoch = u64; pub type Epoch = u64;
pub type Genesishash = ByteVec; pub type Genesishash = Bytes;
pub type GenesisDelegateHash = ByteVec; pub type GenesisDelegateHash = Bytes;
pub type VrfKeyhash = Hash<32>; pub type VrfKeyhash = Hash<32>;
/* move_instantaneous_reward = [ 0 / 1, { * stake_credential => delta_coin } / coin ] /* move_instantaneous_reward = [ 0 / 1, { * stake_credential => delta_coin } / coin ]
@ -188,7 +192,7 @@ pub type VrfKeyhash = Hash<32>;
; otherwise the funds are given to the other accounting pot. ; otherwise the funds are given to the other accounting pot.
*/ */
#[derive(Debug, PartialEq, PartialOrd, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum InstantaneousRewardSource { pub enum InstantaneousRewardSource {
Reserves, Reserves,
Treasury, Treasury,
@ -226,9 +230,9 @@ impl<C> minicbor::encode::Encode<C> for InstantaneousRewardSource {
} }
} }
#[derive(Debug, PartialEq, PartialOrd, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum InstantaneousRewardTarget { pub enum InstantaneousRewardTarget {
StakeCredentials(KeyValuePairs<StakeCredential, i64>), StakeCredentials(BTreeMap<StakeCredential, i64>),
OtherAccountingPot(Coin), OtherAccountingPot(Coin),
} }
@ -268,7 +272,7 @@ impl<C> minicbor::encode::Encode<C> for InstantaneousRewardTarget {
} }
} }
#[derive(Encode, Decode, Debug, PartialEq, PartialOrd, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
#[cbor] #[cbor]
pub struct MoveInstantaneousReward { pub struct MoveInstantaneousReward {
#[n(0)] #[n(0)]
@ -278,18 +282,18 @@ pub struct MoveInstantaneousReward {
pub target: InstantaneousRewardTarget, pub target: InstantaneousRewardTarget,
} }
pub type RewardAccount = ByteVec; pub type RewardAccount = Bytes;
pub type Withdrawals = KeyValuePairs<RewardAccount, Coin>; pub type Withdrawals = BTreeMap<RewardAccount, Coin>;
pub type RequiredSigners = MaybeIndefArray<AddrKeyhash>; pub type RequiredSigners = Vec<AddrKeyhash>;
pub type Port = u32; pub type Port = u32;
pub type IPv4 = ByteVec; pub type IPv4 = Bytes;
pub type IPv6 = ByteVec; pub type IPv6 = Bytes;
pub type DnsName = String; pub type DnsName = String;
#[derive(Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum Relay { pub enum Relay {
SingleHostAddr(Option<Port>, Option<IPv4>, Option<IPv6>), SingleHostAddr(Option<Port>, Option<IPv4>, Option<IPv6>),
SingleHostName(Option<Port>, DnsName), SingleHostName(Option<Port>, DnsName),
@ -356,7 +360,7 @@ impl<C> minicbor::encode::Encode<C> for Relay {
pub type PoolMetadataHash = Hash<32>; pub type PoolMetadataHash = Hash<32>;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct PoolMetadata { pub struct PoolMetadata {
#[n(0)] #[n(0)]
pub url: String, pub url: String,
@ -368,7 +372,7 @@ pub struct PoolMetadata {
pub type AddrKeyhash = Hash<28>; pub type AddrKeyhash = Hash<28>;
pub type Scripthash = Hash<28>; pub type Scripthash = Hash<28>;
#[derive(Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct RationalNumber { pub struct RationalNumber {
pub numerator: i64, pub numerator: i64,
pub denominator: u64, pub denominator: u64,
@ -406,7 +410,7 @@ pub type UnitInterval = RationalNumber;
pub type PositiveInterval = RationalNumber; pub type PositiveInterval = RationalNumber;
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, PartialOrd, Eq, Ord, Clone)]
pub enum StakeCredential { pub enum StakeCredential {
AddrKeyhash(AddrKeyhash), AddrKeyhash(AddrKeyhash),
Scripthash(Scripthash), Scripthash(Scripthash),
@ -452,7 +456,7 @@ impl<C> minicbor::encode::Encode<C> for StakeCredential {
} }
} }
#[derive(Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum Certificate { pub enum Certificate {
StakeRegistration(StakeCredential), StakeRegistration(StakeCredential),
StakeDeregistration(StakeCredential), StakeDeregistration(StakeCredential),
@ -464,8 +468,8 @@ pub enum Certificate {
cost: Coin, cost: Coin,
margin: UnitInterval, margin: UnitInterval,
reward_account: RewardAccount, reward_account: RewardAccount,
pool_owners: MaybeIndefArray<AddrKeyhash>, pool_owners: Vec<AddrKeyhash>,
relays: MaybeIndefArray<Relay>, relays: Vec<Relay>,
pool_metadata: Option<PoolMetadata>, pool_metadata: Option<PoolMetadata>,
}, },
PoolRetirement(PoolKeyhash, Epoch), PoolRetirement(PoolKeyhash, Epoch),
@ -620,7 +624,7 @@ impl<C> minicbor::encode::Encode<C> for Certificate {
} }
} }
#[derive(Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
#[cbor(index_only)] #[cbor(index_only)]
pub enum NetworkId { pub enum NetworkId {
#[n(0)] #[n(0)]
@ -629,18 +633,18 @@ pub enum NetworkId {
Two, Two,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
#[cbor(index_only)] #[cbor(index_only)]
pub enum Language { pub enum Language {
#[n(0)] #[n(0)]
PlutusV1, PlutusV1,
} }
pub type CostModel = MaybeIndefArray<i64>; pub type CostModel = Vec<i64>;
pub type CostMdls = KeyValuePairs<Language, CostModel>; pub type CostMdls = BTreeMap<Language, CostModel>;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
#[cbor(map)] #[cbor(map)]
pub struct ProtocolParamUpdate { pub struct ProtocolParamUpdate {
#[n(0)] #[n(0)]
@ -693,10 +697,10 @@ pub struct ProtocolParamUpdate {
pub max_collateral_inputs: Option<u32>, pub max_collateral_inputs: Option<u32>,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct Update { pub struct Update {
#[n(0)] #[n(0)]
pub proposed_protocol_parameter_updates: KeyValuePairs<Genesishash, ProtocolParamUpdate>, pub proposed_protocol_parameter_updates: BTreeMap<Genesishash, ProtocolParamUpdate>,
#[n(1)] #[n(1)]
pub epoch: Epoch, pub epoch: Epoch,
@ -704,14 +708,14 @@ pub struct Update {
// Can't derive encode for TransactionBody because it seems to require a very // Can't derive encode for TransactionBody because it seems to require a very
// particular order for each key in the map // particular order for each key in the map
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
#[cbor(map)] #[cbor(map)]
pub struct TransactionBody { pub struct TransactionBody {
#[n(0)] #[n(0)]
pub inputs: MaybeIndefArray<TransactionInput>, pub inputs: Vec<TransactionInput>,
#[n(1)] #[n(1)]
pub outputs: MaybeIndefArray<TransactionOutput>, pub outputs: Vec<TransactionOutput>,
#[n(2)] #[n(2)]
pub fee: u64, pub fee: u64,
@ -720,7 +724,7 @@ pub struct TransactionBody {
pub ttl: Option<u64>, pub ttl: Option<u64>,
#[n(4)] #[n(4)]
pub certificates: Option<MaybeIndefArray<Certificate>>, pub certificates: Option<Vec<Certificate>>,
#[n(5)] #[n(5)]
pub withdrawals: Option<Withdrawals>, pub withdrawals: Option<Withdrawals>,
@ -729,7 +733,7 @@ pub struct TransactionBody {
pub update: Option<Update>, pub update: Option<Update>,
#[n(7)] #[n(7)]
pub auxiliary_data_hash: Option<ByteVec>, pub auxiliary_data_hash: Option<Bytes>,
#[n(8)] #[n(8)]
pub validity_interval_start: Option<u64>, pub validity_interval_start: Option<u64>,
@ -741,7 +745,7 @@ pub struct TransactionBody {
pub script_data_hash: Option<Hash<32>>, pub script_data_hash: Option<Hash<32>>,
#[n(13)] #[n(13)]
pub collateral: Option<MaybeIndefArray<TransactionInput>>, pub collateral: Option<Vec<TransactionInput>>,
#[n(14)] #[n(14)]
pub required_signers: Option<RequiredSigners>, pub required_signers: Option<RequiredSigners>,
@ -750,21 +754,21 @@ pub struct TransactionBody {
pub network_id: Option<NetworkId>, pub network_id: Option<NetworkId>,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct VKeyWitness { pub struct VKeyWitness {
#[n(0)] #[n(0)]
pub vkey: ByteVec, pub vkey: Bytes,
#[n(1)] #[n(1)]
pub signature: ByteVec, pub signature: Bytes,
} }
#[derive(Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub enum NativeScript { pub enum NativeScript {
ScriptPubkey(AddrKeyhash), ScriptPubkey(AddrKeyhash),
ScriptAll(MaybeIndefArray<NativeScript>), ScriptAll(Vec<NativeScript>),
ScriptAny(MaybeIndefArray<NativeScript>), ScriptAny(Vec<NativeScript>),
ScriptNOfK(u32, MaybeIndefArray<NativeScript>), ScriptNOfK(u32, Vec<NativeScript>),
InvalidBefore(u64), InvalidBefore(u64),
InvalidHereafter(u64), InvalidHereafter(u64),
} }
@ -831,9 +835,9 @@ impl<C> minicbor::encode::Encode<C> for NativeScript {
} }
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
#[cbor(transparent)] #[cbor(transparent)]
pub struct PlutusScript(#[n(0)] pub ByteVec); pub struct PlutusScript(#[n(0)] pub Bytes);
impl AsRef<[u8]> for PlutusScript { impl AsRef<[u8]> for PlutusScript {
fn as_ref(&self) -> &[u8] { fn as_ref(&self) -> &[u8] {
@ -847,11 +851,11 @@ big_uint = #6.2(bounded_bytes) ; New
big_nint = #6.3(bounded_bytes) ; New big_nint = #6.3(bounded_bytes) ; New
*/ */
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum BigInt { pub enum BigInt {
Int(Int), Int(Int),
BigUInt(ByteVec), BigUInt(Bytes),
BigNInt(ByteVec), BigNInt(Bytes),
} }
impl<'b, C> minicbor::decode::Decode<'b, C> for BigInt { impl<'b, C> minicbor::decode::Decode<'b, C> for BigInt {
@ -909,14 +913,13 @@ impl<C> minicbor::encode::Encode<C> for BigInt {
} }
} }
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum PlutusData { pub enum PlutusData {
Constr(Constr<PlutusData>), Constr(Constr<PlutusData>),
Map(KeyValuePairs<PlutusData, PlutusData>), Map(BTreeMap<PlutusData, PlutusData>),
BigInt(BigInt), BigInt(BigInt),
BoundedBytes(ByteVec), BoundedBytes(Bytes),
Array(MaybeIndefArray<PlutusData>), Array(Vec<PlutusData>),
ArrayIndef(MaybeIndefArray<PlutusData>),
} }
impl<'b, C> minicbor::decode::Decode<'b, C> for PlutusData { impl<'b, C> minicbor::decode::Decode<'b, C> for PlutusData {
@ -955,10 +958,11 @@ impl<'b, C> minicbor::decode::Decode<'b, C> for PlutusData {
full.extend(slice?); full.extend(slice?);
} }
Ok(Self::BoundedBytes(ByteVec::from(full))) Ok(Self::BoundedBytes(Bytes::from(full)))
}
minicbor::data::Type::Array | minicbor::data::Type::ArrayIndef => {
Ok(Self::Array(d.decode_with(ctx)?))
} }
minicbor::data::Type::Array => Ok(Self::Array(d.decode_with(ctx)?)),
minicbor::data::Type::ArrayIndef => Ok(Self::ArrayIndef(d.decode_with(ctx)?)),
_ => Err(minicbor::decode::Error::message( _ => Err(minicbor::decode::Error::message(
"bad cbor data type for plutus data", "bad cbor data type for plutus data",
@ -978,7 +982,13 @@ impl<C> minicbor::encode::Encode<C> for PlutusData {
e.encode_with(a, ctx)?; e.encode_with(a, ctx)?;
} }
Self::Map(a) => { Self::Map(a) => {
e.encode_with(a, ctx)?; // we use indef array by default to match the approach used by the cardano-cli
e.begin_map()?;
for (k, v) in a.iter() {
k.encode(e, ctx)?;
v.encode(e, ctx)?;
}
e.end()?;
} }
Self::BigInt(a) => { Self::BigInt(a) => {
e.encode_with(a, ctx)?; e.encode_with(a, ctx)?;
@ -987,10 +997,12 @@ impl<C> minicbor::encode::Encode<C> for PlutusData {
e.encode_with(a, ctx)?; e.encode_with(a, ctx)?;
} }
Self::Array(a) => { Self::Array(a) => {
e.encode_with(a, ctx)?; // we use indef array by default to match the approach used by the cardano-cli
} e.begin_array()?;
Self::ArrayIndef(a) => { for v in a.iter() {
e.encode_with(a, ctx)?; e.encode_with(v, ctx)?;
}
e.end()?;
} }
} }
@ -998,11 +1010,11 @@ impl<C> minicbor::encode::Encode<C> for PlutusData {
} }
} }
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Constr<A> { pub struct Constr<A> {
pub tag: u64, pub tag: u64,
pub any_constructor: Option<u64>, pub any_constructor: Option<u64>,
pub fields: MaybeIndefArray<A>, pub fields: Vec<A>,
} }
impl<'b, C, A> minicbor::decode::Decode<'b, C> for Constr<A> impl<'b, C, A> minicbor::decode::Decode<'b, C> for Constr<A>
@ -1054,12 +1066,23 @@ where
102 => { 102 => {
e.array(2)?; e.array(2)?;
e.encode_with(self.any_constructor.unwrap_or_default(), ctx)?; e.encode_with(self.any_constructor.unwrap_or_default(), ctx)?;
e.encode_with(&self.fields, ctx)?;
// we use indef array by default to match the approach used by the cardano-cli
e.begin_array()?;
for v in self.fields.iter() {
e.encode_with(v, ctx)?;
}
e.end()?;
Ok(()) Ok(())
} }
_ => { _ => {
e.encode_with(&self.fields, ctx)?; // we use indef array by default to match the approach used by the cardano-cli
e.begin_array()?;
for v in self.fields.iter() {
e.encode_with(v, ctx)?;
}
e.end()?;
Ok(()) Ok(())
} }
@ -1067,7 +1090,7 @@ where
} }
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct ExUnits { pub struct ExUnits {
#[n(0)] #[n(0)]
pub mem: u32, pub mem: u32,
@ -1075,7 +1098,7 @@ pub struct ExUnits {
pub steps: u64, pub steps: u64,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct ExUnitPrices { pub struct ExUnitPrices {
#[n(0)] #[n(0)]
mem_price: PositiveInterval, mem_price: PositiveInterval,
@ -1084,7 +1107,7 @@ pub struct ExUnitPrices {
step_price: PositiveInterval, step_price: PositiveInterval,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
#[cbor(index_only)] #[cbor(index_only)]
pub enum RedeemerTag { pub enum RedeemerTag {
#[n(0)] #[n(0)]
@ -1097,7 +1120,7 @@ pub enum RedeemerTag {
Reward, Reward,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct Redeemer { pub struct Redeemer {
#[n(0)] #[n(0)]
pub tag: RedeemerTag, pub tag: RedeemerTag,
@ -1119,102 +1142,78 @@ pub struct Redeemer {
, attributes : bytes , attributes : bytes
] */ ] */
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct BootstrapWitness { pub struct BootstrapWitness {
#[n(0)] #[n(0)]
pub public_key: ByteVec, pub public_key: Bytes,
#[n(1)] #[n(1)]
pub signature: ByteVec, pub signature: Bytes,
#[n(2)] #[n(2)]
pub chain_code: ByteVec, pub chain_code: Bytes,
#[n(3)] #[n(3)]
pub attributes: ByteVec, pub attributes: Bytes,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Clone)]
#[cbor(map)] #[cbor(map)]
pub struct TransactionWitnessSet { pub struct TransactionWitnessSet {
#[n(0)] #[n(0)]
pub vkeywitness: Option<MaybeIndefArray<VKeyWitness>>, pub vkeywitness: Option<Vec<VKeyWitness>>,
#[n(1)] #[n(1)]
pub native_script: Option<MaybeIndefArray<NativeScript>>, pub native_script: Option<Vec<NativeScript>>,
#[n(2)] #[n(2)]
pub bootstrap_witness: Option<MaybeIndefArray<BootstrapWitness>>, pub bootstrap_witness: Option<Vec<BootstrapWitness>>,
#[n(3)] #[n(3)]
pub plutus_script: Option<MaybeIndefArray<PlutusScript>>, pub plutus_script: Option<Vec<PlutusScript>>,
#[n(4)] #[n(4)]
pub plutus_data: Option<MaybeIndefArray<PlutusData>>, pub plutus_data: Option<Vec<PlutusData>>,
#[n(5)] #[n(5)]
pub redeemer: Option<MaybeIndefArray<Redeemer>>, pub redeemer: Option<Vec<Redeemer>>,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Clone)]
#[cbor(map)] #[cbor(map)]
pub struct PostAlonzoAuxiliaryData { pub struct PostAlonzoAuxiliaryData {
#[n(0)] #[n(0)]
pub metadata: Option<Metadata>, pub metadata: Option<Metadata>,
#[n(1)] #[n(1)]
pub native_scripts: Option<MaybeIndefArray<NativeScript>>, pub native_scripts: Option<Vec<NativeScript>>,
#[n(2)] #[n(2)]
pub plutus_scripts: Option<MaybeIndefArray<PlutusScript>>, pub plutus_scripts: Option<Vec<PlutusScript>>,
} }
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum Metadatum { pub enum Metadatum {
Int(Int), Int(Int),
Bytes(ByteVec), Bytes(Bytes),
Text(String), Text(String),
Array(MaybeIndefArray<Metadatum>), Array(Vec<Metadatum>),
Map(KeyValuePairs<Metadatum, Metadatum>), Map(BTreeMap<Metadatum, Metadatum>),
} }
impl<'b, C> minicbor::Decode<'b, C> for Metadatum { impl<'b, C> minicbor::Decode<'b, C> for Metadatum {
fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> { fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
match d.datatype()? { match d.datatype()? {
minicbor::data::Type::U8 => { minicbor::data::Type::U8
let i = d.u8()?; | minicbor::data::Type::U16
Ok(Metadatum::Int(i.into())) | minicbor::data::Type::U32
} | minicbor::data::Type::U64
minicbor::data::Type::U16 => { | minicbor::data::Type::I8
let i = d.u16()?; | minicbor::data::Type::I16
Ok(Metadatum::Int(i.into())) | minicbor::data::Type::I32
} | minicbor::data::Type::I64
minicbor::data::Type::U32 => { | minicbor::data::Type::Int => {
let i = d.u32()?; let i = d.decode()?;
Ok(Metadatum::Int(i.into()))
}
minicbor::data::Type::U64 => {
let i = d.u64()?;
Ok(Metadatum::Int(i.into()))
}
minicbor::data::Type::I8 => {
let i = d.i8()?;
Ok(Metadatum::Int(i.into()))
}
minicbor::data::Type::I16 => {
let i = d.i16()?;
Ok(Metadatum::Int(i.into()))
}
minicbor::data::Type::I32 => {
let i = d.i32()?;
Ok(Metadatum::Int(i.into()))
}
minicbor::data::Type::I64 => {
let i = d.i64()?;
Ok(Metadatum::Int(i.into()))
}
minicbor::data::Type::Int => {
let i = d.int()?;
Ok(Metadatum::Int(i)) Ok(Metadatum::Int(i))
} }
minicbor::data::Type::Bytes => Ok(Metadatum::Bytes(d.decode_with(ctx)?)), minicbor::data::Type::Bytes => Ok(Metadatum::Bytes(d.decode_with(ctx)?)),
@ -1256,23 +1255,23 @@ impl<C> minicbor::Encode<C> for Metadatum {
} }
} }
pub type MetadatumLabel = AnyUInt; pub type MetadatumLabel = u64;
pub type Metadata = KeyValuePairs<MetadatumLabel, Metadatum>; pub type Metadata = BTreeMap<MetadatumLabel, Metadatum>;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Clone)]
pub struct ShelleyMaAuxiliaryDAta { pub struct ShelleyMaAuxiliaryData {
#[n(0)] #[n(0)]
pub transaction_metadata: Metadata, pub transaction_metadata: Metadata,
#[n(1)] #[n(1)]
pub auxiliary_scripts: Option<MaybeIndefArray<NativeScript>>, pub auxiliary_scripts: Option<Vec<NativeScript>>,
} }
#[derive(Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub enum AuxiliaryData { pub enum AuxiliaryData {
Shelley(Metadata), Shelley(Metadata),
ShelleyMa(ShelleyMaAuxiliaryDAta), ShelleyMa(ShelleyMaAuxiliaryData),
PostAlonzo(PostAlonzoAuxiliaryData), PostAlonzo(PostAlonzoAuxiliaryData),
} }
@ -1320,22 +1319,22 @@ impl<C> minicbor::Encode<C> for AuxiliaryData {
pub type TransactionIndex = u32; pub type TransactionIndex = u32;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Clone)]
pub struct Block { pub struct Block {
#[n(0)] #[n(0)]
pub header: Header, pub header: Header,
#[b(1)] #[b(1)]
pub transaction_bodies: MaybeIndefArray<TransactionBody>, pub transaction_bodies: Vec<TransactionBody>,
#[n(2)] #[n(2)]
pub transaction_witness_sets: MaybeIndefArray<TransactionWitnessSet>, pub transaction_witness_sets: Vec<TransactionWitnessSet>,
#[n(3)] #[n(3)]
pub auxiliary_data_set: KeyValuePairs<TransactionIndex, AuxiliaryData>, pub auxiliary_data_set: BTreeMap<TransactionIndex, AuxiliaryData>,
#[n(4)] #[n(4)]
pub invalid_transactions: Option<MaybeIndefArray<TransactionIndex>>, pub invalid_transactions: Option<Vec<TransactionIndex>>,
} }
/// A memory representation of an already minted block /// A memory representation of an already minted block
@ -1361,7 +1360,34 @@ pub struct MintedBlock<'b> {
pub invalid_transactions: Option<MaybeIndefArray<TransactionIndex>>, pub invalid_transactions: Option<MaybeIndefArray<TransactionIndex>>,
} }
#[derive(Encode, Decode, Debug)] impl<'b> From<MintedBlock<'b>> for Block {
fn from(x: MintedBlock<'b>) -> Self {
Block {
header: x.header.unwrap(),
transaction_bodies: x
.transaction_bodies
.to_vec()
.into_iter()
.map(|x| x.unwrap())
.collect(),
transaction_witness_sets: x
.transaction_witness_sets
.to_vec()
.into_iter()
.map(|x| x.unwrap())
.collect(),
auxiliary_data_set: x
.auxiliary_data_set
.to_vec()
.into_iter()
.map(|(k, v)| (k, v.unwrap()))
.collect(),
invalid_transactions: x.invalid_transactions.map(|x| x.into()),
}
}
}
#[derive(Serialize, Deserialize, Encode, Decode, Debug)]
pub struct Tx { pub struct Tx {
#[n(0)] #[n(0)]
pub transaction_body: TransactionBody, pub transaction_body: TransactionBody,

View file

@ -2,17 +2,21 @@
//! //!
//! Handcrafted, idiomatic rust artifacts based on based on the [Babbage CDDL](https://github.com/input-output-hk/cardano-ledger/blob/master/eras/babbage/test-suite/cddl-files/babbage.cddl) file in IOHK repo. //! Handcrafted, idiomatic rust artifacts based on based on the [Babbage CDDL](https://github.com/input-output-hk/cardano-ledger/blob/master/eras/babbage/test-suite/cddl-files/babbage.cddl) file in IOHK repo.
use pallas_codec::minicbor::{bytes::ByteVec, Decode, Encode}; use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use pallas_codec::minicbor::{Decode, Encode};
use pallas_crypto::hash::Hash; use pallas_crypto::hash::Hash;
use pallas_codec::utils::{CborWrap, KeepRaw, KeyValuePairs, MaybeIndefArray, Nullable}; use pallas_codec::utils::{Bytes, CborWrap, KeepRaw, KeyValuePairs, MaybeIndefArray, Nullable};
// required for derive attrs to work // required for derive attrs to work
use pallas_codec::minicbor; use pallas_codec::minicbor;
pub use crate::alonzo::VrfCert; pub use crate::alonzo::VrfCert;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct HeaderBody { pub struct HeaderBody {
#[n(0)] #[n(0)]
pub block_number: u64, pub block_number: u64,
@ -24,10 +28,10 @@ pub struct HeaderBody {
pub prev_hash: Option<Hash<32>>, pub prev_hash: Option<Hash<32>>,
#[n(3)] #[n(3)]
pub issuer_vkey: ByteVec, pub issuer_vkey: Bytes,
#[n(4)] #[n(4)]
pub vrf_vkey: ByteVec, pub vrf_vkey: Bytes,
#[n(5)] #[n(5)]
pub vrf_result: VrfCert, pub vrf_result: VrfCert,
@ -45,10 +49,10 @@ pub struct HeaderBody {
pub protocol_version: ProtocolVersion, pub protocol_version: ProtocolVersion,
} }
#[derive(Encode, Decode, Debug, Clone, PartialEq, PartialOrd)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct OperationalCert { pub struct OperationalCert {
#[n(0)] #[n(0)]
pub operational_cert_hot_vkey: ByteVec, pub operational_cert_hot_vkey: Bytes,
#[n(1)] #[n(1)]
pub operational_cert_sequence_number: u64, pub operational_cert_sequence_number: u64,
@ -57,20 +61,20 @@ pub struct OperationalCert {
pub operational_cert_kes_period: u64, pub operational_cert_kes_period: u64,
#[n(3)] #[n(3)]
pub operational_cert_sigma: ByteVec, pub operational_cert_sigma: Bytes,
} }
pub use crate::alonzo::ProtocolVersion; pub use crate::alonzo::ProtocolVersion;
pub use crate::alonzo::KesSignature; pub use crate::alonzo::KesSignature;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct Header { pub struct Header {
#[n(0)] #[n(0)]
pub header_body: HeaderBody, pub header_body: HeaderBody,
#[n(1)] #[n(1)]
pub body_signature: ByteVec, pub body_signature: Bytes,
} }
pub use crate::alonzo::TransactionInput; pub use crate::alonzo::TransactionInput;
@ -113,9 +117,9 @@ pub use crate::alonzo::MoveInstantaneousReward;
pub use crate::alonzo::RewardAccount; pub use crate::alonzo::RewardAccount;
pub type Withdrawals = KeyValuePairs<RewardAccount, Coin>; pub type Withdrawals = BTreeMap<RewardAccount, Coin>;
pub type RequiredSigners = MaybeIndefArray<AddrKeyhash>; pub type RequiredSigners = Vec<AddrKeyhash>;
pub use crate::alonzo::Port; pub use crate::alonzo::Port;
@ -147,7 +151,7 @@ pub use crate::alonzo::Certificate;
pub use crate::alonzo::NetworkId; pub use crate::alonzo::NetworkId;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
#[cbor(index_only)] #[cbor(index_only)]
pub enum Language { pub enum Language {
#[n(0)] #[n(0)]
@ -159,7 +163,7 @@ pub enum Language {
pub use crate::alonzo::CostModel; pub use crate::alonzo::CostModel;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
#[cbor(map)] #[cbor(map)]
pub struct CostMdls { pub struct CostMdls {
#[n(0)] #[n(0)]
@ -169,7 +173,7 @@ pub struct CostMdls {
pub plutus_v2: Option<CostModel>, pub plutus_v2: Option<CostModel>,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
#[cbor(map)] #[cbor(map)]
pub struct ProtocolParamUpdate { pub struct ProtocolParamUpdate {
#[n(0)] #[n(0)]
@ -219,23 +223,23 @@ pub struct ProtocolParamUpdate {
pub max_collateral_inputs: Option<u32>, pub max_collateral_inputs: Option<u32>,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct Update { pub struct Update {
#[n(0)] #[n(0)]
pub proposed_protocol_parameter_updates: KeyValuePairs<Genesishash, ProtocolParamUpdate>, pub proposed_protocol_parameter_updates: BTreeMap<Genesishash, ProtocolParamUpdate>,
#[n(1)] #[n(1)]
pub epoch: Epoch, pub epoch: Epoch,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Clone)]
#[cbor(map)] #[cbor(map)]
pub struct TransactionBody { pub struct TransactionBody {
#[n(0)] #[n(0)]
pub inputs: MaybeIndefArray<TransactionInput>, pub inputs: Vec<TransactionInput>,
#[n(1)] #[n(1)]
pub outputs: MaybeIndefArray<TransactionOutput>, pub outputs: Vec<TransactionOutput>,
#[n(2)] #[n(2)]
pub fee: u64, pub fee: u64,
@ -244,16 +248,16 @@ pub struct TransactionBody {
pub ttl: Option<u64>, pub ttl: Option<u64>,
#[n(4)] #[n(4)]
pub certificates: Option<MaybeIndefArray<Certificate>>, pub certificates: Option<Vec<Certificate>>,
#[n(5)] #[n(5)]
pub withdrawals: Option<KeyValuePairs<RewardAccount, Coin>>, pub withdrawals: Option<BTreeMap<RewardAccount, Coin>>,
#[n(6)] #[n(6)]
pub update: Option<Update>, pub update: Option<Update>,
#[n(7)] #[n(7)]
pub auxiliary_data_hash: Option<ByteVec>, pub auxiliary_data_hash: Option<Bytes>,
#[n(8)] #[n(8)]
pub validity_interval_start: Option<u64>, pub validity_interval_start: Option<u64>,
@ -265,10 +269,10 @@ pub struct TransactionBody {
pub script_data_hash: Option<Hash<32>>, pub script_data_hash: Option<Hash<32>>,
#[n(13)] #[n(13)]
pub collateral: Option<MaybeIndefArray<TransactionInput>>, pub collateral: Option<Vec<TransactionInput>>,
#[n(14)] #[n(14)]
pub required_signers: Option<MaybeIndefArray<AddrKeyhash>>, pub required_signers: Option<Vec<AddrKeyhash>>,
#[n(15)] #[n(15)]
pub network_id: Option<NetworkId>, pub network_id: Option<NetworkId>,
@ -280,10 +284,10 @@ pub struct TransactionBody {
pub total_collateral: Option<Coin>, pub total_collateral: Option<Coin>,
#[n(18)] #[n(18)]
pub reference_inputs: Option<MaybeIndefArray<TransactionInput>>, pub reference_inputs: Option<Vec<TransactionInput>>,
} }
#[derive(Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub enum TransactionOutput { pub enum TransactionOutput {
Legacy(LegacyTransactionOutput), Legacy(LegacyTransactionOutput),
PostAlonzo(PostAlonzoTransactionOutput), PostAlonzo(PostAlonzoTransactionOutput),
@ -321,11 +325,11 @@ impl<C> minicbor::Encode<C> for TransactionOutput {
} }
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Clone)]
#[cbor(map)] #[cbor(map)]
pub struct PostAlonzoTransactionOutput { pub struct PostAlonzoTransactionOutput {
#[n(0)] #[n(0)]
pub address: ByteVec, pub address: Bytes,
#[n(1)] #[n(1)]
pub value: Value, pub value: Value,
@ -343,9 +347,9 @@ pub use crate::alonzo::NativeScript;
pub use crate::alonzo::PlutusScript as PlutusV1Script; pub use crate::alonzo::PlutusScript as PlutusV1Script;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone)]
#[cbor(transparent)] #[cbor(transparent)]
pub struct PlutusV2Script(#[n(0)] pub ByteVec); pub struct PlutusV2Script(#[n(0)] pub Bytes);
impl AsRef<[u8]> for PlutusV2Script { impl AsRef<[u8]> for PlutusV2Script {
fn as_ref(&self) -> &[u8] { fn as_ref(&self) -> &[u8] {
@ -369,45 +373,45 @@ pub use crate::alonzo::Redeemer;
pub use crate::alonzo::BootstrapWitness; pub use crate::alonzo::BootstrapWitness;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Clone)]
#[cbor(map)] #[cbor(map)]
pub struct TransactionWitnessSet { pub struct TransactionWitnessSet {
#[n(0)] #[n(0)]
pub vkeywitness: Option<MaybeIndefArray<VKeyWitness>>, pub vkeywitness: Option<Vec<VKeyWitness>>,
#[n(1)] #[n(1)]
pub native_script: Option<MaybeIndefArray<NativeScript>>, pub native_script: Option<Vec<NativeScript>>,
#[n(2)] #[n(2)]
pub bootstrap_witness: Option<MaybeIndefArray<BootstrapWitness>>, pub bootstrap_witness: Option<Vec<BootstrapWitness>>,
#[n(3)] #[n(3)]
pub plutus_v1_script: Option<MaybeIndefArray<PlutusV1Script>>, pub plutus_v1_script: Option<Vec<PlutusV1Script>>,
#[n(4)] #[n(4)]
pub plutus_data: Option<MaybeIndefArray<PlutusData>>, pub plutus_data: Option<Vec<PlutusData>>,
#[n(5)] #[n(5)]
pub redeemer: Option<MaybeIndefArray<Redeemer>>, pub redeemer: Option<Vec<Redeemer>>,
#[n(6)] #[n(6)]
pub plutus_v2_script: Option<MaybeIndefArray<PlutusV2Script>>, pub plutus_v2_script: Option<Vec<PlutusV2Script>>,
} }
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Clone)]
#[cbor(map)] #[cbor(map)]
pub struct PostAlonzoAuxiliaryData { pub struct PostAlonzoAuxiliaryData {
#[n(0)] #[n(0)]
pub metadata: Option<Metadata>, pub metadata: Option<Metadata>,
#[n(1)] #[n(1)]
pub native_scripts: Option<MaybeIndefArray<NativeScript>>, pub native_scripts: Option<Vec<NativeScript>>,
#[n(2)] #[n(2)]
pub plutus_v1_scripts: Option<MaybeIndefArray<PlutusV1Script>>, pub plutus_v1_scripts: Option<Vec<PlutusV1Script>>,
#[n(3)] #[n(3)]
pub plutus_v2_scripts: Option<MaybeIndefArray<PlutusV2Script>>, pub plutus_v2_scripts: Option<Vec<PlutusV2Script>>,
} }
pub type DatumHash = Hash<32>; pub type DatumHash = Hash<32>;
@ -415,7 +419,7 @@ pub type DatumHash = Hash<32>;
pub type Data = CborWrap<PlutusData>; pub type Data = CborWrap<PlutusData>;
// datum_option = [ 0, $hash32 // 1, data ] // datum_option = [ 0, $hash32 // 1, data ]
#[derive(Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum DatumOption { pub enum DatumOption {
Hash(Hash<32>), Hash(Hash<32>),
Data(Data), Data(Data),
@ -457,7 +461,7 @@ impl<C> minicbor::Encode<C> for DatumOption {
pub type ScriptRef = CborWrap<Script>; pub type ScriptRef = CborWrap<Script>;
// script = [ 0, native_script // 1, plutus_v1_script // 2, plutus_v2_script ] // script = [ 0, native_script // 1, plutus_v1_script // 2, plutus_v2_script ]
#[derive(Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub enum Script { pub enum Script {
NativeScript(NativeScript), NativeScript(NativeScript),
PlutusV1Script(PlutusV1Script), PlutusV1Script(PlutusV1Script),
@ -508,22 +512,22 @@ pub use crate::alonzo::AuxiliaryData;
pub use crate::alonzo::TransactionIndex; pub use crate::alonzo::TransactionIndex;
#[derive(Encode, Decode, Debug, PartialEq, Clone)] #[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Clone)]
pub struct Block { pub struct Block {
#[n(0)] #[n(0)]
pub header: Header, pub header: Header,
#[b(1)] #[b(1)]
pub transaction_bodies: MaybeIndefArray<TransactionBody>, pub transaction_bodies: Vec<TransactionBody>,
#[n(2)] #[n(2)]
pub transaction_witness_sets: MaybeIndefArray<TransactionWitnessSet>, pub transaction_witness_sets: Vec<TransactionWitnessSet>,
#[n(3)] #[n(3)]
pub auxiliary_data_set: KeyValuePairs<TransactionIndex, AuxiliaryData>, pub auxiliary_data_set: BTreeMap<TransactionIndex, AuxiliaryData>,
#[n(4)] #[n(4)]
pub invalid_transactions: Option<MaybeIndefArray<TransactionIndex>>, pub invalid_transactions: Option<Vec<TransactionIndex>>,
} }
/// A memory representation of an already minted block /// A memory representation of an already minted block
@ -549,7 +553,34 @@ pub struct MintedBlock<'b> {
pub invalid_transactions: Option<MaybeIndefArray<TransactionIndex>>, pub invalid_transactions: Option<MaybeIndefArray<TransactionIndex>>,
} }
#[derive(Encode, Decode, Debug)] impl<'b> From<MintedBlock<'b>> for Block {
fn from(x: MintedBlock<'b>) -> Self {
Block {
header: x.header.unwrap(),
transaction_bodies: x
.transaction_bodies
.to_vec()
.into_iter()
.map(|x| x.unwrap())
.collect(),
transaction_witness_sets: x
.transaction_witness_sets
.to_vec()
.into_iter()
.map(|x| x.unwrap())
.collect(),
auxiliary_data_set: x
.auxiliary_data_set
.to_vec()
.into_iter()
.map(|(k, v)| (k, v.unwrap()))
.collect(),
invalid_transactions: x.invalid_transactions.map(|x| x.into()),
}
}
}
#[derive(Serialize, Deserialize, Encode, Decode, Debug)]
pub struct Tx { pub struct Tx {
#[n(0)] #[n(0)]
pub transaction_body: TransactionBody, pub transaction_body: TransactionBody,
@ -579,6 +610,17 @@ pub struct MintedTx<'b> {
pub auxiliary_data: Nullable<KeepRaw<'b, AuxiliaryData>>, pub auxiliary_data: Nullable<KeepRaw<'b, AuxiliaryData>>,
} }
impl<'b> From<MintedTx<'b>> for Tx {
fn from(x: MintedTx<'b>) -> Self {
Tx {
transaction_body: x.transaction_body.unwrap(),
transaction_witness_set: x.transaction_witness_set.unwrap(),
success: x.success,
auxiliary_data: x.auxiliary_data.map(|x| x.unwrap()),
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use pallas_codec::minicbor; use pallas_codec::minicbor;

View file

@ -52,7 +52,7 @@ pub type Attributes = EmptyMap;
// The primitives crate will treat addresses as a black-box vec of bytes. // The primitives crate will treat addresses as a black-box vec of bytes.
// address = [ #6.24(bytes .cbor ([addressid, addrattr, addrtype])), u64 ] // address = [ #6.24(bytes .cbor ([addressid, addrattr, addrtype])), u64 ]
#[derive(Debug, Encode, Decode, Clone, PartialEq, PartialOrd)] #[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Address { pub struct Address {
#[n(0)] #[n(0)]
pub payload: TagWrap<ByteVec, 24>, pub payload: TagWrap<ByteVec, 24>,

View file

@ -8,9 +8,7 @@ homepage = "https://github.com/txpipe/pallas"
documentation = "https://docs.rs/pallas-traverse" documentation = "https://docs.rs/pallas-traverse"
license = "Apache-2.0" license = "Apache-2.0"
readme = "README.md" readme = "README.md"
authors = [ authors = ["Santiago Carmuega <santiago@carmuega.me>"]
"Santiago Carmuega <santiago@carmuega.me>",
]
[dependencies] [dependencies]
pallas-primitives = { version = "0.13.0", path = "../pallas-primitives" } pallas-primitives = { version = "0.13.0", path = "../pallas-primitives" }

View file

@ -62,17 +62,17 @@ impl<'b> MultiEraOutput<'b> {
MultiEraOutput::Byron(x) => x.amount, MultiEraOutput::Byron(x) => x.amount,
MultiEraOutput::Babbage(x) => match x.deref().deref() { MultiEraOutput::Babbage(x) => match x.deref().deref() {
babbage::TransactionOutput::Legacy(x) => match x.amount { babbage::TransactionOutput::Legacy(x) => match x.amount {
babbage::Value::Coin(c) => u64::from(c), babbage::Value::Coin(c) => c,
babbage::Value::Multiasset(c, _) => u64::from(c), babbage::Value::Multiasset(c, _) => c,
}, },
babbage::TransactionOutput::PostAlonzo(x) => match x.value { babbage::TransactionOutput::PostAlonzo(x) => match x.value {
babbage::Value::Coin(c) => u64::from(c), babbage::Value::Coin(c) => c,
babbage::Value::Multiasset(c, _) => u64::from(c), babbage::Value::Multiasset(c, _) => c,
}, },
}, },
MultiEraOutput::AlonzoCompatible(x) => match x.amount { MultiEraOutput::AlonzoCompatible(x) => match x.amount {
alonzo::Value::Coin(c) => u64::from(c), alonzo::Value::Coin(c) => c,
alonzo::Value::Multiasset(c, _) => u64::from(c), alonzo::Value::Multiasset(c, _) => c,
}, },
} }
} }

View file

@ -25,7 +25,7 @@ impl<'b> MultiEraWithdrawals<'b> {
MultiEraWithdrawals::NotApplicable => std::iter::empty().collect(), MultiEraWithdrawals::NotApplicable => std::iter::empty().collect(),
MultiEraWithdrawals::Empty => std::iter::empty().collect(), MultiEraWithdrawals::Empty => std::iter::empty().collect(),
MultiEraWithdrawals::AlonzoCompatible(x) => { MultiEraWithdrawals::AlonzoCompatible(x) => {
x.iter().map(|(k, v)| (k.as_slice(), v.into())).collect() x.iter().map(|(k, v)| (k.as_slice(), *v)).collect()
} }
} }
} }