aiken/cbor

Functions

diagnostic(self: Data) -> String

Obtain a String representation of anything. This is particularly (and only) useful for tracing and debugging. This function is expensive and should not be used in any production code as it will very likely explodes the validator’s budget.

The output is a CBOR diagnostic of the underlying on-chain binary representation of the data. It’s not as easy to read as plain Aiken code, but it is handy for troubleshooting values at runtime. Incidentally, getting familiar with reading CBOR diagnostic is a good idea in the Cardano world.

cbor.diagnostic(42) == "42"
cbor.diagnostic(#"a1b2") == "h'A1B2'"
cbor.diagnostic([1, 2, 3]) == "[_ 1, 2, 3]"
cbor.diagnostic([]) == "[]"
cbor.diagnostic((1, 2)) == "[_ 1, 2]"
cbor.diagnostic((1, #"ff", 3)) == "[_ 1, h'FF', 3]"
cbor.diagnostic([(1, #"ff")]) == "{_ 1: h'FF' }"
cbor.diagnostic(Some(42)) == "121([_ 42])"
cbor.diagnostic(None) == "122([])"

deserialise(bytes: ByteArray) -> Option<Data>

Deserialise a CBOR Data. This is the reverse operation of serialise. In particular, we have the following property:

cbor.deserialise(cbor.serialise(any_data)) == Some(any_data)

Unfortunately, this function isn’t derived from a builtin primitive. It is therefore an order of magnitude more expensive than its counterpart and shall be used with care.

In general, one might prefer avoiding deserialisation unless truly necessary. Yet, it may come in handy for testing and in rare scenarios.

serialise(self: Data) -> ByteArray

Serialise any value to binary, encoding using CBOR.

This is particularly useful in combination with hashing functions, as a way to obtain a byte representation that matches the serialised representation used by the ledger in the context of on-chain code.

Note that the output matches the output of diagnostic, though with a different encoding. diagnostic is merely a textual representation of the CBOR encoding that is human friendly and useful for debugging.

cbor.serialise(42) == #"182a"
cbor.serialise(#"a1b2") == #"42a1b2"
cbor.serialise([]) == #"80"
cbor.serialise((1, 2)) == #"9f0102ff"
cbor.serialise((1, #"ff", 3)) == #"9f0141ff03ff"
cbor.serialise([(1, #"ff")]) == #"a10141ff"
cbor.serialise(Some(42)) == #"d8799f182aff"
cbor.serialise(None) == #"d87a80"
Search Document