use std::path::{Path, PathBuf};
use sha2::{Digest, Sha256};
use soroban_env_host::xdr::{Limits, WriteXdr};
use soroban_ledger_snapshot::{Error as SnapshotError, LedgerSnapshot};
use thiserror::Error;
pub const SUPPORTED_PROTOCOL_VERSION: u32 = soroban_env_host::VERSION.interface.protocol;
const NEWER_PROTOCOL_VERSION: u32 = SUPPORTED_PROTOCOL_VERSION + 1;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) enum ProtocolPolicy {
#[default]
Exact,
AllowNewer,
}
impl ProtocolPolicy {
pub(crate) const fn check(self, found: u32) -> Result<(), UnsupportedProtocol> {
let accepted = found == SUPPORTED_PROTOCOL_VERSION
|| (matches!(self, Self::AllowNewer) && found == NEWER_PROTOCOL_VERSION);
if accepted {
Ok(())
} else {
Err(UnsupportedProtocol {
found,
supported: SUPPORTED_PROTOCOL_VERSION,
})
}
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct UnsupportedProtocol {
pub(crate) found: u32,
pub(crate) supported: u32,
}
impl From<UnsupportedProtocol> for FixtureError {
fn from(error: UnsupportedProtocol) -> Self {
Self::UnsupportedProtocol {
found: error.found,
supported: error.supported,
}
}
}
pub(crate) const fn executed_protocol_version(network_protocol_version: u32) -> u32 {
if network_protocol_version == NEWER_PROTOCOL_VERSION {
SUPPORTED_PROTOCOL_VERSION
} else {
network_protocol_version
}
}
const LEDGER_DIGEST_DOMAIN_V1: &[u8] = b"KANATOKO\0LEDGER-SNAPSHOT\0V1\0";
#[derive(Clone, Debug)]
pub struct FrozenFixture {
snapshot: LedgerSnapshot,
ledger_digest: [u8; 32],
}
impl FrozenFixture {
pub fn from_file(
path: impl AsRef<Path>,
expected_network_passphrase: &str,
) -> Result<Self, FixtureError> {
Self::from_file_with_policy(path, expected_network_passphrase, ProtocolPolicy::Exact)
}
pub fn from_file_allowing_newer_protocol(
path: impl AsRef<Path>,
expected_network_passphrase: &str,
) -> Result<Self, FixtureError> {
Self::from_file_with_policy(
path,
expected_network_passphrase,
ProtocolPolicy::AllowNewer,
)
}
fn from_file_with_policy(
path: impl AsRef<Path>,
expected_network_passphrase: &str,
policy: ProtocolPolicy,
) -> Result<Self, FixtureError> {
let path = path.as_ref();
let snapshot = LedgerSnapshot::read_file(path).map_err(|source| match source {
source @ SnapshotError::Io(_) => FixtureError::Read {
path: path.to_path_buf(),
source,
},
SnapshotError::Serde(error) if error.is_io() => FixtureError::Read {
path: path.to_path_buf(),
source: SnapshotError::Serde(error),
},
SnapshotError::Serde(error) => FixtureError::Parse {
path: path.to_path_buf(),
source: SnapshotError::Serde(error),
},
})?;
Self::from_snapshot_with_policy(snapshot, expected_network_passphrase, policy)
}
pub fn from_snapshot(
snapshot: LedgerSnapshot,
expected_network_passphrase: &str,
) -> Result<Self, FixtureError> {
Self::from_snapshot_with_policy(
snapshot,
expected_network_passphrase,
ProtocolPolicy::Exact,
)
}
pub fn from_snapshot_allowing_newer_protocol(
snapshot: LedgerSnapshot,
expected_network_passphrase: &str,
) -> Result<Self, FixtureError> {
Self::from_snapshot_with_policy(
snapshot,
expected_network_passphrase,
ProtocolPolicy::AllowNewer,
)
}
pub(crate) fn from_snapshot_with_policy(
snapshot: LedgerSnapshot,
expected_network_passphrase: &str,
policy: ProtocolPolicy,
) -> Result<Self, FixtureError> {
policy.check(snapshot.protocol_version)?;
let expected_network_id: [u8; 32] =
Sha256::digest(expected_network_passphrase.as_bytes()).into();
if snapshot.network_id != expected_network_id {
return Err(FixtureError::NetworkMismatch {
expected: expected_network_id,
found: snapshot.network_id,
});
}
let ledger_digest = canonical_ledger_digest(&snapshot)?;
Ok(Self {
snapshot,
ledger_digest,
})
}
#[must_use]
pub const fn ledger_digest(&self) -> [u8; 32] {
self.ledger_digest
}
#[must_use]
pub const fn ledger_snapshot(&self) -> &LedgerSnapshot {
&self.snapshot
}
#[must_use]
pub const fn executed_protocol_version(&self) -> u32 {
executed_protocol_version(self.snapshot.protocol_version)
}
}
pub fn canonical_ledger_digest(snapshot: &LedgerSnapshot) -> Result<[u8; 32], FixtureError> {
let mut encoded_entries = Vec::with_capacity(snapshot.ledger_entries.len());
for (index, (key, (entry, live_until))) in snapshot.ledger_entries.iter().enumerate() {
let derived_key = entry.to_key();
if key.as_ref() != &derived_key {
return Err(FixtureError::LedgerKeyMismatch { index });
}
let key_xdr = key.to_xdr(Limits::none())?;
let entry_xdr = entry.to_xdr(Limits::none())?;
encoded_entries.push((key_xdr, entry_xdr, *live_until));
}
encoded_entries.sort_unstable_by(|left, right| left.0.cmp(&right.0));
for pair in encoded_entries.windows(2) {
if pair[0].0 == pair[1].0 {
return Err(FixtureError::DuplicateLedgerKey {
key_xdr: pair[0].0.clone(),
});
}
}
let mut digest = Sha256::new();
digest.update(LEDGER_DIGEST_DOMAIN_V1);
digest.update(snapshot.protocol_version.to_be_bytes());
digest.update(snapshot.sequence_number.to_be_bytes());
digest.update(snapshot.timestamp.to_be_bytes());
digest.update(snapshot.network_id);
digest.update(snapshot.base_reserve.to_be_bytes());
digest.update(snapshot.min_persistent_entry_ttl.to_be_bytes());
digest.update(snapshot.min_temp_entry_ttl.to_be_bytes());
digest.update(snapshot.max_entry_ttl.to_be_bytes());
digest.update((encoded_entries.len() as u64).to_be_bytes());
for (key_xdr, entry_xdr, live_until) in encoded_entries {
digest.update((key_xdr.len() as u64).to_be_bytes());
digest.update(key_xdr);
digest.update((entry_xdr.len() as u64).to_be_bytes());
digest.update(entry_xdr);
match live_until {
Some(sequence) => {
digest.update([1]);
digest.update(sequence.to_be_bytes());
}
None => digest.update([0]),
}
}
Ok(digest.finalize().into())
}
#[derive(Debug, Error)]
pub enum FixtureError {
#[error("failed to read ledger snapshot {path}")]
Read {
path: PathBuf,
#[source]
source: SnapshotError,
},
#[error("failed to parse ledger snapshot {path}")]
Parse {
path: PathBuf,
#[source]
source: SnapshotError,
},
#[error(
"ledger protocol {found} is not supported by this Kanatoko release (Host protocol \
{supported}); use the Kanatoko release line for protocol {found}"
)]
UnsupportedProtocol { found: u32, supported: u32 },
#[error("fixture network ID does not match the expected passphrase")]
NetworkMismatch { expected: [u8; 32], found: [u8; 32] },
#[error("ledger entry at index {index} does not match its supplied key")]
LedgerKeyMismatch { index: usize },
#[error("duplicate canonical ledger key")]
DuplicateLedgerKey { key_xdr: Vec<u8> },
#[error("failed to encode canonical ledger XDR")]
Xdr(#[from] soroban_env_host::xdr::Error),
}