uftp 0.2.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
Documentation
//! A whole trade between a DSO and an aggregator, in one process: request, offer, order
//! and settlement, each answered with its response. Every document goes through the
//! receive path a real endpoint uses: header check, then `Endpoint::receive` (open, market,
//! time, outbox, replay), then the reference check.
//! Run with `cargo run --example loopback`.

use uftp::jiff::{SignedDuration, Timestamp};
use uftp::transport::{self, Delivery};
use uftp::*;

/// One side of the trade: who it is, its key, and its receiving endpoint.
struct Party {
    role: Role,
    key: SigningKey,
    domain: InternetDomain,
    endpoint: Endpoint,
}

impl Party {
    fn new(domain: &str, role: Role, seed: u8) -> Result<Self, Rejection> {
        let domain: InternetDomain = domain.parse()?;
        let market = Market {
            isp_duration: IspDuration::PT15M,
            time_zone: "Europe/Amsterdam".parse()?,
        };
        let options = OpenOptions::for_recipient(domain.clone());
        Ok(Self {
            role,
            key: SigningKey::from_seed(&[seed; 32]),
            domain,
            endpoint: Endpoint::new(options, SignedDuration::from_mins(15))
                .with_market(market)
                .with_outbox(Outbox::new(SignedDuration::from_hours(24))),
        })
    }

    fn domain(&self) -> InternetDomain {
        self.domain.clone()
    }

    fn participant(&self) -> Participant {
        Participant::new(self.domain(), self.role, self.key.public_keys([0; 32]))
    }

    /// Seals a message and records it, so its response can be matched (and a response to
    /// anything this party did not send is refused).
    fn send(&mut self, message: impl Into<Message>, now: Timestamp) -> Result<String, Rejection> {
        let message = message.into();
        self.endpoint.sent(&message, now);
        Ok(seal(&message, self.role, &self.key)?.to_xml())
    }

    /// What an HTTP handler does with a POSTed body: check headers, then receive. It
    /// answers with an HTTP status and, for a valid message, the opened message.
    fn receive(&mut self, body: &str, now: Timestamp, dir: &Directory) -> (u16, Option<Opened>) {
        let len = u64::try_from(body.len()).ok();
        let limits = self.endpoint.options().limits;
        let result = transport::check_request(Some(transport::CONTENT_TYPE), len, &limits)
            .and_then(|()| self.endpoint.receive(body.as_bytes(), now, dir.lookup()));
        match result {
            Ok(opened) => (200, Some(opened)),
            Err(e) => {
                println!("    refused: {e}");
                (e.http_status(), None)
            }
        }
    }
}

#[allow(clippy::too_many_lines)] // one trade, read top to bottom
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut dso = Party::new("dso.example", Role::Dso, 1)?;
    let mut agr = Party::new("agr.example", Role::Agr, 2)?;
    let dir = Directory::new()
        .with(dso.participant())
        .with(agr.participant());
    let mut ids = (1u8..).map(|n| MessageUuid::from_bytes([n; 16]));
    let mut id = move || ids.next().expect("enough ids");
    let now: Timestamp = "2026-11-30T12:00:00Z".parse()?;

    // 1. DSO → AGR: 500 kW less from 17:00 to 19:00 tomorrow (ISPs 69–76).
    let meta = Metadata::new(dso.domain(), agr.domain(), now, id());
    let zone = "Europe/Amsterdam".parse()?;
    let point = "ean.871685900012636543".parse()?;
    let header = FlexHeader::new(meta, zone, "2026-12-01".parse()?, point);
    let isps = vec![FlexRequestIsp::requested(IspSpan::new(69, 8)?, -500_000, 0)];
    let request = FlexRequest::new(header, "2026-11-30T18:00:00Z".parse()?, isps);
    let (status, Some(opened)) = agr.receive(&dso.send(request, now)?, now, &dir) else {
        return Err("the request was refused".into());
    };
    println!(
        "1. AGR got {} (HTTP {status})",
        opened.message().type_name()
    );
    let request: FlexRequest = opened.message().clone().try_into()?;
    let answer = opened
        .reply(Reply::accepted(id(), now))
        .expect("a request is answered");
    dso.receive(&agr.send(answer, now)?, now, &dir);

    // 2. AGR → DSO: two mutually exclusive options, each also orderable at half.
    let option = |reference: &str, power: i64, price: &str| -> Result<OfferOption, Rejection> {
        let isps = vec![PowerIsp {
            span: IspSpan::new(69, 8)?,
            power,
        }];
        let mut option = OfferOption::new(reference, price.parse()?, isps);
        option.min_activation_factor = "0.5".parse()?;
        Ok(option)
    };
    let offer = request.offer(
        id(),
        now,
        "2026-11-30T16:00:00Z".parse()?,
        Currency::EUR,
        // Two fraction digits for EUR: Shapeshifter receivers refuse other scales (SH-02).
        vec![
            option("A", -500_000, "180.00")?,
            option("B", -300_000, "95.00")?,
        ],
    );
    let (_, Some(opened)) = dso.receive(&agr.send(offer, now)?, now, &dir) else {
        return Err("the offer was refused".into());
    };
    let offer: FlexOffer = opened.message().clone().try_into()?;
    offer
        .check_against(&request)
        .map_err(|e| opened.reject(e))?;
    println!("2. DSO got an offer with {} options", offer.options.len());
    agr.receive(
        &dso.send(offer.reply(Reply::accepted(id(), now)), now)?,
        now,
        &dir,
    );

    // 3. DSO → AGR: option B, fully. The AGR checks it against its own offer.
    let order = offer.order(
        Some("B"),
        ActivationFactor::FULL,
        id(),
        now,
        "ORD-2026-0001",
    )?;
    let (_, Some(opened)) = agr.receive(&dso.send(order.clone(), now)?, now, &dir) else {
        return Err("the order was refused".into());
    };
    let received: FlexOrder = opened.message().clone().try_into()?;
    received.check_against(&offer)?;
    println!(
        "3. AGR accepts order {} for {}",
        received.order_reference, received.price
    );
    dso.receive(
        &agr.send(received.reply(Reply::accepted(id(), now)), now)?,
        now,
        &dir,
    );

    // The same order delivered twice is recognised, not executed twice.
    let (status, _) = agr.receive(&dso.send(order.clone(), now)?, now, &dir);
    println!(
        "   a second delivery of the order: HTTP {status} ({:?})",
        Delivery::of(status)
    );

    // 4. DSO → AGR: the month's settlement. The DSO measured 280 kW of the 300 kW.
    let mut settlement = FlexSettlement::new(
        Metadata::new(dso.domain(), agr.domain(), now, id()),
        "2026-12-01".parse()?,
        "2026-12-31".parse()?,
        Currency::EUR,
        vec![order.settlement(vec![SettlementIsp {
            span: IspSpan::new(69, 8)?,
            baseline_power: 400_000,
            ordered_flex_power: -300_000,
            actual_power: 120_000,
            delivered_flex_power: -280_000,
            power_deficiency: -20_000,
        }])],
    );
    settlement.contract_settlements = vec![reservation(&order)?]; // the 3.1.0 XSD insists (SS-02)

    // The AGR checks every item against the orders it accepted, then answers.
    let (_, Some(opened)) = agr.receive(&dso.send(settlement, now)?, now, &dir) else {
        return Err("the settlement was refused".into());
    };
    let settlement: FlexSettlement = opened.message().clone().try_into()?;
    let answer: Message = match settlement.check_against([&received]) {
        Ok(statuses) => settlement
            .reply(Reply::accepted(id(), now), statuses)
            .into(),
        Err(missing) => opened
            .reject(missing)
            .response(id(), now)
            .expect("a rule answer"),
    };
    let (status, Some(opened)) = dso.receive(&agr.send(answer, now)?, now, &dir) else {
        return Err("the settlement response was refused".into());
    };
    let r: FlexSettlementResponse = opened.into_message().try_into()?;
    println!(
        "4. DSO: settlement {} (HTTP {status}), order {} {:?}",
        r.header().result(),
        received.order_reference,
        r.statuses[0].disposition
    );
    Ok(())
}

/// The reservation contract the order was placed under, settled for the same day.
fn reservation(order: &FlexOrder) -> Result<ContractSettlement, Rejection> {
    Ok(ContractSettlement {
        contract_id: Some("C-7".into()),
        periods: vec![ContractSettlementPeriod {
            period: order.header.period,
            isps: vec![ContractSettlementIsp {
                span: IspSpan::new(69, 8)?,
                reserved_power: -300_000,
                requested_power: Some(-300_000),
                available_power: None,
                offered_power: Some(-300_000),
                ordered_power: Some(-300_000),
            }],
        }],
    })
}