Skip to main content

canton_token/
registry.rs

1//! The registry's off-ledger HTTP API.
2//!
3//! Every path and payload here comes from the token standard's OpenAPI
4//! documents — `token-metadata-v1`, `transfer-instruction-v1`,
5//! `allocation-v1`, `allocation-instruction-v1`, `transfer-instruction-v2`,
6//! `allocation-v2`, `allocation-instruction-v2` (vendored under
7//! `testdata/openapi/`) — and the method names follow their `operationId`s,
8//! so a reader can match one to the other.
9//!
10//! # What the registry is for
11//!
12//! Two things. It *describes* the instruments it issues (the metadata API),
13//! and it supplies the **choice context** for exercising a token-standard
14//! choice: the reference data and the contracts a participant must be shown.
15//! A client cannot assemble that itself — the contracts are the registry's own
16//! and usually invisible to the submitting party.
17
18use canton_core::{Auth, Error, Result, TokenSource};
19use serde::{Deserialize, Serialize};
20
21use crate::context::{ChoiceContext, ChoiceContextRequest, WireChoiceContext};
22
23/// A client for one registry's off-ledger API.
24/// How long to wait on a registry that accepts the connection and then says
25/// nothing. `reqwest`'s own default is unbounded, which turns an unresponsive
26/// registry into a transfer that never returns.
27const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
28
29/// A client for one registry's off-ledger API.
30#[derive(Clone, Debug)]
31pub struct RegistryClient {
32    base: reqwest::Url,
33    http: reqwest::Client,
34    auth: Auth,
35}
36
37/// What a registry says about itself.
38#[derive(Clone, Debug, Deserialize)]
39#[serde(rename_all = "camelCase")]
40#[non_exhaustive]
41pub struct RegistryInfo {
42    /// The party that administers the instruments — the `expectedAdmin` a
43    /// factory choice is exercised against.
44    pub admin_id: String,
45    /// Which token-standard APIs this registry implements.
46    #[serde(default)]
47    pub supported_apis: std::collections::BTreeMap<String, i32>,
48}
49
50/// An instrument the registry issues.
51#[derive(Clone, Debug, Deserialize)]
52#[serde(rename_all = "camelCase")]
53#[non_exhaustive]
54pub struct Instrument {
55    /// The instrument id, as it appears in a `Holding`.
56    pub id: String,
57    /// Human-readable name.
58    pub name: String,
59    /// Ticker-style symbol.
60    pub symbol: String,
61    /// Total supply, when the registry publishes one.
62    #[serde(default)]
63    pub total_supply: Option<String>,
64    /// When `total_supply` was measured.
65    #[serde(default)]
66    pub total_supply_as_of: Option<String>,
67    /// How many decimal places amounts of this instrument carry.
68    ///
69    /// The standard marks this required with a default of 10, so an absent
70    /// field means ten places — not "unknown". Reporting it as unknown pushes a
71    /// display-precision decision about money onto a caller who has no better
72    /// information than this default.
73    #[serde(default = "default_decimals")]
74    pub decimals: i32,
75    /// Which token-standard APIs apply to this instrument.
76    #[serde(default)]
77    pub supported_apis: std::collections::BTreeMap<String, i32>,
78    /// A paused instrument cannot be transferred or allocated (metadata-v1
79    /// 1.2.0). Absent on older registries, which is the same as `false`.
80    #[serde(default)]
81    pub paused: bool,
82    /// Why, and until when, if the registry says.
83    #[serde(default)]
84    pub pause_info: Option<PauseInfo>,
85    /// For V2 wallets: which `Account` input fields this instrument's users
86    /// must fill in — `provider`, `accountId`. Absent means the registry did
87    /// not say, not that there are none.
88    #[serde(default)]
89    pub account_input_fields_to_show: Option<Vec<String>>,
90}
91
92/// Why an instrument is paused, and until when.
93#[derive(Clone, Debug, Deserialize)]
94#[serde(rename_all = "camelCase")]
95#[non_exhaustive]
96pub struct PauseInfo {
97    /// Free text from the registry.
98    #[serde(default)]
99    pub reason: Option<String>,
100    /// RFC 3339, when the pause is scheduled to end.
101    #[serde(default)]
102    pub until: Option<String>,
103}
104
105/// The standard's default for `decimals`.
106fn default_decimals() -> i32 {
107    10
108}
109
110#[derive(Debug, Deserialize)]
111#[serde(rename_all = "camelCase")]
112struct ListInstrumentsResponse {
113    #[serde(default)]
114    instruments: Vec<Instrument>,
115    #[serde(default)]
116    next_page_token: Option<String>,
117}
118
119/// How a transfer will be carried out, as the registry decides.
120///
121/// Not a caller's choice: it follows from whether the receiver has pre-approved
122/// direct transfers, and whether sender and receiver are the same party. A
123/// client that assumes `Direct` and gets `Offer` has a transfer that is
124/// pending someone else's acceptance, which is a different workflow.
125#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)]
126#[serde(rename_all = "lowercase")]
127#[non_exhaustive]
128pub enum TransferKind {
129    /// Sender and receiver are the same party; no approval, usually immediate.
130    #[serde(rename = "self")]
131    SelfTransfer,
132    /// The receiver has pre-approved direct transfers, so it completes at once.
133    Direct,
134    /// The receiver is offered the transfer and it completes only if accepted.
135    Offer,
136    /// A kind this build does not know.
137    ///
138    /// Without this, a registry that adds a fourth kind makes the whole factory
139    /// response fail to decode and *every* transfer stop — including the ones
140    /// whose kind is perfectly understood. `#[non_exhaustive]` promises a
141    /// caller their match will keep compiling; this is what makes the promise
142    /// reach runtime.
143    #[serde(other)]
144    Unknown,
145}
146
147/// A factory contract together with the context for exercising its choice.
148#[derive(Clone, Debug)]
149#[non_exhaustive]
150pub struct FactoryWithContext {
151    /// The contract id of the contract implementing the factory interface.
152    pub factory_id: String,
153    /// How the transfer will be carried out. `None` for factories whose API
154    /// does not classify the workflow — the allocation factory, for one.
155    pub transfer_kind: Option<TransferKind>,
156    /// The context for the factory's choice.
157    pub context: ChoiceContext,
158}
159
160/// `TransferFactoryWithChoiceContext` — `transferKind` is `required` here.
161#[derive(Debug, Deserialize)]
162#[serde(rename_all = "camelCase")]
163struct WireTransferFactory {
164    factory_id: String,
165    transfer_kind: TransferKind,
166    choice_context: WireChoiceContext,
167}
168
169/// `FactoryWithChoiceContext` — the allocation API has no `transferKind` at
170/// all. Kept separate from the transfer factory so that "this API does not
171/// classify the workflow" and "a registry omitted a required field" cannot
172/// arrive as the same value.
173#[derive(Debug, Deserialize)]
174#[serde(rename_all = "camelCase")]
175struct WireFactory {
176    factory_id: String,
177    choice_context: WireChoiceContext,
178}
179
180/// A request for a factory.
181///
182/// `choice_arguments` is the choice as the Daml JSON API encodes it, **with
183/// `extraArgs.context` and `extraArgs.meta` empty** — the standard says so
184/// explicitly, and it is what lets a registry tailor the context to the actual
185/// arguments (the configuration for one instrument id, say).
186///
187/// So the argument is a *generated* choice type, serialized. Nothing here
188/// hand-writes the JSON.
189#[derive(Debug, Serialize)]
190#[serde(rename_all = "camelCase")]
191struct GetFactoryRequest<'a> {
192    choice_arguments: &'a serde_json::Value,
193    #[serde(skip_serializing_if = "std::ops::Not::not")]
194    exclude_debug_fields: bool,
195}
196
197impl RegistryClient {
198    /// A client for the registry served at `base_url`.
199    ///
200    /// The URL is parsed here rather than at the first request, so a typo is a
201    /// configuration error the caller sees immediately — and not, as it was, a
202    /// `Connection` failure that the SDK reports as retriable and an
203    /// application retries forever.
204    ///
205    /// # Errors
206    /// [`Error::InvalidRequest`] if `base_url` is not a URL, or an HTTP client
207    /// cannot be built.
208    pub fn new(base_url: &str) -> Result<Self> {
209        // No redirects: what the registry answers is put into commands the
210        // caller signs, so it must come from the registry the caller named,
211        // not from wherever a 3xx points.
212        let http = reqwest::Client::builder()
213            .timeout(DEFAULT_TIMEOUT)
214            .redirect(reqwest::redirect::Policy::none())
215            .build()
216            .map_err(|e| Error::InvalidRequest(format!("cannot build an HTTP client: {e}")))?;
217        Self::with_http_client(base_url, http)
218    }
219
220    /// A client using an HTTP client the caller has already configured —
221    /// timeouts, proxies, a custom TLS root store. Configure it with
222    /// `reqwest::redirect::Policy::none()`, as [`Self::new`] does: a registry
223    /// answer reached through a redirect is not the registry's.
224    ///
225    /// # Errors
226    /// [`Error::InvalidRequest`] if `base_url` is not a URL.
227    pub fn with_http_client(base_url: &str, http: reqwest::Client) -> Result<Self> {
228        // A trailing slash matters to `Url::join`, and the paths below are
229        // relative, so it is normalised here once.
230        let normalised = format!("{}/", base_url.trim_end_matches('/'));
231        let base = reqwest::Url::parse(&normalised).map_err(|e| {
232            Error::InvalidRequest(format!("`{base_url}` is not a registry URL: {e}"))
233        })?;
234        Ok(Self {
235            base,
236            http,
237            auth: Auth::None,
238        })
239    }
240
241    /// Send a bearer token with every request.
242    ///
243    /// A registry answers without one. A validator's scan-proxy, which serves
244    /// the Amulet registry under `/api/validator/v0/scan-proxy`, does not: it
245    /// authenticates every route.
246    #[must_use]
247    pub fn with_token(mut self, token: impl Into<String>) -> Self {
248        self.auth = Auth::Static(token.into());
249        self
250    }
251
252    /// Send a bearer token from a source that refreshes it, such as
253    /// `canton_auth::TokenProvider`. See [`with_token`](Self::with_token).
254    #[must_use]
255    pub fn with_token_source(mut self, source: impl TokenSource + 'static) -> Self {
256        self.auth = Auth::Dynamic(std::sync::Arc::new(source));
257        self
258    }
259
260    /// `request` with the bearer token, when one is configured.
261    async fn authorized(
262        &self,
263        request: reqwest::RequestBuilder,
264    ) -> Result<reqwest::RequestBuilder> {
265        Ok(match self.auth.bearer().await? {
266            Some(token) => request.bearer_auth(token),
267            None => request,
268        })
269    }
270
271    /// Build a URL from path segments.
272    ///
273    /// Every segment is **percent-encoded**. Interpolating them into a string
274    /// let a caller-supplied id change which resource was addressed: an
275    /// instrument id of `a?b` fetched instrument `a` and returned its name,
276    /// symbol and decimals with no error at all, and `../../info` walked out of
277    /// the collection entirely. Instrument ids are admin-assigned free-form
278    /// strings, so nothing upstream rules that out.
279    fn url(&self, segments: &[&str]) -> Result<reqwest::Url> {
280        let mut url = self.base.clone();
281        url.path_segments_mut()
282            .map_err(|()| Error::InvalidRequest("the registry URL cannot have a path".to_string()))?
283            .pop_if_empty()
284            .extend(segments);
285        Ok(url)
286    }
287
288    /// The registry's own description of itself — including `admin_id`, which
289    /// is the `expectedAdmin` a factory choice names.
290    ///
291    /// # Errors
292    /// As any HTTP call, plus [`Error::UnexpectedResponse`] on a body that does
293    /// not match the standard.
294    pub async fn info(&self) -> Result<RegistryInfo> {
295        self.get(self.url(&["registry", "metadata", "v1", "info"])?)
296            .await
297    }
298
299    /// One page of the instruments this registry issues.
300    ///
301    /// Returns the page and the token for the next one, or `None` at the end.
302    ///
303    /// # Errors
304    /// As [`info`](Self::info).
305    pub async fn list_instruments(
306        &self,
307        page_size: Option<u32>,
308        page_token: Option<&str>,
309    ) -> Result<(Vec<Instrument>, Option<String>)> {
310        let mut url = self.url(&["registry", "metadata", "v1", "instruments"])?;
311        {
312            // Encoded, not formatted: a page token is an instrument id by the
313            // standard's own definition, so one containing `&` would otherwise
314            // split into extra query parameters.
315            let mut query = url.query_pairs_mut();
316            if let Some(size) = page_size {
317                query.append_pair("pageSize", &size.to_string());
318            }
319            if let Some(token) = page_token {
320                query.append_pair("pageToken", token);
321            }
322        }
323        let response: ListInstrumentsResponse = self.get(url).await?;
324        Ok((response.instruments, response.next_page_token))
325    }
326
327    /// One instrument by id, or `None` if this registry does not issue it.
328    ///
329    /// # Errors
330    /// As [`info`](Self::info). A `404` is not an error here — not issuing an
331    /// instrument is an answer — but only when the *registry* is the one
332    /// answering it. A `404` whose body is not JSON did not come from a
333    /// registry handler at all: it is a base URL one path component off, or a
334    /// gateway in front of one, and reporting that as "this registry does not
335    /// issue it" is the worst of both worlds. A wallet polling for an
336    /// instrument would see a steady, quiet `None` while every other call on
337    /// the same client failed loudly.
338    pub async fn instrument(&self, instrument_id: &str) -> Result<Option<Instrument>> {
339        let url = self.url(&["registry", "metadata", "v1", "instruments", instrument_id])?;
340        let response = self
341            .authorized(self.http.get(url.clone()))
342            .await?
343            .send()
344            .await
345            .map_err(connection)?;
346        if response.status() == reqwest::StatusCode::NOT_FOUND {
347            // A failed body read on a 404 is not "the registry does not issue
348            // it": it is a transport failure, and reporting it as `None`
349            // would tell a wallet the instrument does not exist.
350            let body = read_error_body(response, url.as_str(), REGISTRY).await?;
351            let trimmed = body.trim();
352            if trimmed.is_empty() || serde_json::from_str::<serde_json::Value>(trimmed).is_ok() {
353                return Ok(None);
354            }
355            // Not the registry's own 404 — a proxy or a wrong base URL. The
356            // body stays the body; the URL goes to the log, where it is
357            // already, rather than into a field the error model reads as JSON.
358            tracing::warn!(%url, "a 404 that is not the registry's own — check the base URL");
359            return Err(Error::http_at(404, truncate(trimmed), url.as_str()));
360        }
361        Ok(Some(Self::decode(response, url.as_str()).await?))
362    }
363
364    /// Resolve the transfer factory for a transfer, with its choice context.
365    ///
366    /// `choice_arguments` is a serialized `TransferFactory_Transfer` with empty
367    /// `extraArgs` — see [`crate::transfer()`], which builds it.
368    ///
369    /// # Errors
370    /// As [`info`](Self::info).
371    pub async fn transfer_factory(
372        &self,
373        choice_arguments: &serde_json::Value,
374    ) -> Result<FactoryWithContext> {
375        let url = self.url(&["registry", "transfer-instruction", "v1", "transfer-factory"])?;
376        let wire: WireTransferFactory = self.post_factory(url, choice_arguments).await?;
377        Ok(FactoryWithContext {
378            factory_id: wire.factory_id,
379            transfer_kind: Some(wire.transfer_kind),
380            context: ChoiceContext::from_wire(wire.choice_context)?,
381        })
382    }
383
384    /// Resolve the allocation factory, with its choice context.
385    ///
386    /// # Errors
387    /// As [`info`](Self::info).
388    pub async fn allocation_factory(
389        &self,
390        choice_arguments: &serde_json::Value,
391    ) -> Result<FactoryWithContext> {
392        let url = self.url(&[
393            "registry",
394            "allocation-instruction",
395            "v1",
396            "allocation-factory",
397        ])?;
398        let wire: WireFactory = self.post_factory(url, choice_arguments).await?;
399        Ok(FactoryWithContext {
400            factory_id: wire.factory_id,
401            transfer_kind: None,
402            context: ChoiceContext::from_wire(wire.choice_context)?,
403        })
404    }
405
406    // ---- CIP-0112 (V2) ------------------------------------------------------
407    //
408    // Separate methods rather than a version flag on the ones above: the V2
409    // paths are not the V1 paths with a digit changed, and the shapes differ
410    // too. Allocation V2 has no `execute-transfer` context at all — settlement
411    // moved to a factory — and allocation-instruction V2 gained `accept` and
412    // `withdraw`, which V1 has not. A flag would have made those differences
413    // silent.
414
415    /// Resolve the **V2** transfer factory, with its choice context.
416    ///
417    /// `POST /registry/transfer-instruction/v2/transfer-factory`
418    ///
419    /// # Errors
420    /// As [`info`](Self::info).
421    pub async fn transfer_factory_v2(
422        &self,
423        choice_arguments: &serde_json::Value,
424    ) -> Result<FactoryWithContext> {
425        let url = self.url(&["registry", "transfer-instruction", "v2", "transfer-factory"])?;
426        let wire: WireTransferFactory = self.post_factory(url, choice_arguments).await?;
427        Ok(FactoryWithContext {
428            factory_id: wire.factory_id,
429            transfer_kind: Some(wire.transfer_kind),
430            context: ChoiceContext::from_wire(wire.choice_context)?,
431        })
432    }
433
434    /// Resolve the **V2** allocation factory.
435    ///
436    /// `POST /registry/allocation-instruction/v2/allocation-factory`
437    ///
438    /// # Errors
439    /// As [`info`](Self::info).
440    pub async fn allocation_factory_v2(
441        &self,
442        choice_arguments: &serde_json::Value,
443    ) -> Result<FactoryWithContext> {
444        let url = self.url(&[
445            "registry",
446            "allocation-instruction",
447            "v2",
448            "allocation-factory",
449        ])?;
450        let wire: WireFactory = self.post_factory(url, choice_arguments).await?;
451        Ok(FactoryWithContext {
452            factory_id: wire.factory_id,
453            transfer_kind: None,
454            context: ChoiceContext::from_wire(wire.choice_context)?,
455        })
456    }
457
458    /// Resolve the **settlement factory** — how a V2 allocation is settled.
459    ///
460    /// `POST /registry/allocation/v2/settlement-factory`
461    ///
462    /// Note the **singular** `allocation` here against the plural
463    /// `allocations` of the choice-context paths below. That is what the
464    /// specification says, inconsistent as it looks, and a client that
465    /// regularises it gets a 404 from a registry that is working correctly.
466    ///
467    /// V1 has no equivalent: there, an allocation is executed through a choice
468    /// context on the allocation itself. V2 settles a *batch* through this
469    /// factory instead, which is what lets both legs of a delivery-versus-
470    /// payment settle together.
471    ///
472    /// # Errors
473    /// As [`info`](Self::info).
474    pub async fn settlement_factory_v2(
475        &self,
476        choice_arguments: &serde_json::Value,
477    ) -> Result<FactoryWithContext> {
478        let url = self.url(&["registry", "allocation", "v2", "settlement-factory"])?;
479        let wire: WireFactory = self.post_factory(url, choice_arguments).await?;
480        Ok(FactoryWithContext {
481            factory_id: wire.factory_id,
482            transfer_kind: None,
483            context: ChoiceContext::from_wire(wire.choice_context)?,
484        })
485    }
486
487    /// The **V2** context for a choice on an existing transfer instruction.
488    ///
489    /// `POST /registry/transfer-instruction/v2/{id}/choice-contexts/{choice}`
490    ///
491    /// # Errors
492    /// As [`info`](Self::info).
493    pub async fn transfer_instruction_context_v2(
494        &self,
495        transfer_instruction_id: &str,
496        choice: TransferInstructionChoice,
497        request: &ChoiceContextRequest,
498    ) -> Result<ChoiceContext> {
499        self.choice_context(
500            self.url(&[
501                "registry",
502                "transfer-instruction",
503                "v2",
504                transfer_instruction_id,
505                "choice-contexts",
506                choice.path(),
507            ])?,
508            request,
509        )
510        .await
511    }
512
513    /// The **V2** context for a choice on an existing allocation.
514    ///
515    /// `POST /registry/allocations/v2/{id}/choice-contexts/{choice}` — plural,
516    /// unlike the settlement factory above.
517    ///
518    /// # Errors
519    /// As [`info`](Self::info), plus [`Error::InvalidRequest`] for
520    /// [`AllocationChoice::ExecuteTransfer`], which V2 does not have: settling
521    /// goes through [`settlement_factory_v2`](Self::settlement_factory_v2).
522    /// Refusing locally names the reason; the registry would answer 404.
523    pub async fn allocation_context_v2(
524        &self,
525        allocation_id: &str,
526        choice: AllocationChoice,
527        request: &ChoiceContextRequest,
528    ) -> Result<ChoiceContext> {
529        if choice == AllocationChoice::ExecuteTransfer {
530            return Err(Error::InvalidRequest(
531                "V2 allocations are settled through the settlement factory, not an \
532                 execute-transfer context — see `settlement_factory_v2`"
533                    .to_string(),
534            ));
535        }
536        self.choice_context(
537            self.url(&[
538                "registry",
539                "allocations",
540                "v2",
541                allocation_id,
542                "choice-contexts",
543                choice.path(),
544            ])?,
545            request,
546        )
547        .await
548    }
549
550    /// The **V2** context for a choice on an allocation *instruction*.
551    ///
552    /// `POST /registry/allocation-instruction/v2/{id}/choice-contexts/{choice}`
553    ///
554    /// V1 has no such endpoint — an allocation instruction there is driven
555    /// entirely through the factory.
556    ///
557    /// # Errors
558    /// As [`info`](Self::info).
559    pub async fn allocation_instruction_context_v2(
560        &self,
561        allocation_instruction_id: &str,
562        choice: AllocationInstructionChoice,
563        request: &ChoiceContextRequest,
564    ) -> Result<ChoiceContext> {
565        self.choice_context(
566            self.url(&[
567                "registry",
568                "allocation-instruction",
569                "v2",
570                allocation_instruction_id,
571                "choice-contexts",
572                choice.path(),
573            ])?,
574            request,
575        )
576        .await
577    }
578
579    /// The context for a choice on an existing transfer instruction.
580    ///
581    /// # Errors
582    /// As [`info`](Self::info).
583    pub async fn transfer_instruction_context(
584        &self,
585        transfer_instruction_id: &str,
586        choice: TransferInstructionChoice,
587        request: &ChoiceContextRequest,
588    ) -> Result<ChoiceContext> {
589        self.choice_context(
590            self.url(&[
591                "registry",
592                "transfer-instruction",
593                "v1",
594                transfer_instruction_id,
595                "choice-contexts",
596                choice.path(),
597            ])?,
598            request,
599        )
600        .await
601    }
602
603    /// The context for a choice on an existing allocation.
604    ///
605    /// # Errors
606    /// As [`info`](Self::info).
607    pub async fn allocation_context(
608        &self,
609        allocation_id: &str,
610        choice: AllocationChoice,
611        request: &ChoiceContextRequest,
612    ) -> Result<ChoiceContext> {
613        self.choice_context(
614            self.url(&[
615                "registry",
616                "allocations",
617                "v1",
618                allocation_id,
619                "choice-contexts",
620                choice.path(),
621            ])?,
622            request,
623        )
624        .await
625    }
626
627    async fn post_factory<T: serde::de::DeserializeOwned>(
628        &self,
629        url: reqwest::Url,
630        choice_arguments: &serde_json::Value,
631    ) -> Result<T> {
632        let response = self
633            .authorized(self.http.post(url.clone()))
634            .await?
635            .json(&GetFactoryRequest {
636                choice_arguments,
637                // The debug fields are explicitly untrustworthy unless the
638                // provider is trusted, and nothing here reads them, so they are
639                // bytes on the wire for no purpose.
640                exclude_debug_fields: true,
641            })
642            .send()
643            .await
644            .map_err(connection)?;
645        Self::decode(response, url.as_str()).await
646    }
647
648    async fn choice_context(
649        &self,
650        url: reqwest::Url,
651        request: &ChoiceContextRequest,
652    ) -> Result<ChoiceContext> {
653        let response = self
654            .authorized(self.http.post(url.clone()))
655            .await?
656            .json(request)
657            .send()
658            .await
659            .map_err(connection)?;
660        let wire: WireChoiceContext = Self::decode(response, url.as_str()).await?;
661        ChoiceContext::from_wire(wire)
662    }
663
664    async fn get<T: serde::de::DeserializeOwned>(&self, url: reqwest::Url) -> Result<T> {
665        let response = self
666            .authorized(self.http.get(url.clone()))
667            .await?
668            .send()
669            .await
670            .map_err(connection)?;
671        Self::decode(response, url.as_str()).await
672    }
673
674    /// One place where a non-success status becomes an error and a body becomes
675    /// a value, so every call reports failure the same way.
676    async fn decode<T: serde::de::DeserializeOwned>(
677        response: reqwest::Response,
678        url: &str,
679    ) -> Result<T> {
680        let status = response.status();
681        let body = if status.is_success() {
682            read_body(response, MAX_RESPONSE_BYTES, url).await?
683        } else {
684            read_error_body(response, url, REGISTRY).await?
685        };
686        if status == reqwest::StatusCode::CONFLICT {
687            // Every token-standard document defines 409 the same way: a
688            // contract the reply would name is in the middle of a
689            // reassignment between synchronizers. It resolves by itself in
690            // seconds, so this is the one non-2xx that is transient, and the
691            // shared error model's HTTP rule (408, 429, 5xx) would call it
692            // permanent. Reported as a connection-class error, which retries.
693            let message = serde_json::from_str::<ErrorResponse>(&body)
694                .map(|e| e.error)
695                .unwrap_or(body);
696            return Err(Error::Connection(format!(
697                "{url}: the registry reports a contract mid-reassignment (409), retry shortly: {}",
698                truncate(&message)
699            )));
700        }
701        if !status.is_success() {
702            // The standard's error body is `{"error": "…"}`; anything else is
703            // passed through, since a registry that is failing is exactly when
704            // a truncated-to-nothing message helps least. The body is the
705            // body — `canton-core` reads `Error::Http::body` as the response
706            // (for a category, a retry delay, a correlation id), and a URL
707            // prefixed onto it made every one of those reads fail. The URL is
708            // in the log line instead.
709            tracing::warn!(%url, status = status.as_u16(), "the registry answered with an error");
710            let message = serde_json::from_str::<ErrorResponse>(&body)
711                .map(|e| e.error)
712                .unwrap_or(body);
713            return Err(Error::http_at(status.as_u16(), truncate(&message), url));
714        }
715        serde_json::from_str(&body).map_err(|e| {
716            Error::UnexpectedResponse(format!(
717                "{url} returned a body this does not understand: {e}"
718            ))
719        })
720    }
721}
722
723#[derive(Deserialize)]
724pub(crate) struct ErrorResponse {
725    pub(crate) error: String,
726}
727
728/// How the registry is named in an error.
729const REGISTRY: &str = "the registry";
730
731/// Turn a transport failure into an error a caller can act on.
732///
733/// Two things this must get right, and the first version got neither.
734///
735/// **The message.** A `reqwest::Error` prints only its outer sentence —
736/// `error sending request for url (…)` — and keeps what actually went wrong in
737/// its source chain. Reporting only the outer message hides the one line that
738/// says *certificate*, or *dns*, or *connection refused*.
739///
740/// **The verdict.** [`Error::Connection`] is unconditionally retriable, so
741/// mapping everything to it makes an application that loops on `is_retriable()`
742/// retry forever on a condition no amount of waiting fixes — a certificate it
743/// The most a registry answer may be. A choice context carries the disclosed
744/// contracts' `createdEventBlob`s, so it is kilobytes to a few megabytes;
745/// nothing the standard defines is larger, and a registry (or whatever answers
746/// in its place) does not get to size the client's memory.
747pub(crate) const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024;
748/// How much of an error body is kept for the message.
749pub(crate) const ERROR_BODY_CAP: usize = 64 * 1024;
750
751/// Read a response body, refusing one that declares or grows past `cap`.
752/// `reqwest`'s `text()` reads to the end whatever the size; this reads chunk
753/// by chunk, so the bound holds for a chunked stream without `Content-Length`.
754async fn read_body(response: reqwest::Response, cap: usize, url: &str) -> Result<String> {
755    read_body_from(response, cap, url, REGISTRY).await
756}
757
758/// The body of a reply that is already an error, up to [`ERROR_BODY_CAP`].
759///
760/// Cut off at the cap rather than refused for exceeding it: the status is
761/// what the caller acts on (a 503 is retried, a 404 may be an answer), and a
762/// gateway's long error page must not turn it into a complaint about size.
763pub(crate) async fn read_error_body(
764    mut response: reqwest::Response,
765    url: &str,
766    who: &str,
767) -> Result<String> {
768    let mut buffer: Vec<u8> = Vec::new();
769    while buffer.len() < ERROR_BODY_CAP {
770        let Some(chunk) = response
771            .chunk()
772            .await
773            .map_err(|e| transport_error(e, who))?
774        else {
775            break;
776        };
777        let room = ERROR_BODY_CAP.saturating_sub(buffer.len());
778        buffer.extend_from_slice(chunk.get(..room).unwrap_or(&chunk));
779    }
780    tracing::trace!(%url, bytes = buffer.len(), "read an error body");
781    Ok(String::from_utf8_lossy(&buffer).into_owned())
782}
783
784/// [`read_body`] for any service this crate talks to; `who` names it in the
785/// errors ("the registry", "Scan").
786pub(crate) async fn read_body_from(
787    mut response: reqwest::Response,
788    cap: usize,
789    url: &str,
790    who: &str,
791) -> Result<String> {
792    if let Some(declared) = response
793        .content_length()
794        .filter(|declared| usize::try_from(*declared).map_or(true, |n| n > cap))
795    {
796        {
797            return Err(Error::UnexpectedResponse(format!(
798                "{url}: {who} answered with a {declared}-byte body, above the {cap}-byte limit"
799            )));
800        }
801    }
802    let mut buffer: Vec<u8> = Vec::new();
803    while let Some(chunk) = response
804        .chunk()
805        .await
806        .map_err(|e| transport_error(e, who))?
807    {
808        if buffer.len() + chunk.len() > cap {
809            return Err(Error::UnexpectedResponse(format!(
810                "{url}: {who} answered with a body above the {cap}-byte limit"
811            )));
812        }
813        buffer.extend_from_slice(&chunk);
814    }
815    String::from_utf8(buffer).map_err(|e| {
816        Error::UnexpectedResponse(format!(
817            "{url}: {who} answered with a body that is not UTF-8: {e}"
818        ))
819    })
820}
821
822/// cannot verify, a URL it cannot build, a redirect loop. Those are reported as
823/// [`Error::InvalidRequest`], which is not retriable.
824fn connection(e: reqwest::Error) -> Error {
825    transport_error(e, REGISTRY)
826}
827
828/// [`connection`] for any service this crate talks to; `who` names it in the
829/// error ("the registry", "Scan").
830pub(crate) fn transport_error(e: reqwest::Error, who: &str) -> Error {
831    let kind = if e.is_timeout() {
832        Transport::Timeout
833    } else if e.is_builder() {
834        Transport::Builder
835    } else if e.is_redirect() {
836        Transport::Redirect
837    } else if e.is_decode() {
838        Transport::Decode
839    } else {
840        Transport::Connect
841    };
842    // The URL goes into the message, redacted, and not into the text the
843    // verdict is read off: a host or path with "certificate" in it would
844    // otherwise decide it.
845    let at = e
846        .url()
847        .map(|url| canton_core::redact_url(url.as_str()).into_owned());
848    classify_transport(
849        kind,
850        &canton_core::chain(&e.without_url()),
851        who,
852        at.as_deref(),
853    )
854}
855
856/// What `reqwest` says about a failure, by type, in the order the verdict
857/// reads them. Separated from the error so the verdict below can be tested on
858/// the strings it reads, which are the only place a TLS failure shows.
859#[derive(Clone, Copy, Debug, PartialEq, Eq)]
860enum Transport {
861    Timeout,
862    Builder,
863    Redirect,
864    Decode,
865    /// Everything else: the connection itself failed, and the chain says how.
866    Connect,
867}
868
869/// The verdict on a transport failure, read off `detail`, which carries no
870/// URL. `at` is the request's URL, redacted, for the message only.
871fn classify_transport(kind: Transport, detail: &str, who: &str, at: Option<&str>) -> Error {
872    let at = at.map(|url| format!(" ({url})")).unwrap_or_default();
873    match kind {
874        // The 30s default this client sets. Retriable, and `Error::Timeout`
875        // says why without the caller reading the message.
876        Transport::Timeout => return Error::Timeout,
877        Transport::Builder | Transport::Redirect => {
878            return Error::InvalidRequest(format!("{who} request could not be made{at}: {detail}"));
879        }
880        Transport::Decode => {
881            return Error::UnexpectedResponse(format!(
882                "{who}'s reply could not be read{at}: {detail}"
883            ));
884        }
885        Transport::Connect => {}
886    }
887    // A TLS failure arrives as a connect error, indistinguishable by type from
888    // a refused connection — reqwest exposes no typed TLS error — so the chain
889    // is the only place the difference shows. Worth the string match: a
890    // certificate the client cannot verify is permanent, and retrying it
891    // forever is the failure this whole function exists to avoid.
892    let lower = detail.to_ascii_lowercase();
893    if lower.contains("certificate") {
894        return Error::InvalidRequest(format!(
895            "{who}'s TLS certificate could not be verified{at}: {detail}"
896        ));
897    }
898    Error::Connection(format!("cannot reach {who}{at}: {detail}"))
899}
900
901/// The choices a transfer instruction offers, as the registry paths name them.
902#[derive(Clone, Copy, Debug, Eq, PartialEq)]
903#[non_exhaustive]
904pub enum TransferInstructionChoice {
905    /// The receiver accepts an offered transfer.
906    Accept,
907    /// The receiver rejects it.
908    Reject,
909    /// The sender withdraws it.
910    Withdraw,
911}
912
913impl TransferInstructionChoice {
914    fn path(self) -> &'static str {
915        match self {
916            Self::Accept => "accept",
917            Self::Reject => "reject",
918            Self::Withdraw => "withdraw",
919        }
920    }
921}
922
923/// The choices a V2 allocation *instruction* offers.
924///
925/// V1 has no equivalent: an allocation instruction there is driven through the
926/// factory and has no choice contexts of its own.
927#[derive(Clone, Copy, Debug, Eq, PartialEq)]
928#[non_exhaustive]
929pub enum AllocationInstructionChoice {
930    /// The registry accepts a pending instruction.
931    Accept,
932    /// The sender withdraws it.
933    Withdraw,
934}
935
936impl AllocationInstructionChoice {
937    fn path(self) -> &'static str {
938        match self {
939            Self::Accept => "accept",
940            Self::Withdraw => "withdraw",
941        }
942    }
943}
944
945/// The choices an allocation offers.
946#[derive(Clone, Copy, Debug, Eq, PartialEq)]
947#[non_exhaustive]
948pub enum AllocationChoice {
949    /// The executor settles the allocated transfer.
950    ExecuteTransfer,
951    /// The sender withdraws the allocation.
952    Withdraw,
953    /// The executor cancels it.
954    Cancel,
955}
956
957impl AllocationChoice {
958    fn path(self) -> &'static str {
959        match self {
960            Self::ExecuteTransfer => "execute-transfer",
961            Self::Withdraw => "withdraw",
962            Self::Cancel => "cancel",
963        }
964    }
965}
966
967/// A body excerpt short enough for an error message. An HTML error page is
968/// otherwise long enough to bury the sentence that names the problem.
969pub(crate) fn truncate(body: &str) -> String {
970    const LIMIT: usize = 200;
971    if body.len() <= LIMIT {
972        return body.to_string();
973    }
974    let cut = body
975        .char_indices()
976        .map(|(i, _)| i)
977        .take_while(|i| *i <= LIMIT)
978        .last()
979        .unwrap_or(0);
980    format!("{}…", body.get(..cut).unwrap_or(body))
981}
982
983#[cfg(test)]
984#[allow(clippy::unwrap_used, clippy::expect_used)]
985mod tests {
986    use super::*;
987
988    /// The paths are the standard's, spelled as its `operationId`s imply. A
989    /// wrong one is a 404 from a registry that is working perfectly.
990    #[test]
991    fn the_choice_paths_are_the_ones_the_standard_publishes() {
992        assert_eq!(TransferInstructionChoice::Accept.path(), "accept");
993        assert_eq!(TransferInstructionChoice::Reject.path(), "reject");
994        assert_eq!(TransferInstructionChoice::Withdraw.path(), "withdraw");
995        assert_eq!(AllocationChoice::ExecuteTransfer.path(), "execute-transfer");
996        assert_eq!(AllocationChoice::Withdraw.path(), "withdraw");
997        assert_eq!(AllocationChoice::Cancel.path(), "cancel");
998    }
999
1000    /// `self` is a Rust keyword and the wire spells it exactly that, so the
1001    /// rename is load-bearing: without it the variant would never match.
1002    #[test]
1003    fn the_transfer_kinds_decode_from_the_words_the_wire_uses() {
1004        let kinds: Vec<TransferKind> =
1005            serde_json::from_str(r#"["self", "direct", "offer"]"#).expect("decodes");
1006        assert_eq!(
1007            kinds,
1008            [
1009                TransferKind::SelfTransfer,
1010                TransferKind::Direct,
1011                TransferKind::Offer
1012            ]
1013        );
1014    }
1015
1016    /// A trailing slash on the base URL would otherwise produce `//registry/…`,
1017    /// which some servers route and others do not.
1018    #[test]
1019    fn a_trailing_slash_on_the_base_url_does_not_double_up() {
1020        let client = RegistryClient::new("https://scan.example.com/").unwrap();
1021        assert_eq!(
1022            client
1023                .url(&["registry", "metadata", "v1", "info"])
1024                .unwrap()
1025                .as_str(),
1026            "https://scan.example.com/registry/metadata/v1/info"
1027        );
1028    }
1029
1030    /// A path segment from outside must not be able to change which resource is
1031    /// addressed. Formatted into a string, an instrument id of `a?b` fetched
1032    /// instrument `a` and returned its name, symbol and decimals with no error
1033    /// — and `../../info` walked out of the collection entirely.
1034    #[test]
1035    fn a_hostile_path_segment_cannot_redirect_the_request() {
1036        let client = RegistryClient::new("https://scan.example.com").unwrap();
1037        for hostile in ["a?b", "a#b", "../../info", "a/b"] {
1038            let url = client
1039                .url(&["registry", "metadata", "v1", "instruments", hostile])
1040                .unwrap();
1041            assert_eq!(
1042                url.query(),
1043                None,
1044                "`{hostile}` must not become a query: {url}"
1045            );
1046            assert_eq!(
1047                url.path_segments().map(Iterator::count),
1048                Some(5),
1049                "`{hostile}` must stay one segment: {url}"
1050            );
1051            assert!(
1052                url.as_str()
1053                    .starts_with("https://scan.example.com/registry/metadata/v1/instruments/"),
1054                "`{hostile}` escaped the collection: {url}"
1055            );
1056        }
1057    }
1058
1059    /// A base URL that is not a URL is a configuration mistake, and it has to
1060    /// arrive as one. Left to surface from the first request it became
1061    /// `Error::Connection`, which the SDK reports as retriable — so an
1062    /// application would retry a typo forever.
1063    #[test]
1064    fn a_base_url_that_is_not_a_url_is_refused_immediately() {
1065        let err = RegistryClient::new("not a url").expect_err("not a URL");
1066        assert!(!err.is_retriable(), "a typo is not worth retrying: {err}");
1067        assert!(err.to_string().contains("not a url"), "{err}");
1068    }
1069
1070    #[test]
1071    fn the_factory_request_is_the_shape_the_standard_specifies() {
1072        let args = serde_json::json!({ "expectedAdmin": "dso::1220", "transfer": {} });
1073        let request = GetFactoryRequest {
1074            choice_arguments: &args,
1075            exclude_debug_fields: true,
1076        };
1077        assert_eq!(
1078            serde_json::to_value(&request).unwrap(),
1079            serde_json::json!({
1080                "choiceArguments": { "expectedAdmin": "dso::1220", "transfer": {} },
1081                "excludeDebugFields": true
1082            })
1083        );
1084    }
1085
1086    /// The response is read by the field names the standard uses, and the
1087    /// factory's context is translated on the way through.
1088    #[test]
1089    fn a_factory_response_decodes_and_its_context_is_translated() {
1090        let json = serde_json::json!({
1091            "factoryId": "00factory",
1092            "transferKind": "direct",
1093            "choiceContext": {
1094                "choiceContextData": { "values": {} },
1095                "disclosedContracts": [{
1096                    "templateId": "pkg:Splice.AmuletRules:AmuletRules",
1097                    "contractId": "001",
1098                    "createdEventBlob": "AQI=",
1099                    "synchronizerId": "sync::1220ab"
1100                }]
1101            }
1102        });
1103        let wire: WireTransferFactory = serde_json::from_value(json).expect("decodes");
1104        assert_eq!(wire.factory_id, "00factory");
1105        assert_eq!(wire.transfer_kind, TransferKind::Direct);
1106
1107        let context = ChoiceContext::from_wire(wire.choice_context).expect("translates");
1108        assert_eq!(context.disclosed_contracts().len(), 1);
1109        assert_eq!(context.disclosed_contracts()[0].created_event_blob, [1, 2]);
1110    }
1111
1112    /// The allocation factory's response has no `transferKind` at all, and it
1113    /// is a different type for that reason: "this API does not classify the
1114    /// workflow" and "a registry omitted a field its spec requires" must not
1115    /// arrive as the same value.
1116    #[test]
1117    fn the_allocation_factory_response_has_no_transfer_kind() {
1118        let json = serde_json::json!({
1119            "factoryId": "00factory",
1120            "choiceContext": { "choiceContextData": {}, "disclosedContracts": [] }
1121        });
1122        let wire: WireFactory = serde_json::from_value(json).expect("decodes");
1123        assert_eq!(wire.factory_id, "00factory");
1124
1125        // And the transfer factory refuses the same body, because its spec
1126        // marks the field required.
1127        let json = serde_json::json!({
1128            "factoryId": "00factory",
1129            "choiceContext": { "choiceContextData": {}, "disclosedContracts": [] }
1130        });
1131        assert!(serde_json::from_value::<WireTransferFactory>(json).is_err());
1132    }
1133
1134    /// A registry that adds a fourth kind must not break the transfers whose
1135    /// kind this build understands perfectly well.
1136    #[test]
1137    fn an_unknown_transfer_kind_decodes_instead_of_failing_the_response() {
1138        let json = serde_json::json!({
1139            "factoryId": "00factory",
1140            "transferKind": "escrow-something-new",
1141            "choiceContext": { "choiceContextData": {}, "disclosedContracts": [] }
1142        });
1143        let wire: WireTransferFactory =
1144            serde_json::from_value(json).expect("an unknown kind is a value, not a decode failure");
1145        assert_eq!(wire.transfer_kind, TransferKind::Unknown);
1146    }
1147
1148    /// The standard marks `decimals` required with a default of ten, so an
1149    /// absent field means ten places — not "unknown". It is what a wallet
1150    /// formats an amount with.
1151    #[test]
1152    fn an_absent_decimals_is_the_standards_default_and_not_unknown() {
1153        let instrument: Instrument = serde_json::from_value(serde_json::json!({
1154            "id": "Amulet", "name": "Canton Coin", "symbol": "CC"
1155        }))
1156        .expect("decodes");
1157        assert_eq!(instrument.decimals, 10);
1158    }
1159
1160    #[test]
1161    fn instruments_decode_with_the_optional_fields_absent() {
1162        let json = serde_json::json!({
1163            "instruments": [{ "id": "Amulet", "name": "Canton Coin", "symbol": "CC" }]
1164        });
1165        let response: ListInstrumentsResponse = serde_json::from_value(json).expect("decodes");
1166        assert_eq!(response.instruments.len(), 1);
1167        assert_eq!(response.instruments[0].id, "Amulet");
1168        assert_eq!(response.instruments[0].total_supply, None);
1169        assert_eq!(response.instruments[0].decimals, 10);
1170        assert_eq!(response.next_page_token, None);
1171    }
1172
1173    /// The transport verdict, on the strings it has to read. A certificate
1174    /// failure is permanent, however the chain capitalizes it; a refused
1175    /// connection is not, and neither is a handshake the peer hung up on,
1176    /// which is what a restart looks like from here.
1177    #[test]
1178    fn a_certificate_failure_is_permanent_and_a_dropped_handshake_is_not() {
1179        let hung_up = classify_transport(
1180            Transport::Connect,
1181            "client error (Connect): tls handshake eof",
1182            REGISTRY,
1183            None,
1184        );
1185        assert!(matches!(hung_up, Error::Connection(_)), "{hung_up:?}");
1186        assert!(hung_up.is_retriable(), "{hung_up}");
1187
1188        for detail in [
1189            "error sending request: invalid peer certificate: UnknownIssuer",
1190            "CERTIFICATE verify failed",
1191        ] {
1192            let error = classify_transport(Transport::Connect, detail, REGISTRY, None);
1193            assert!(
1194                matches!(error, Error::InvalidRequest(_)),
1195                "{detail}: {error:?}"
1196            );
1197            assert!(!error.is_retriable(), "{detail}");
1198            assert!(error.to_string().contains("TLS certificate"), "{error}");
1199        }
1200        let refused = classify_transport(
1201            Transport::Connect,
1202            "connection refused (os error 61)",
1203            REGISTRY,
1204            None,
1205        );
1206        assert!(matches!(refused, Error::Connection(_)), "{refused:?}");
1207        assert!(refused.is_retriable());
1208        assert!(
1209            refused.to_string().contains("connection refused"),
1210            "{refused}"
1211        );
1212    }
1213
1214    /// Each typed verdict on its own: a timeout is `Timeout`, an unbuildable
1215    /// request or a redirect loop is permanent, a body that does not read is
1216    /// an unexpected response.
1217    #[test]
1218    fn the_typed_verdicts_are_read_before_the_strings() {
1219        let timeout = classify_transport(
1220            Transport::Timeout,
1221            "certificate", // would otherwise be read as permanent
1222            REGISTRY,
1223            None,
1224        );
1225        assert!(matches!(timeout, Error::Timeout), "{timeout:?}");
1226
1227        for kind in [Transport::Builder, Transport::Redirect] {
1228            let error = classify_transport(kind, "x", REGISTRY, None);
1229            assert!(
1230                matches!(&error, Error::InvalidRequest(m) if m.contains("could not be made")),
1231                "{kind:?}: {error:?}"
1232            );
1233        }
1234
1235        let decode = classify_transport(Transport::Decode, "x", REGISTRY, None);
1236        assert!(matches!(decode, Error::UnexpectedResponse(_)), "{decode:?}");
1237    }
1238
1239    /// A real failed request: reqwest prints the URL into its own message,
1240    /// and "certificate" there is not a certificate failure. The URL is in
1241    /// the message, redacted, for the reader.
1242    #[tokio::test]
1243    async fn a_refused_connection_is_retriable_whatever_the_url_spells() {
1244        let failed = reqwest::Client::new()
1245            .get("http://user:secret@127.0.0.1:1/certificate-service/registry/metadata/v1/info")
1246            .send()
1247            .await
1248            .expect_err("nothing listens there");
1249        let error = transport_error(failed, REGISTRY);
1250        assert!(matches!(error, Error::Connection(_)), "{error:?}");
1251        assert!(error.is_retriable(), "{error}");
1252        let message = error.to_string();
1253        assert!(
1254            message.contains("127.0.0.1:1/certificate-service"),
1255            "{message}"
1256        );
1257        assert!(!message.contains("secret"), "{message}");
1258    }
1259
1260    /// The excerpt boundary: exactly the limit is left alone, one byte over is
1261    /// cut and marked, and the cut never splits a character.
1262    #[test]
1263    fn truncate_cuts_past_the_limit_and_on_a_character_boundary() {
1264        let exact = "x".repeat(200);
1265        assert_eq!(truncate(&exact), exact);
1266
1267        let over = "x".repeat(201);
1268        let cut = truncate(&over);
1269        assert!(cut.ends_with('…'), "{cut}");
1270        assert_eq!(cut.trim_end_matches('…').len(), 200);
1271
1272        // 199 ASCII bytes, then a three-byte character straddling the limit.
1273        let straddle = format!("{}€€", "x".repeat(199));
1274        let cut = truncate(&straddle);
1275        assert!(cut.ends_with('…'), "{cut}");
1276        assert!(cut.starts_with(&"x".repeat(199)), "{cut}");
1277    }
1278}