Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implement block cbor probing #44

Merged
merged 1 commit into from
Feb 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pallas-primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ authors = [
]

[dependencies]
minicbor = { version = "0.13", features = ["std"] }
minicbor = { version = "0.13", features = ["std", "half"] }
minicbor-derive = "0.8.0"
hex = "0.4.3"
log = "0.4.14"
Expand Down
1 change: 1 addition & 0 deletions pallas-primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod framework;

pub mod alonzo;
pub mod byron;
pub mod probing;
pub mod utils;

pub use framework::*;
57 changes: 57 additions & 0 deletions pallas-primitives/src/probing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//! Heuristics for detecting cbor content without decoding

use minicbor::decode::{Token, Tokenizer};

pub enum BlockInference {
Byron,
Shelley,
Inconclusive,
}

// Executes a very lightweight inspection of the initial tokens of the CBOR
// payload and infers with a certain degree of confidence the type of Cardano
// structure within.
pub fn probe_block_cbor(cbor: &[u8]) -> BlockInference {
let mut tokenizer = Tokenizer::new(cbor);

if !matches!(tokenizer.next(), Some(Ok(Token::Array(2)))) {
return BlockInference::Inconclusive;
}

if !matches!(tokenizer.next(), Some(Ok(Token::U8(_)))) {
return BlockInference::Inconclusive;
}

//println!("{:?}", tokenizer.next());

match tokenizer.next() {
Some(Ok(Token::Array(3))) => BlockInference::Byron,
Some(Ok(Token::Array(5))) => BlockInference::Shelley,
_ => BlockInference::Inconclusive,
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn byron_block_detected() {
let block_str = include_str!("byron/test_data/test1.block");
let bytes = hex::decode(block_str).unwrap();

let inference = probe_block_cbor(bytes.as_slice());

assert!(matches!(inference, BlockInference::Byron));
}

#[test]
fn shelley_block_detected() {
let block_str = include_str!("alonzo/test_data/test1.block");
let bytes = hex::decode(block_str).unwrap();

let inference = probe_block_cbor(bytes.as_slice());

assert!(matches!(inference, BlockInference::Shelley));
}
}