Skip to main content

Crate uftp

Crate uftp 

Source
Expand description

§uftp

UFTP 3.1, the USEF Flex Trading Protocol, in Rust. Distribution system operators (DSO), aggregators (AGR) and the Common Reference Operator (CRO) use it to trade grid flexibility. Since version 3 it is maintained by LF Energy as Shapeshifter. Not the UDP multicast file-transfer tool of the same name.

The crate covers the 26 messages, their XML, their CS1 (Ed25519) signatures, the ISP arithmetic, and the rules a receiver applies. It is sans I/O: it reads no clock, random source, file or network. Ids, timestamps, keys and the key lookup come from you.

The documentation site explains the protocol and each part of the crate, and defines the specification notes (SS-…) cited in these docs.

use uftp::jiff::{SignedDuration, Timestamp};
use uftp::*;

let dso_key = SigningKey::from_seed(&[1; 32]);
let directory = Directory::new()
    .with(Participant::new("dso.example".parse()?, Role::Dso, dso_key.public_keys([0; 32])));
let id = |n: u8| MessageUuid::from_bytes([n; 16]);
let now: Timestamp = "2026-11-30T12:00:00Z".parse()?;

// A DSO asks for 500 kW less consumption from 17:00 to 19:00 local time (ISPs 69–76).
// A conversation starts with its first message; ISPs are PT15M unless set otherwise.
let meta = Metadata::new("dso.example".parse()?, "agr.example".parse()?, now, id(1));
let header = FlexHeader::new(
    meta,
    "Europe/Amsterdam".parse()?,
    "2026-12-01".parse()?,
    "ean.871685900012636543".parse()?,
);
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 document = seal(&request.clone().into(), Role::Dso, &dso_key)?.to_xml();

// The aggregator receives it: every check, in the order the protocol needs.
let mut endpoint = Endpoint::new(
    OpenOptions::for_recipient("agr.example".parse()?),
    SignedDuration::from_mins(15),
);
let opened = endpoint.receive(document.as_bytes(), now, directory.lookup())?;
let received: FlexRequest = opened.into_message().try_into()?;
assert_eq!(received, request);

// It answers in the same conversation.
let response = received.reply(Reply::accepted(id(2), now));
assert_eq!(response.header().meta().conversation_id, id(1));

§Receiving

Endpoint::receive runs, in this order:

  1. open: a strict signature check over exactly the received bytes, then the schema, the sender binding, the sender’s role, the type’s rules and the recipient;
  2. the Market’s ISP duration and time zone, if set;
  3. Message::check_time;
  4. the Outbox, if set: a response must answer a request this endpoint sent;
  5. the ReplayGuard, last, so it remembers only messages it accepted.

Each step is public on its own. With the http feature, Endpoint::receive_request checks the headers before the body, and uftp::http::response writes the answer.

§Two ways to say no

UFTP 3.1 (Appendix 4 §4) answers a refusal in one of two ways, and a Rejection knows which:

WhenRejection::http_statusThen
not UFTP XML, too large, a bad header400 (411 without a length)nothing else
the signature does not verify401nothing else
the sender’s key cannot be looked up419, retrynothing else
the sender is over its quota429, Rejection::retry_afternothing else
valid, verified, but it breaks a rule200seal and send Rejection::response

The Rejected response goes to the sender whose signature verified, never to a domain the message merely names. Its RejectionReason is one of the specification’s 38; RejectionReason::source cites where each is defined. Reasons that depend on your state, such as a revoked offer, are yours to raise with Rejection::because.

A refusal’s text is one line you can log and send back: received values are escaped and cut after 64 characters or 128 escaped bytes, and no refusal is longer than 512 bytes.

§Sending

seal refuses a message that breaks a rule, so what you send is valid. Build messages with the constructors (FlexHeader::new, FlexRequest::new, FlexOffer::unsolicited, FlexOrder::unsolicited) and the flow helpers (FlexRequest::offer, FlexOffer::order, FlexOffer::revoke). transport has the content type, the paths and transport::Delivery for the status you get back.

§Settling

Each month the DSO settles its orders. FlexOrder::settlement turns an order into an item at its price × ActivationFactor (SS-26), and FlexSettlement::new wraps the items. The aggregator calls FlexSettlement::check_against with the orders it accepted. It gets back one Accepted or Disputed status per item, or Missing Settlement Items if an order of the period is not settled [UFTP §3.10.1]. The figures the DSO computes (delivered power, deficiency, penalty) are transported, not computed; SettlementIsp says how their signs are read.

§Power

Every power is an i64 in watts, positive for consumption [UFTP §4.2.1]: a request for 500 kW less is -500_000. The XSD’s xs:integer is unbounded; a power outside the i64 range is refused when parsed, never clamped.

§Features

cs1 (default) adds keys, seal and open, the Directory, Endpoint, Outbox and ReplayGuard. Without it the crate is the messages, their rules and XML, the ISP grid and the flow and settle helpers. http adds uftp::http and turns on cs1.

§Keys

Directory holds participants for configured deployments, with two keys during a rollover. dns builds the record names of Appendix 4 and parses their keys. Query them with a DNSSEC-validating resolver of your choice.

Re-exports§

pub use msg::DecodeOptions;
pub use msg::FlexHeader;
pub use msg::Message;
pub use msg::Metadata;
pub use msg::Reply;
pub use msg::ResponseHeader;
pub use msg::UnexpectedMessage;
pub use jiff;
pub use rust_decimal;
pub use msg::agr_cro::*;
pub use msg::agr_dso::*;
pub use msg::common::*;
pub use msg::cro_dso::*;
pub use msg::metering::*;

Modules§

dnscs1
The DNS names of [UFTP App. 4 §2] and the parsing of their values. The library resolves nothing: query these names with a DNSSEC-validating resolver and pass the answers here.
httphttp
[UFTP App. 4 §3, §4] on the http crate’s types (feature http).
msg
The UFTP 3.1.0 messages: all 26 types of the common, AGR–DSO, AGR–CRO, CRO–DSO and metering schemas.
transport
The HTTP mapping of [UFTP App. 4 §3, §4], without an HTTP dependency: constants, a check of a received request before its body is read, and the classification of a status received after sending.

Structs§

ActivationFactor
The share of an offer option that is activated, 0.01 to 1.00 with at most two fraction digits [XSD ActivationFactorType]. The order copies the option’s power and price; the factor scales both once, at settlement (SS-26).
Amount
A money amount with at most four fraction digits [XSD CurrencyAmountType]. Too many digits are refused, never rounded.
Currency
An ISO 4217 currency code, three upper-case letters [XSD ISO4217CurrencyType].
DayGrid
The ISPs of one day (a Period) in one time zone.
Directorycs1
A static set of participants, for configured deployments and tests. Use it as the key lookup of open: directory.lookup().
Ean
The connection a Metering message is about [XSD EANType]: E (or e) followed by 18 digits. Unlike an EntityAddress it has no ean. prefix. The case is kept as received.
Endpointcs1
A receiver: every check the library knows, in the order the specification needs.
EntityAddress
The address of a congestion point or other entity [XSD EntityAddressType]: ean. followed by 12 to 34 digits, or ea1.YYYY-MM.<naming authority>:<name>.
InternetDomain
The Internet domain of a participant [XSD InternetDomainType]: lower-case labels of letters, digits and inner hyphens, and a top-level label of two or more letters.
IspDuration
The length of an imbalance settlement period, whole minutes that divide a day (PT15M) [UFTP §4.2.2 ISP-Duration].
IspSpan
One ISP element: Start (the first ISP of the day is 1) and Duration (a number of ISPs, 1 by default).
KeyLookupErrorcs1
Why a key lookup failed. It maps to 419: the sender may retry once DNS or the configuration is fixed.
Limits
Bounds on what the decoder will read. Each can be lowered but never raised past a hard cap, and none can be turned off.
Market
The agreed values of a market: its ISP length and time zone [UFTP §4.2.2].
MessageUuid
A message or conversation identifier: a UUID in the hyphenated 8-4-4-4-12 form [XSD UUIDType]. Compared without regard to case.
OpenOptionscs1
How open reads: limits, XSD relaxations and the domains this endpoint serves.
Openedcs1
A message whose signature verified and whose XML is valid UFTP from the sender it claims, as open returns it.
Outboxcs1
The requests this endpoint sent, kept for a retention, so a response can be checked against them and matched to them.
Participantcs1
A participant you trade with: who it is, the keys it signs with, and where it receives messages.
PublicKeyscs1
A participant’s published public keys: signing key and encryption key, written as cs1. and Base64 of the 64 bytes.
Rejection
A refusal, with the rule that was broken and, where there is one, the attribute or element that broke it.
ReplayGuardcs1
Remembers the messages accepted within a time window and refuses replays.
SignedMessagecs1
The secure wrapper every message travels in [XSD SignedMessageType].
SigningKeycs1
A participant’s private signing key.
SpecVersion
The Shapeshifter specification version a message claims, major.minor.patch [XSD SpecVersion].
TimeZoneName
An IANA time-zone name such as Europe/Amsterdam.
VerifyingKeycs1
A public signing key.

Enums§

AcceptedDisputed
The AGR’s answer to one order settlement [XSD AcceptedDisputedType].
AcceptedRejected
The outcome of a request [XSD AcceptedRejectedType].
AvailableRequested
Whether a FlexRequest ISP asks for flexibility or only shows room for it [XSD AvailableRequestedType].
Disposition
How a rejection reaches the sender [UFTP App. 4 §4].
MeteringProfileType
The kind of data in a metering profile [XSD MeteringProfileEnum].
MeteringUnit
The unit of a metering profile [XSD MeteringUnitType].
RedispatchBy
Who is responsible for redispatch on a congestion point [XSD RedispatchByType].
RejectKind
What kind of failure a Rejection is, and so how it travels back to the sender.
RejectionReason
Why a message is rejected, in the words of the specification: the generic table of [UFTP §3.5] and the reasons its use cases name (§3.6 to §3.10).
Role
A USEF role [XSD USEF-RoleType].

Constants§

MAX_KEYScs1
The most keys a participant may publish at once [UFTP App. 4 §2].

Traits§

IntoKeyscs1
What a key lookup may return: one key, or the keys of a rollover.

Functions§

opencs1
Opens a received SignedMessage document.
sealcs1
Encodes message, signs it with key and wraps it.