use std::collections::BTreeMap;
use std::time::Duration;
use base64::Engine as _;
use canton_core::{Auth, Error, Result, TokenSource};
use canton_daml::Timestamp;
use canton_proto::com::daml::ledger::api::v2 as pb;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::registry::{
ErrorResponse, MAX_RESPONSE_BYTES, read_body_from, read_error_body, transport_error, truncate,
};
const SCAN: &str = "Scan";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_PAGE_SIZE: u32 = 1000;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Route {
Scan,
ScanProxy,
}
#[derive(Clone, Debug)]
pub struct ScanClient {
base: reqwest::Url,
http: reqwest::Client,
auth: Auth,
route: Route,
internal_endpoints: bool,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct ScanContract {
pub template_id: String,
pub contract_id: String,
pub payload: Value,
pub created_event_blob: String,
pub created_at: String,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct ContractWithState {
pub contract: ScanContract,
#[serde(rename = "domain_id", default)]
pub synchronizer_id: Option<String>,
}
impl ScanContract {
pub fn disclosed(&self, synchronizer_id: &str) -> Result<pb::DisclosedContract> {
let created_event_blob = base64::engine::general_purpose::STANDARD
.decode(&self.created_event_blob)
.map_err(|e| {
Error::UnexpectedResponse(format!(
"Scan published contract `{}` with a created-event blob that is not \
base64: {e}",
self.contract_id
))
})?;
Ok(pb::DisclosedContract {
template_id: Some(identifier(&self.template_id)?),
contract_id: self.contract_id.clone(),
created_event_blob,
synchronizer_id: synchronizer_id.to_string(),
})
}
#[must_use]
pub fn disclosed_json(&self, synchronizer_id: &str) -> Value {
serde_json::json!({
"templateId": self.template_id,
"contractId": self.contract_id,
"createdEventBlob": self.created_event_blob,
"synchronizerId": synchronizer_id,
})
}
}
impl ContractWithState {
pub fn disclosed(&self) -> Result<pb::DisclosedContract> {
self.contract.disclosed(self.assigned()?)
}
pub fn disclosed_json(&self) -> Result<Value> {
Ok(self.contract.disclosed_json(self.assigned()?))
}
fn assigned(&self) -> Result<&str> {
self.synchronizer_id.as_deref().ok_or_else(|| {
Error::Connection(format!(
"contract `{}` is being reassigned between synchronizers, so there is none to \
disclose it on yet; retry shortly",
self.contract.contract_id
))
})
}
}
fn identifier(template_id: &str) -> Result<pb::Identifier> {
let mut parts = template_id.split(':');
match (parts.next(), parts.next(), parts.next(), parts.next()) {
(Some(package_id), Some(module_name), Some(entity_name), None)
if !package_id.is_empty() && !module_name.is_empty() && !entity_name.is_empty() =>
{
Ok(pb::Identifier {
package_id: package_id.to_string(),
module_name: module_name.to_string(),
entity_name: entity_name.to_string(),
})
}
_ => Err(Error::UnexpectedResponse(format!(
"Scan published a contract with template id `{template_id}`, which is not \
`<package>:<Module>:<Entity>`"
))),
}
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct DsoInfo {
pub dso_party_id: String,
pub voting_threshold: u32,
pub latest_mining_round: ContractWithState,
pub amulet_rules: ContractWithState,
pub dso_rules: ContractWithState,
pub sv_node_states: Vec<ContractWithState>,
#[serde(default)]
pub initial_round: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct SynchronizerScans {
#[serde(rename = "domainId")]
pub synchronizer_id: String,
pub scans: Vec<ScanInfo>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ScanInfo {
pub public_url: String,
pub sv_name: String,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct MiningRounds {
pub open: Vec<ContractWithState>,
pub issuing: Vec<ContractWithState>,
}
#[derive(Deserialize)]
struct OpenRound {
round: Round,
#[serde(rename = "opensAt")]
opens_at: Timestamp,
}
#[derive(Deserialize)]
struct Round {
#[serde(deserialize_with = "int64")]
number: i64,
}
fn int64<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<i64, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Int {
Text(String),
Number(i64),
}
match Int::deserialize(deserializer)? {
Int::Text(text) => text.parse().map_err(serde::de::Error::custom),
Int::Number(number) => Ok(number),
}
}
impl MiningRounds {
pub fn latest_open(&self, now: Timestamp) -> Result<&ContractWithState> {
let mut latest: Option<(i64, &ContractWithState)> = None;
for round in &self.open {
let fields: OpenRound = serde_json::from_value(round.contract.payload.clone())
.map_err(|e| {
Error::UnexpectedResponse(format!(
"Scan published open mining round `{}` with a payload that is not an \
OpenMiningRound: {e}",
round.contract.contract_id
))
})?;
if fields.opens_at > now {
continue;
}
if latest.is_none_or(|(number, _)| fields.round.number > number) {
latest = Some((fields.round.number, round));
}
}
latest.map(|(_, round)| round).ok_or_else(|| {
Error::Connection(format!(
"none of the {} open mining rounds Scan published has reached its opening time; \
retry shortly",
self.open.len()
))
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct TrafficStatus {
pub total_consumed: i64,
pub total_limit: i64,
pub total_purchased: i64,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct AnsEntry {
#[serde(default)]
pub contract_id: Option<String>,
pub user: String,
pub name: String,
pub url: String,
pub description: String,
#[serde(default)]
pub expires_at: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct HistoryPosition {
#[serde(rename = "after_migration_id")]
pub migration_id: i64,
#[serde(rename = "after_record_time")]
pub record_time: String,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ScanUpdate {
Transaction(ScanTransaction),
Reassignment(ScanReassignment),
}
impl ScanUpdate {
#[must_use]
pub fn position(&self) -> HistoryPosition {
match self {
Self::Transaction(transaction) => HistoryPosition {
migration_id: transaction.migration_id,
record_time: transaction.record_time.clone(),
},
Self::Reassignment(reassignment) => HistoryPosition {
migration_id: match &reassignment.event {
ReassignmentEvent::Assignment(assignment) => assignment.migration_id,
ReassignmentEvent::Unassignment(unassignment) => unassignment.migration_id,
},
record_time: reassignment.record_time.clone(),
},
}
}
#[must_use]
pub fn update_id(&self) -> &str {
match self {
Self::Transaction(transaction) => &transaction.update_id,
Self::Reassignment(reassignment) => &reassignment.update_id,
}
}
}
impl<'de> Deserialize<'de> for ScanUpdate {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
use serde::de::Error as _;
let value = Value::deserialize(deserializer)?;
if value.get("events_by_id").is_some() {
serde_json::from_value(value)
.map(Self::Transaction)
.map_err(D::Error::custom)
} else if value.get("event").is_some() {
serde_json::from_value(value)
.map(Self::Reassignment)
.map_err(D::Error::custom)
} else {
Err(D::Error::custom(
"an update with neither `events_by_id` (a transaction) nor `event` (a \
reassignment)",
))
}
}
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct ScanTransaction {
pub update_id: String,
pub migration_id: i64,
pub workflow_id: String,
pub record_time: String,
pub synchronizer_id: String,
pub effective_at: String,
pub root_event_ids: Vec<String>,
pub events_by_id: BTreeMap<String, ScanEvent>,
#[serde(default)]
pub external_transaction_hash: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "event_type")]
#[non_exhaustive]
pub enum ScanEvent {
#[serde(rename = "created_event")]
Created(ScanCreatedEvent),
#[serde(rename = "exercised_event")]
Exercised(ScanExercisedEvent),
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct ScanCreatedEvent {
pub event_id: String,
pub contract_id: String,
pub template_id: String,
pub package_name: String,
pub create_arguments: Value,
pub created_at: String,
pub signatories: Vec<String>,
pub observers: Vec<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct ScanExercisedEvent {
pub event_id: String,
pub contract_id: String,
pub template_id: String,
pub package_name: String,
pub choice: String,
pub choice_argument: Value,
pub child_event_ids: Vec<String>,
pub exercise_result: Value,
pub consuming: bool,
pub acting_parties: Vec<String>,
#[serde(default)]
pub interface_id: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct ScanReassignment {
pub update_id: String,
pub offset: String,
pub record_time: String,
pub event: ReassignmentEvent,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ReassignmentEvent {
Assignment(ScanAssignment),
Unassignment(ScanUnassignment),
}
impl<'de> Deserialize<'de> for ReassignmentEvent {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
use serde::de::Error as _;
let value = Value::deserialize(deserializer)?;
if value.get("created_event").is_some() {
serde_json::from_value(value)
.map(Self::Assignment)
.map_err(D::Error::custom)
} else if value.get("contract_id").is_some() {
serde_json::from_value(value)
.map(Self::Unassignment)
.map_err(D::Error::custom)
} else {
Err(D::Error::custom(
"a reassignment event with neither `created_event` (an assignment) nor \
`contract_id` (an unassignment)",
))
}
}
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct ScanAssignment {
pub submitter: String,
pub source_synchronizer: String,
pub target_synchronizer: String,
pub migration_id: i64,
pub unassign_id: String,
pub created_event: ScanCreatedEvent,
pub reassignment_counter: i64,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct ScanUnassignment {
pub submitter: String,
pub source_synchronizer: String,
pub migration_id: i64,
pub target_synchronizer: String,
pub unassign_id: String,
pub reassignment_counter: i64,
pub contract_id: String,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct ScanEventItem {
#[serde(default)]
pub update: Option<ScanUpdate>,
#[serde(default)]
pub verdict: Option<Value>,
#[serde(default)]
pub traffic_summary: Option<Value>,
#[serde(default)]
pub app_activity_records: Option<Value>,
#[serde(default)]
pub asset_activity_records: Option<Value>,
#[serde(default)]
pub submitting_app_provider: Option<String>,
}
impl ScanEventItem {
#[must_use]
pub fn position(&self) -> Option<HistoryPosition> {
if let Some(update) = &self.update {
return Some(update.position());
}
let verdict = self.verdict.as_ref()?;
Some(HistoryPosition {
migration_id: verdict.get("migration_id")?.as_i64()?,
record_time: verdict.get("record_time")?.as_str()?.to_string(),
})
}
}
#[derive(Clone, Debug)]
pub struct SnapshotRequest {
migration_id: i64,
record_time: String,
at_or_before: bool,
after: Option<String>,
page_size: u32,
parties: Vec<String>,
templates: Vec<String>,
}
impl SnapshotRequest {
pub fn at(migration_id: i64, record_time: impl Into<String>) -> Self {
Self {
migration_id,
record_time: record_time.into(),
at_or_before: false,
after: None,
page_size: 100,
parties: Vec::new(),
templates: Vec::new(),
}
}
#[must_use]
pub fn at_or_before(mut self) -> Self {
self.at_or_before = true;
self
}
#[must_use]
pub fn with_page_size(mut self, page_size: u32) -> Self {
self.page_size = page_size;
self
}
#[must_use]
pub fn after(mut self, next_page_token: impl Into<String>) -> Self {
self.after = Some(next_page_token.into());
self
}
#[must_use]
pub fn for_parties<I, S>(mut self, parties: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.parties = parties.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn for_templates<I, S>(mut self, templates: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.templates = templates.into_iter().map(Into::into).collect();
self
}
fn record_time_match(&self) -> &'static str {
if self.at_or_before {
"at_or_before"
} else {
"exact"
}
}
fn owners(&self, read: &str) -> Result<&[String]> {
if self.parties.is_empty() {
return Err(Error::InvalidRequest(format!(
"{read} needs at least one owner party (SnapshotRequest::for_parties)"
)));
}
Ok(&self.parties)
}
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct AcsSnapshot {
pub record_time: String,
pub migration_id: i64,
pub created_events: Vec<ActiveContract>,
#[serde(default)]
pub next_page_token: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct ActiveContract {
#[serde(default)]
pub created_in_update_id: Option<String>,
pub contract_id: String,
pub template_id: String,
pub package_name: String,
pub create_arguments: Value,
pub created_at: String,
pub signatories: Vec<String>,
pub observers: Vec<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct HoldingsSummaries {
pub record_time: String,
pub migration_id: i64,
pub summaries: Vec<HoldingsSummary>,
}
#[derive(Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct HoldingsSummary {
pub party_id: String,
pub total_unlocked_coin: String,
pub total_locked_coin: String,
pub total_coin_holdings: String,
}
impl ScanClient {
pub fn new(base_url: &str) -> Result<Self> {
Self::with_http_client(base_url, default_http_client()?)
}
pub fn with_http_client(base_url: &str, http: reqwest::Client) -> Result<Self> {
Self::build(base_url, http, Route::Scan)
}
pub fn through_validator(base_url: &str) -> Result<Self> {
Self::through_validator_with_http_client(base_url, default_http_client()?)
}
pub fn through_validator_with_http_client(
base_url: &str,
http: reqwest::Client,
) -> Result<Self> {
Self::build(base_url, http, Route::ScanProxy)
}
fn build(base_url: &str, http: reqwest::Client, route: Route) -> Result<Self> {
let normalised = format!("{}/", base_url.trim_end_matches('/'));
let base = reqwest::Url::parse(&normalised)
.map_err(|e| Error::InvalidRequest(format!("`{base_url}` is not a Scan URL: {e}")))?;
Ok(Self {
base,
http,
auth: Auth::None,
route,
internal_endpoints: false,
})
}
#[must_use]
pub fn with_token(mut self, token: impl Into<String>) -> Self {
self.auth = Auth::Static(token.into());
self
}
#[must_use]
pub fn with_token_source(mut self, source: impl TokenSource + 'static) -> Self {
self.auth = Auth::Dynamic(std::sync::Arc::new(source));
self
}
#[must_use]
pub fn with_internal_endpoints(mut self) -> Self {
self.internal_endpoints = true;
self
}
fn url(&self, version: &str, segments: &[&str]) -> Result<reqwest::Url> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|()| {
Error::InvalidRequest("the Scan URL cannot have a path".to_string())
})?;
path.pop_if_empty().push(version);
if self.route == Route::ScanProxy {
path.push("scan-proxy");
}
path.extend(segments);
}
Ok(url)
}
fn scan_only(&self, read: &str) -> Result<()> {
if self.route == Route::ScanProxy {
return Err(Error::InvalidRequest(format!(
"a validator's scan-proxy does not serve {read}; ask a Scan for it \
(ScanClient::new)"
)));
}
Ok(())
}
fn internal(&self, read: &str) -> Result<()> {
if self.route == Route::Scan && !self.internal_endpoints {
return Err(Error::InvalidRequest(format!(
"{read} is an endpoint Scan tags internal, which Splice may change in any \
release; opt in with ScanClient::with_internal_endpoints(), or go through a \
validator's scan-proxy (ScanClient::through_validator), which serves it as \
part of its API"
)));
}
Ok(())
}
pub async fn dso_party_id(&self) -> Result<String> {
#[derive(Deserialize)]
struct Reply {
dso_party_id: String,
}
let reply: Reply = self.get(self.url("v0", &["dso-party-id"])?).await?;
Ok(reply.dso_party_id)
}
pub async fn dso(&self) -> Result<DsoInfo> {
match self.get(self.url("v1", &["dso"])?).await {
Err(Error::Http { status: 404, .. }) => self.get(self.url("v0", &["dso"])?).await,
answer => answer,
}
}
pub async fn scans(&self) -> Result<Vec<SynchronizerScans>> {
#[derive(Deserialize)]
struct Reply {
scans: Vec<SynchronizerScans>,
}
self.scan_only("the list of Scans")?;
let reply: Reply = self.get(self.url("v0", &["scans"])?).await?;
Ok(reply.scans)
}
pub async fn open_and_issuing_mining_rounds(&self) -> Result<MiningRounds> {
#[derive(Serialize)]
struct Cached {
cached_open_mining_round_contract_ids: [String; 0],
cached_issuing_round_contract_ids: [String; 0],
}
#[derive(Deserialize)]
struct MaybeCached {
#[serde(default)]
contract: Option<ScanContract>,
#[serde(default)]
domain_id: Option<String>,
}
#[derive(Deserialize)]
struct FromScan {
open_mining_rounds: BTreeMap<String, MaybeCached>,
issuing_mining_rounds: BTreeMap<String, MaybeCached>,
}
#[derive(Deserialize)]
struct FromProxy {
open_mining_rounds: Vec<ContractWithState>,
issuing_mining_rounds: Vec<ContractWithState>,
}
fn all(rounds: BTreeMap<String, MaybeCached>) -> Result<Vec<ContractWithState>> {
rounds
.into_iter()
.map(|(contract_id, round)| {
let contract = round.contract.ok_or_else(|| {
Error::UnexpectedResponse(format!(
"Scan left out mining round `{contract_id}` as cached, where this \
client told it nothing was"
))
})?;
Ok(ContractWithState {
contract,
synchronizer_id: round.domain_id,
})
})
.collect()
}
let url = self.url("v0", &["open-and-issuing-mining-rounds"])?;
match self.route {
Route::Scan => {
let reply: FromScan = self
.post(
url,
&Cached {
cached_open_mining_round_contract_ids: [],
cached_issuing_round_contract_ids: [],
},
)
.await?;
Ok(MiningRounds {
open: all(reply.open_mining_rounds)?,
issuing: all(reply.issuing_mining_rounds)?,
})
}
Route::ScanProxy => {
let reply: FromProxy = self.get(url).await?;
Ok(MiningRounds {
open: reply.open_mining_rounds,
issuing: reply.issuing_mining_rounds,
})
}
}
}
pub async fn latest_open_mining_round(&self) -> Result<ContractWithState> {
let rounds = self.open_and_issuing_mining_rounds().await?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()
.and_then(|since| i64::try_from(since.as_micros()).ok())
.ok_or_else(|| {
Error::InvalidRequest("the system clock is not a time after 1970".to_string())
})?;
rounds.latest_open(Timestamp(now)).cloned()
}
pub async fn closed_rounds(&self) -> Result<Vec<ScanContract>> {
#[derive(Deserialize)]
struct Reply {
rounds: Vec<ScanContract>,
}
self.scan_only("the closed mining rounds")?;
let reply: Reply = self.get(self.url("v0", &["closed-rounds"])?).await?;
Ok(reply.rounds)
}
pub async fn amulet_rules(&self) -> Result<ContractWithState> {
#[derive(Deserialize)]
struct MaybeCached {
#[serde(default)]
contract: Option<ScanContract>,
#[serde(default)]
domain_id: Option<String>,
}
#[derive(Deserialize)]
struct FromScan {
amulet_rules_update: MaybeCached,
}
#[derive(Deserialize)]
struct FromProxy {
amulet_rules: ContractWithState,
}
if self.route == Route::Scan && !self.internal_endpoints {
return Ok(self.dso().await?.amulet_rules);
}
let url = self.url("v0", &["amulet-rules"])?;
match self.route {
Route::Scan => {
let reply: FromScan = self.post(url, &serde_json::json!({})).await?;
let contract = reply.amulet_rules_update.contract.ok_or_else(|| {
Error::UnexpectedResponse(
"Scan left out the Amulet rules as cached, where this client told it \
nothing was"
.to_string(),
)
})?;
Ok(ContractWithState {
contract,
synchronizer_id: reply.amulet_rules_update.domain_id,
})
}
Route::ScanProxy => {
let reply: FromProxy = self.get(url).await?;
Ok(reply.amulet_rules)
}
}
}
pub async fn featured_app_right(&self, provider: &str) -> Result<Option<ScanContract>> {
#[derive(Deserialize)]
struct Reply {
#[serde(default)]
featured_app_right: Option<ScanContract>,
}
self.internal("a featured application right")?;
let reply: Reply = self
.get(self.url("v0", &["featured-apps", provider])?)
.await?;
Ok(reply.featured_app_right)
}
pub async fn transfer_preapproval_by_party(
&self,
party: &str,
) -> Result<Option<ContractWithState>> {
#[derive(Deserialize)]
struct Reply {
transfer_preapproval: ContractWithState,
}
self.internal("a transfer preapproval")?;
let url = self.url("v0", &["transfer-preapprovals", "by-party", party])?;
let reply: Option<Reply> = self.get_optional(url).await?;
Ok(reply.map(|reply| reply.transfer_preapproval))
}
pub async fn member_traffic_status(
&self,
synchronizer_id: &str,
member_id: &str,
) -> Result<TrafficStatus> {
#[derive(Deserialize)]
struct Reply {
traffic_status: Status,
}
#[derive(Deserialize)]
struct Status {
actual: Actual,
target: Target,
}
#[derive(Deserialize)]
struct Actual {
total_consumed: i64,
total_limit: i64,
}
#[derive(Deserialize)]
struct Target {
total_purchased: i64,
}
self.scan_only("a member's traffic status")?;
let url = self.url(
"v0",
&[
"domains",
synchronizer_id,
"members",
member_id,
"traffic-status",
],
)?;
let reply: Reply = self.get(url).await?;
Ok(TrafficStatus {
total_consumed: reply.traffic_status.actual.total_consumed,
total_limit: reply.traffic_status.actual.total_limit,
total_purchased: reply.traffic_status.target.total_purchased,
})
}
pub async fn ans_entry_by_party(&self, party: &str) -> Result<Option<AnsEntry>> {
self.ans_entry(&["ans-entries", "by-party", party]).await
}
pub async fn ans_entry_by_name(&self, name: &str) -> Result<Option<AnsEntry>> {
self.ans_entry(&["ans-entries", "by-name", name]).await
}
async fn ans_entry(&self, segments: &[&str]) -> Result<Option<AnsEntry>> {
#[derive(Deserialize)]
struct Reply {
entry: AnsEntry,
}
let reply: Option<Reply> = self.get_optional(self.url("v0", segments)?).await?;
Ok(reply.map(|reply| reply.entry))
}
pub async fn ans_entries(
&self,
name_prefix: Option<&str>,
page_size: u32,
) -> Result<Vec<AnsEntry>> {
#[derive(Deserialize)]
struct Reply {
entries: Vec<AnsEntry>,
}
let mut url = self.url("v0", &["ans-entries"])?;
{
let mut query = url.query_pairs_mut();
if let Some(name_prefix) = name_prefix {
query.append_pair("name_prefix", name_prefix);
}
query.append_pair("page_size", &page_size.to_string());
}
let reply: Reply = self.get(url).await?;
Ok(reply.entries)
}
pub async fn updates(
&self,
after: Option<&HistoryPosition>,
page_size: u32,
) -> Result<Vec<ScanUpdate>> {
#[derive(Deserialize)]
struct Reply {
transactions: Vec<ScanUpdate>,
}
self.scan_only("the update history")?;
let reply: Reply = self
.post(
self.url("v2", &["updates"])?,
&history_request(after, page_size)?,
)
.await?;
Ok(reply.transactions)
}
pub async fn update(&self, update_id: &str) -> Result<Option<ScanUpdate>> {
self.scan_only("an update")?;
self.get_optional(self.url("v2", &["updates", update_id])?)
.await
}
pub async fn events(
&self,
after: Option<&HistoryPosition>,
page_size: u32,
) -> Result<Vec<ScanEventItem>> {
#[derive(Deserialize)]
struct Reply {
events: Vec<ScanEventItem>,
}
self.scan_only("the event history")?;
let reply: Reply = self
.post(
self.url("v0", &["events"])?,
&history_request(after, page_size)?,
)
.await?;
Ok(reply.events)
}
pub async fn acs_snapshot_timestamp(
&self,
before: &str,
migration_id: i64,
) -> Result<Option<String>> {
#[derive(Deserialize)]
struct Reply {
record_time: String,
}
self.scan_only("the snapshot times")?;
let mut url = self.url("v0", &["state", "acs", "snapshot-timestamp"])?;
url.query_pairs_mut()
.append_pair("before", before)
.append_pair("migration_id", &migration_id.to_string());
let reply: Option<Reply> = self.get_optional(url).await?;
Ok(reply.map(|reply| reply.record_time))
}
pub async fn acs_snapshot(&self, request: &SnapshotRequest) -> Result<AcsSnapshot> {
self.scan_only("the snapshots of the active contracts")?;
let mut body = serde_json::json!({
"migration_id": request.migration_id,
"record_time": request.record_time,
"record_time_match": request.record_time_match(),
"page_size": page_size(request.page_size)?,
});
if let Some(after) = &request.after {
set(&mut body, "after", Value::from(after.as_str()));
}
if !request.parties.is_empty() {
set(&mut body, "party_ids", Value::from(request.parties.clone()));
}
if !request.templates.is_empty() {
set(
&mut body,
"templates",
Value::from(request.templates.clone()),
);
}
self.post(self.url("v2", &["state", "acs"])?, &body).await
}
pub async fn holdings_state(&self, request: &SnapshotRequest) -> Result<AcsSnapshot> {
self.scan_only("the holdings at a snapshot")?;
let mut body = serde_json::json!({
"migration_id": request.migration_id,
"record_time": request.record_time,
"record_time_match": request.record_time_match(),
"page_size": page_size(request.page_size)?,
"owner_party_ids": request.owners("a holdings read")?,
});
if let Some(after) = &request.after {
set(&mut body, "after", Value::from(after.as_str()));
}
self.post(self.url("v2", &["holdings", "state"])?, &body)
.await
}
pub async fn holdings_summary(&self, request: &SnapshotRequest) -> Result<HoldingsSummaries> {
let body = serde_json::json!({
"migration_id": request.migration_id,
"record_time": request.record_time,
"record_time_match": request.record_time_match(),
"owner_party_ids": request.owners("a holdings summary")?,
});
self.post(self.url("v1", &["holdings", "summary"])?, &body)
.await
}
pub async fn get_json(
&self,
version: &str,
segments: &[&str],
query: &[(&str, &str)],
) -> Result<Value> {
let mut url = self.url(version, segments)?;
if !query.is_empty() {
url.query_pairs_mut().extend_pairs(query);
}
self.get(url).await
}
pub async fn post_json(&self, version: &str, segments: &[&str], body: &Value) -> Result<Value> {
self.post(self.url(version, segments)?, body).await
}
async fn send(&self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
let request = match self.auth.bearer().await? {
Some(token) => request.bearer_auth(token),
None => request,
};
request.send().await.map_err(|e| transport_error(e, SCAN))
}
async fn get<T: serde::de::DeserializeOwned>(&self, url: reqwest::Url) -> Result<T> {
let response = self.send(self.http.get(url.clone())).await?;
decode(response, url.as_str()).await
}
async fn post<T: serde::de::DeserializeOwned>(
&self,
url: reqwest::Url,
body: &(impl Serialize + ?Sized),
) -> Result<T> {
let response = self.send(self.http.post(url.clone()).json(body)).await?;
decode(response, url.as_str()).await
}
async fn get_optional<T: serde::de::DeserializeOwned>(
&self,
url: reqwest::Url,
) -> Result<Option<T>> {
let response = self.send(self.http.get(url.clone())).await?;
if response.status() == reqwest::StatusCode::NOT_FOUND {
let body = read_error_body(response, url.as_str(), SCAN).await?;
let trimmed = body.trim();
if serde_json::from_str::<ErrorResponse>(trimmed).is_ok() {
return Ok(None);
}
tracing::warn!(%url, "a 404 that is not Scan's own — check the base URL");
return Err(Error::http_at(404, truncate(trimmed), url.as_str()));
}
Ok(Some(decode(response, url.as_str()).await?))
}
}
fn default_http_client() -> Result<reqwest::Client> {
reqwest::Client::builder()
.timeout(DEFAULT_TIMEOUT)
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|e| Error::InvalidRequest(format!("cannot build an HTTP client: {e}")))
}
fn page_size(page_size: u32) -> Result<u32> {
if page_size == 0 || page_size > MAX_PAGE_SIZE {
return Err(Error::InvalidRequest(format!(
"a page of {page_size} is not one Scan serves: it takes 1 to {MAX_PAGE_SIZE}"
)));
}
Ok(page_size)
}
fn set(object: &mut Value, key: &str, value: Value) {
if let Some(fields) = object.as_object_mut() {
fields.insert(key.to_string(), value);
}
}
fn history_request(after: Option<&HistoryPosition>, size: u32) -> Result<Value> {
let mut body = serde_json::json!({ "page_size": page_size(size)? });
if let Some(after) = after {
let after = serde_json::to_value(after).map_err(|e| {
Error::InvalidRequest(format!("a history position that is not JSON: {e}"))
})?;
set(&mut body, "after", after);
}
Ok(body)
}
async fn decode<T: serde::de::DeserializeOwned>(
response: reqwest::Response,
url: &str,
) -> Result<T> {
let status = response.status();
let body = if status.is_success() {
read_body_from(response, MAX_RESPONSE_BYTES, url, SCAN).await?
} else {
read_error_body(response, url, SCAN).await?
};
if !status.is_success() {
tracing::warn!(%url, status = status.as_u16(), "Scan answered with an error");
let message = serde_json::from_str::<ErrorResponse>(&body)
.map(|e| e.error)
.unwrap_or(body);
return Err(Error::http_at(status.as_u16(), truncate(&message), url));
}
serde_json::from_str(&body).map_err(|e| {
Error::UnexpectedResponse(format!(
"{url} returned a body this does not understand: {e}"
))
})
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
fn contract(contract_id: &str, payload: Value) -> ContractWithState {
ContractWithState {
contract: ScanContract {
template_id: "pkg:Splice.Round:OpenMiningRound".to_string(),
contract_id: contract_id.to_string(),
payload,
created_event_blob: base64::engine::general_purpose::STANDARD.encode([1, 2, 3]),
created_at: "2026-11-26T10:00:00Z".to_string(),
},
synchronizer_id: Some("global-domain::1220aa".to_string()),
}
}
fn round(number: i64, opens_at: &str) -> ContractWithState {
contract(
&format!("00round{number}"),
serde_json::json!({
"round": { "number": number.to_string() },
"opensAt": opens_at,
"targetClosesAt": "2026-11-26T12:00:00Z",
}),
)
}
fn at(time: &str) -> Timestamp {
serde_json::from_value(Value::from(time)).unwrap()
}
#[test]
fn the_latest_open_round_is_the_highest_one_whose_opening_time_has_come() {
let rounds = MiningRounds {
open: vec![
round(11, "2026-11-26T10:10:00.000000Z"),
round(10, "2026-11-26T10:00:00.000000Z"),
round(12, "2026-11-26T10:20:00.000000Z"),
],
issuing: Vec::new(),
};
let pick = |now: &str| {
rounds
.latest_open(at(now))
.map(|round| round.contract.contract_id.clone())
};
assert_eq!(pick("2026-11-26T10:15:00Z").unwrap(), "00round11");
assert_eq!(pick("2026-11-26T10:05:00Z").unwrap(), "00round10");
assert_eq!(pick("2026-11-26T10:20:00Z").unwrap(), "00round12");
assert_eq!(pick("2026-11-27T00:00:00Z").unwrap(), "00round12");
let error = pick("2026-11-26T09:00:00Z").unwrap_err();
assert!(error.is_retriable(), "{error:?}");
assert!(
error.to_string().contains("3 open mining rounds"),
"{error}"
);
}
#[test]
fn round_numbers_compare_as_numbers_whether_written_as_text_or_not() {
let mut as_number = round(9, "2026-11-26T09:50:00Z");
as_number.contract.payload["round"]["number"] = Value::from(9);
let rounds = MiningRounds {
open: vec![round(10, "2026-11-26T10:00:00Z"), as_number],
issuing: Vec::new(),
};
let latest = rounds.latest_open(at("2026-11-26T11:00:00Z")).unwrap();
assert_eq!(latest.contract.contract_id, "00round10");
}
#[test]
fn a_round_that_is_not_an_open_mining_round_is_an_unexpected_response() {
let rounds = MiningRounds {
open: vec![contract("00odd", serde_json::json!({ "round": {} }))],
issuing: Vec::new(),
};
let error = rounds.latest_open(at("2026-11-26T11:00:00Z")).unwrap_err();
assert!(matches!(error, Error::UnexpectedResponse(_)), "{error:?}");
assert!(error.to_string().contains("00odd"), "{error}");
}
#[test]
fn a_contract_is_disclosed_as_bytes_for_grpc_and_base64_for_json() {
let rules = contract("00rules", serde_json::json!({}));
let disclosed = rules.disclosed().unwrap();
assert_eq!(disclosed.contract_id, "00rules");
assert_eq!(disclosed.created_event_blob, [1, 2, 3]);
assert_eq!(disclosed.synchronizer_id, "global-domain::1220aa");
let template = disclosed.template_id.unwrap();
assert_eq!(
(
template.package_id.as_str(),
template.module_name.as_str(),
template.entity_name.as_str()
),
("pkg", "Splice.Round", "OpenMiningRound")
);
let json = rules.disclosed_json().unwrap();
assert_eq!(json["createdEventBlob"], "AQID");
assert_eq!(json["synchronizerId"], "global-domain::1220aa");
assert_eq!(json["templateId"], "pkg:Splice.Round:OpenMiningRound");
}
#[test]
fn a_contract_that_cannot_be_disclosed_says_why() {
let mut in_transit = contract("00moving", serde_json::json!({}));
in_transit.synchronizer_id = None;
let error = in_transit.disclosed().unwrap_err();
assert!(error.is_retriable(), "{error:?}");
assert!(in_transit.disclosed_json().is_err());
for template_id in ["pkg:Module", "pkg:Module:Entity:Extra", "::", ""] {
let mut odd = contract("00odd", serde_json::json!({}));
odd.contract.template_id = template_id.to_string();
let error = odd.disclosed().unwrap_err();
assert!(matches!(error, Error::UnexpectedResponse(_)), "{error:?}");
}
let mut odd = contract("00blob", serde_json::json!({}));
odd.contract.created_event_blob = "not base64!!".to_string();
let error = odd.disclosed().unwrap_err();
assert!(error.to_string().contains("00blob"), "{error}");
}
#[test]
fn updates_are_told_apart_by_their_fields() {
let transaction: ScanUpdate = serde_json::from_value(serde_json::json!({
"update_id": "1220tx",
"migration_id": 4,
"workflow_id": "",
"record_time": "2026-11-26T10:00:00.000000Z",
"synchronizer_id": "global-domain::1220aa",
"effective_at": "2026-11-26T09:59:59.000000Z",
"root_event_ids": ["1220tx:0"],
"events_by_id": {
"1220tx:0": {
"event_type": "exercised_event",
"event_id": "1220tx:0",
"contract_id": "00rules",
"template_id": "pkg:Splice.AmuletRules:AmuletRules",
"package_name": "splice-amulet",
"choice": "AmuletRules_Transfer",
"choice_argument": {},
"child_event_ids": ["1220tx:1"],
"exercise_result": {},
"consuming": false,
"acting_parties": ["alice::1220"],
},
"1220tx:1": {
"event_type": "created_event",
"event_id": "1220tx:1",
"contract_id": "00amulet",
"template_id": "pkg:Splice.Amulet:Amulet",
"package_name": "splice-amulet",
"create_arguments": { "owner": "bob::1220" },
"created_at": "2026-11-26T09:59:59.000000Z",
"signatories": ["DSO::1220"],
"observers": [],
},
},
}))
.unwrap();
assert_eq!(transaction.update_id(), "1220tx");
assert_eq!(
transaction.position(),
HistoryPosition {
migration_id: 4,
record_time: "2026-11-26T10:00:00.000000Z".to_string(),
}
);
let ScanUpdate::Transaction(transaction) = transaction else {
panic!("a transaction");
};
assert!(matches!(
transaction.events_by_id["1220tx:0"],
ScanEvent::Exercised(_)
));
assert!(matches!(
transaction.events_by_id["1220tx:1"],
ScanEvent::Created(_)
));
let unassigned: ScanUpdate = serde_json::from_value(serde_json::json!({
"update_id": "1220out",
"offset": "000a",
"record_time": "2026-11-26T10:01:00.000000Z",
"event": {
"submitter": "alice::1220",
"source_synchronizer": "one::1220",
"target_synchronizer": "two::1220",
"migration_id": 5,
"unassign_id": "u1",
"reassignment_counter": 1,
"contract_id": "00moving",
},
}))
.unwrap();
assert_eq!(unassigned.position().migration_id, 5);
assert!(matches!(
unassigned,
ScanUpdate::Reassignment(ScanReassignment {
event: ReassignmentEvent::Unassignment(_),
..
})
));
let neither = serde_json::from_value::<ScanUpdate>(serde_json::json!({
"update_id": "1220odd",
}))
.unwrap_err();
assert!(neither.to_string().contains("events_by_id"), "{neither}");
}
#[test]
fn an_event_entry_has_a_position_with_or_without_an_update() {
let rejected: ScanEventItem = serde_json::from_value(serde_json::json!({
"update": null,
"verdict": {
"update_id": "1220rejected",
"migration_id": 4,
"domain_id": "global-domain::1220aa",
"record_time": "2026-11-26T10:02:00.000000Z",
"finalization_time": "2026-11-26T10:02:01.000000Z",
"submitting_parties": ["alice::1220"],
"submitting_participant_uid": "participant::1220",
"verdict_result": "VERDICT_RESULT_REJECTED",
"mediator_group": 0,
"transaction_views": { "views": [], "root_views": [] },
},
"asset_activity_records": [],
"submitting_app_provider": "provider::1220",
}))
.unwrap();
assert!(rejected.update.is_none());
assert_eq!(
rejected.position(),
Some(HistoryPosition {
migration_id: 4,
record_time: "2026-11-26T10:02:00.000000Z".to_string(),
})
);
assert_eq!(
rejected.submitting_app_provider.as_deref(),
Some("provider::1220")
);
assert!(rejected.asset_activity_records.is_some());
let empty: ScanEventItem = serde_json::from_value(serde_json::json!({})).unwrap();
assert_eq!(empty.position(), None);
}
#[test]
fn a_history_position_is_the_after_of_the_next_page() {
let after = HistoryPosition {
migration_id: 4,
record_time: "2026-11-26T10:00:00.000000Z".to_string(),
};
assert_eq!(
history_request(Some(&after), 50).unwrap(),
serde_json::json!({
"page_size": 50,
"after": {
"after_migration_id": 4,
"after_record_time": "2026-11-26T10:00:00.000000Z",
},
})
);
assert_eq!(
history_request(None, 1).unwrap(),
serde_json::json!({ "page_size": 1 })
);
for size in [0, 1001] {
let error = history_request(None, size).unwrap_err();
assert!(matches!(error, Error::InvalidRequest(_)), "{error:?}");
}
}
}