reference

package
v1.0.0-alpha.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

edo.dev/ake/internal/reference

This package is an executable integration example, not a production service. It shows how the core AKE fits around an untrusted directory, an authoritative single-use OTK store, explicitly configured identity trust, SPK rotation, and application control messages.

Pairwise flow

Party.Publish drives prekey.Manager: the initial call stages and publishes a signed-prekey epoch, while later calls use its atomic replenishment path. The in-memory backend implements both prekey.Backend and ake.OneTimePreKeyStore. Directory.FetchForHandshake atomically removes one public OTK record; strict v1 refuses an empty inventory rather than degrading to another handshake.

Party.Send:

  1. fetches a bundle and reserved OTK record;
  2. checks the requested party id and explicitly configured trusted identity;
  3. verifies bundle freshness and both signatures;
  4. calls ake.Initiate and seals one payload.

What Party.Send returns is this package's own Envelope type: a handshake with its first payload, whose PendingSession the receiver retains. It is not ake.Envelope, the library's stateless one-shot message, which Party.SealTo and Party.OpenFrom use. Where this document says "envelope" without that qualification it means the first.

Party.Receive selects the exact SPK epoch, calls ake.Accept with the backend as its ake.OneTimePreKeyStore, and confirms the session by opening the first payload. The tombstone is recorded before the private pair is returned to Accept, which scrubs it before Open runs, so a failed open still burns the OTK. The reference retains the resulting PendingSession for five minutes in a 64-entry cache keyed by the initial message's authenticated content digest, which excludes the randomized composite-signature witness, with at most eight entries for one trusted identity. A retransmission of that authenticated content, including one with another valid signature witness, retries Open directly instead of calling Accept against the tombstone. A production service needs its own bounded lifetime, capacity, and per-peer policy. Party does not implement the store itself: holding a *Party never yields a private OTK. An envelope naming an already tombstoned OTK with no retained pending state is refused with the opaque ake.ErrAuthentication result. Cache capacity never blocks a valid first record: Party.Receive attempts the authenticated open before deciding whether failed confirmation state needs retention. Retaining a failed open at a limit evicts the oldest entry from the same identity when it has one; otherwise it evicts the oldest entry of whichever identity holds the most, so identities that fill the cache between them lose their own entries before a peer holding a single one does. A separate 1,024-entry FIFO caches fingerprints of successfully opened envelopes for cheap exact-replay rejection. Evicting a fingerprint does not re-enable the replay: the authoritative OTK tombstone remains the barrier.

After Party.Close, every error-returning Party operation except the idempotent Close reports ErrPartyClosed; accessors such as PublicIdentity and GroupKeyID return zero or empty values.

The reference state is in memory and Party is deliberately single-goroutine. The backend uses the same stage, publish, replenish, retirement, consumption, and tombstone boundaries a durable adapter needs, but loses all state with the process. A production adapter must persist them transactionally. Restores and replicas must never let an older private record override a newer tombstone. A consumed private pair must leave no readable copy in any backup, replica, log or snapshot, and across all replicas of one store a pair must go to at most one taker (SPEC.md section 16).

Rotation

Every OTK signature names one SPK id. Rotating the signed prekey therefore publishes a fresh OTK inventory for the new epoch. Reserved old-epoch records may remain available locally only during the bounded grace window in which the previous SPK private is retained. DropPreviousSignedPreKey ends that window.

Rotation uses prekey.Manager and its bounded grace epoch. The illustrative backend atomically stops its in-memory reservations and tombstones remaining OTKs when grace ends. It is still not durable: it cannot reconcile a crash, coordinate another process, or prevent storage rollback.

ReplenishIfLow adds records without relisting any OTK already reserved by the directory.

Publication follows the prekey.Rotation contract. A failed Stage, or a first Publish that wraps prekey.ErrNotPublished, aborts the candidate. Any other Publish error is ambiguous and permits only retrying Publish on the same Rotation. After a few bounded retries, Party keeps the unsettled Rotation; later calls to Publish, RotateSignedPreKey, Restart, or Close resume it and report prekey.ErrRotationPending while it remains unsettled. A durable adapter must keep the Rotation in the same way, or reconcile the backend's candidate before RestoreManager after a crash. Within one process a pending value that the caller did not keep is not lost: Manager.PendingRotation returns the Rotation, and Manager.PendingReplenishment a pending batch, for as long as its Publish or Commit, or its Abort, has not succeeded. Party holds the Rotation from before Stage runs, marked for abort until Stage returns nil, so a backend Stage that panics or exits its goroutine leaves a candidate the next call aborts rather than one nobody owns.

A replenishment whose Commit fails is abandoned with Replenishment.Abort, which never calls the backend: a batch that committed stays public, and one that did not is dropped. Party holds the batch from before Commit until that Abort succeeds, so after an abnormal Commit the next Publish, RotateSignedPreKey, DropPreviousSignedPreKey, Restart, or Close abandons it first and otherwise reports prekey.ErrReplenishmentPending.

Record channel lifecycle and restart

Example_recordChannel carries the pairwise lifecycle through the record layer using the exported EstablishConfirmedSessions, EstablishRecordChannels, and RekeyRecordChannels helpers. It confirms the responder before creating channels, binds a caller-chosen channel id through AppInfo, exchanges reordered records, rejects a replay, and stages a fresh authenticated handshake as record epoch 1, carrying the confirmation and the reply through the old epoch. The rekey follows the procedure of SPEC section 11 step by step, and the helper differs from a deployment in one respect. These synchronous helpers are for executable orchestration examples and will be handed nothing more once a step has returned, so where a deployment's initiator keeps waiting for a matching value and withdraws only when its timeout ends, the helper's initiator calls AbortRekey at once and sends nothing; the current epoch stays usable, and the next call to the helper succeeds, because the next attempt's confirmation releases a responder still committed to the withdrawn one. A failure after the initiator has activated destroys both reference channels and requires rebuilding.

These three helpers call the Channel rekey methods directly, one step after the other over a path that loses nothing. They show the steps and the checks; they do not show what a deployment needs when records are lost, delayed or reordered.

DriverLink shows that. It joins two parties' record.Drivers by an in-process link that can lose records and has a clock the caller advances, and it is the reference for the rekey of an application built on the Driver. Despite its name it is not a record.Link: it is this package's wiring of two Drivers over one simulated path, and LinkPair below is the reference for a record.Link.

  • EstablishDriverLink performs a handshake whose first record is marked record.PurposeNewChannel and builds a Driver on each side.
  • StartRekey performs a handshake marked record.PurposeRekey. The responder reads the mark with record.OpenHandshakePurpose and either adds the handshake to its Driver or builds a new Driver, so it never mistakes a rebuild for a rekey. This in-process reference then drops the old Driver at once, which SPEC section 11 ("Rebuilding") forbids in a deployment: there a handshake that arrives destroys nothing, and LinkPair shows the replacement that is safe.
  • Advance is the application's loop: pass each record to Driver.Receive, send what it returns even when the output says the record was dropped, stop only on an error, and call Driver.Tick.
  • Rebuild replaces both Drivers at once, after a restart or a record.DriverRebuildRequired event. Only this in-process link can do that: it sees both parties, and its handshake path loses and delays nothing. It puts a DriverLink back in working order for the rekey tests and is not a procedure for a deployment.

The Driver does the rest: it resends the confirmation, keeps one early confirmation, retransmits the first record of a new epoch from either side, and times out. Example_driverLink runs data, a rekey, a restart and a rebuild. TestDriverLinkRekeysOverLossyLink rekeys about 35 times per run with a quarter of the records lost in each direction, including runs in which the responder sends nothing of its own.

LinkPair is the reference for replacing a channel, and for an application built on record.Link. It gives each party a Link toward the other and joins them by a record path and a handshake path that can both lose what they carry. Each end does only what one endpoint can do: it sees its own Link and what reaches it.

  • An end prepares one handshake at a time, keyed on the output's Request. When a Link's output has NeedHandshake and no preparation is running, the end keeps its Request and begins one: the fetch of the peer's bundle, which takes LinkPair.FetchDelay at that end, zero unless a test sets it. The end goes on receiving and running its timer meanwhile. A NeedHandshake that comes while a preparation runs begins nothing: with the same Request it repeats the request, and with another it is a request the Link made since, which the running preparation answers; LinkPairReport.Repeats counts both.
  • When the fetch has returned the end clears the Request it kept and reads Link.Status before it reserves anything. Unless Seeking is true, Attempt is false and StartAfter is not after the present time, the preparation stops there with no one-time prekey reserved and no call to the Link, and LinkPairReport.Stopped counts it. Otherwise the end reserves a one-time prekey, initiates, seals the handshake's first record with Link.SealPurpose and calls Link.StartChannel. If the handshake cannot be made, as when the peer publishes no prekey, it calls Link.CannotInitiate and sends the hint the Link asks for. If StartChannel refuses the handshake, the end zeroes the Session and waits for the next NeedHandshake. TestLinkPairSlowFetchPreparesOneHandshakeAndStopsALateOne runs a fetch that outlasts several requests.
  • What the reference does not do is what the documentation of package record advises an application that expects to be slow: call Link.CannotInitiate first, send the hint, and then prepare. A LinkPair end calls CannotInitiate only after a handshake could not be made, so an end that restarted sends nothing for the whole of its fetch, and a peer that still holds the earlier channel and does not probe it does not notice the restart in that time.
  • For a handshake that arrives it calls Link.OfferHandshake with the digest first, accepts only if the Link says so, and passes the pending session to Link.AcceptHandshake.
  • Advance is the loop: frames to Link.Receive, hints to Link.ReceiveHint, then Link.Tick when Link.Wake reports a time that is not zero and has come. A Link that has not been ticked reports a time that has passed, so a new Link is ticked at once with no flag of the end's own.
  • Restart gives one end a new Link, as a process restart does. Nobody tells the other end. TestLinkPairComesBackAfterARestart restarts either party, or both, and the pair settles on one channel again; TestLinkPairHintWhenThePeerPublishesNoPrekeys restarts a party that cannot start a handshake; TestLinkPairOverLossyPaths does it with a fifth of everything lost. Example_linkPair runs the sequence.

Delivery is the reference for what a Link leaves to the application: acknowledged delivery. Over one record.Link, messages passed to Delivery.Send are handed to the peer's application in the order sent, across loss, duplication, reordering, cuts of the path, rekeys and the replacement of the channel. How often depends on whether the ends keep their Deliveries:

  • While both ends keep their Delivery, every message is handed over once, in order.
  • When an end makes a new Delivery, as every restart of its process does, a message is handed over at least once. The duplicates are among the messages the other end's output counts as Unconfirmed, and what the lost Delivery had taken and not handed on is gone with it. They are handed over twice at the end that made the new Delivery, which is told nothing of them. Either end may be that end, so an application that handles every message exactly once puts an identifier of its own in each message and keeps, at each end, the identifiers of the messages it handled in durable storage, committed with the handling.
  • When both ends make a new one at the same instant, no message is handed over twice: what the lost Deliveries held is gone, and a new Delivery takes messages only from frames sealed for its own stream (none in 300 such runs). Neither output says anything, except where the first frame a new Delivery opens is a late one of the peer's lost Delivery, sealed for no stream: it takes that stream as the one it receives, so the first frame of the peer's new Delivery reports PeerRestarted there, and the messages it counts as Unconfirmed were never handed over. When the second end makes its new one a moment after the first, the case of one end applies to each loss. Where the second loss comes before the end that kept its Delivery opened a frame of the first's new one, neither end is told anything, as for losses at the same instant. Measured on a path that loses a tenth of the frames, duplicates three tenths and delays them by 5 to 600 ms, with ten messages a second each way throughout: 5 seconds of traffic, then one end made its new Delivery and the other made its own 0.1 to 3 seconds later in steps of 0.1 s, then 10 seconds more of traffic; either end first, half the runs with a new Link at each loss and half over the Link in use, 120 runs. Up to 14 messages a run were handed over twice, every one of them counted as Unconfirmed by its sender. The runs draw from one set of seeds; other seeds give other counts, higher ones as well.

Like a Link it does no I/O and reads no clock. The application passes every frame of the record path to Delivery.Receive in place of Link.Receive, calls Delivery.Tick in place of Link.Tick when Delivery.Wake says it is due, and sends what each output holds. Until a call has passed it a time, a Delivery reports from Wake a time that has passed, as a Link does until its first Tick, so its first Tick is due at once. After a pause in which frames queued up, of its own process or of its reading of the path, it passes all of them to Receive before it calls Tick, which is the Link's rule too. The times it is passed must never go backwards, which is the Link's rule as well: time.Now() as it is, with its monotonic reading. A Delivery keeps the time at which each of its waits ends, as a Link does. With times set back, a wait that was running ends later by as much as they were set back: a frame waiting to be sent again, an acknowledgement that is due, the report of a stall. A wait that begins afterwards ends when it should (TestDeliveryTimesSetBackLengthenTheWaitsThatWereRunning). So what a step back costs depends on what was waiting when it came. With one end's times set back by ten minutes and that end passed 3,000 messages in the next five: with nothing waiting at the step its peer was handed all of them (TestDeliveryTimesSetBackWithNothingWaitingDelayNothing holds that for 300 messages); with the step in the middle of traffic both ways, measured over twenty runs on each path, it was handed all of them in every run on a path that loses nothing, and in all but three and all but two runs, which lacked up to four messages, on paths that lose a twentieth and a tenth.

Tick is the one call that reports a stall, and a Tick that finds the report more than ResendInterval overdue makes none: the application did not run its timers when Wake said so, and the acknowledgements that end the stall may wait in its queue. The report is put off by sixteen ResendIntervals from that Tick, 4 seconds with the defaults, and by StallAfter where that is less: the longest a frame waits before it is sent again. An acknowledgement read in that time starts StallAfter over. Without one, a Tick that comes no more than ResendInterval after the end of that time reports, and a later one puts the report off again, the process having stopped a second time or being as busy as before. The times a report is put off by add up to StallAfter at the most, and the Tick that finds it due after that makes it, however late it is itself (TestDeliveryReportsAStallFromTickAlone, TestDeliveryPutsAnOverdueReportOffWhileItsTicksAreLate).

So an application that calls Tick when Wake says so, or up to ResendInterval later, is told of a lasting stall once every StallAfter. One whose Ticks are later than that is told of every stall all the same, and less often: two reports are StallAfter apart at the least, and twice StallAfter and the time its Ticks between them were late at the most. Through a cut of an hour, with each Tick the same time after the time Wake reported: 120 reports with Ticks on time, 65 with Ticks 251 ms late, 34 with 5 s and 11 with 31 s (TestDeliveryReportsEveryStallToAnApplicationWhoseTicksAreLate).

Without the putting off, the order decides whether an application that tests its channel at every report replaces a channel that works. Over the 36 schedules of TestDeliveryReportsNoStallForAcknowledgementsThatQueuedUp, in which this end's process stops for longer than StallAfter after a report and resumes with the peer's acknowledgements queued, a Tick that reported whenever StallAfter had passed did this: the whole queue passed before Tick, no report and no Rebuild; Tick before the first queued frame, a report in all 36 and no Rebuild, the Link probing or seeking; Tick after one queued frame, a report and a Rebuild in 23; after two frames in 16, after three in 11, after five in 7, after ten in 1, and after twenty or more in none. With the report put off, none of these orders makes a report or a Rebuild in any of the schedules, which the test holds. Neither does a process that stops again for 20 seconds after that Tick, with the rest of its queue unread, and calls Tick before it reads on (TestDeliveryReportsNoStallWhenItsProcessStopsAgainWithItsQueueUnread): that second Tick finds the report overdue again and puts it off again, and the acknowledgements in the rest of the queue are read before it is due.

What is put off is the report of the Delivery, and nothing of the Link. The same Tick runs the Link's timers, and the Link allows a queue one of its own resend intervals where the deadline of a probe or a confirmation is more than RekeyTimeout past, and none where it is less (SPEC section 13, rule 15): an application that calls Tick first and passes its queue later than that has a Link that probes, seeks or replaces a channel that works, with no report from its Delivery. Over the same schedules, with Tick before the first queued frame and the queue 1.1 seconds later, the pair ended on another channel in 35 of the 36, against 14 with the whole queue passed before Tick. The Delivery is silent through it and the Link is not: in each of those 35 the Link's events of the resume, LinkStalled and LinkReplaced, are in DeliveryOutput.Link.Events, which is where an application learns of it. So the rule stands for a Delivery as for its Link: the whole queue first, then Tick.

One case of the report itself is left to the order: a queue that the application is reading when the report comes due, or no more than ResendInterval after that, as when its pause ended just before that time, or a second stop ended at the time the report was put off to. A Tick among the queued frames is on time then, and reports; an application that passes all of its queue before it calls Tick has no such case.

The application goes on acting on the Link's own output, which DeliveryOutput.Link passes on without Send, Plaintext and Delivered: the Link's frames are in the output's Send once, and what the Link opened is the Delivery's to read (TestDeliveryOutputLinkHasNoFramesAndNoPlaintext). A record the peer sealed on its Link directly, with no Delivery or beside one, is no frame: the Delivery drops it and counts it in DeliveryStatus.NotFrames, the one trace it leaves (TestDeliveryCountsTheRecordsThatAreNoFrameOfADelivery). That holds for a record that begins with the kind of a frame and is as long as a header as well: every frame carries a fixed marker after its kind, and a record without it is no frame, so the streams it would seem to name never have the receiver report PeerRestarted for nothing. A record of the application's carries the marker by accident with a chance of about 2^-64; only one written to pass for a frame is taken as one (TestDeliveryKeepsReceivingAfterARecordThatBeginsWithAnotherByte, TestDeliveryCountsARecordThatBeginsWithTheKindOfAFrameWithoutTheMarker). It goes on running the handshakes, and calling Probe, StartRekey or Rebuild on the Link itself, from any goroutine. It makes one call on the Delivery at a time, which is all it serialises: a frame's channel, epoch and sequence number are its record's, which the sender takes from Link.SealNumbered and the receiver from LinkOutput.OpenedAt, so a record that another goroutine has the Link seal during a call of the Delivery takes a number and nothing else (TestDeliveryDeliversWithRecordsSealedBesideItFromAnotherGoroutine). So NotFrames rises for one cause: a peer that seals on its Link beside its Delivery. A Delivery counts with the MaxSkip and the ReplayWindow its Link was made with, which the Link's status reports. Zero in DeliveryOptions means the Link's, and a value that is not the Link's is refused: NewDelivery returns an error wrapping ake.ErrUsage for it, and SetLink for a Link made with other values than the Delivery counts with (TestNewDeliveryCountsWithItsLinksLimitsAndRefusesOthers). The check is made, and belongs in a port, because nothing else shows a difference. What it prevents happens on a path that loses frames: there a Delivery that counted with higher values than its Link's would stop delivering for good, with no error from any call. With both made to count with a MaxSkip and a ReplayWindow of 256 over Links of 64, which only a test can do, twenty minutes after a cut of two minutes neither backlog had drained and no message was handed over in the last ten of those minutes, with the channel kept and no handshake performed. Each end reported DeliveryUnacknowledged every StallAfter, as it does through a cut, and each Link refused every frame of the peer's Delivery that arrived in those ten minutes as older than its replay window, record.ErrTooOld in DeliveryOutput.Link.Dropped, hundreds of times, and none as too far ahead (TestDeliveryCountingWithLimitsAboveItsLinksStopsDelivering). The decisions are stated with their reasons in the type's documentation, and six of them are easy to miss in a layer written from scratch:

  • Messages have their own numbers and the acknowledgement is cumulative, both inside the sealed plaintext. Each frame also states its sender's position, and its own epoch and sequence number are its record's, which the Link reports to both ends (Link.SealNumbered, LinkOutput.OpenedAt). The position is one more than the sequence number of the peer's frame it opened latest, which is the one sealed latest of those it opened: the highest epoch and, within it, the highest sequence number. NextSequence less the position the peer reported is the distance: how many numbers past the one the peer expects next the next record sealed would be, at the most. The peer refuses a record more than MaxSkip past the one it expects next, and a Delivery seals nothing at a distance of MaxSkip or more, with one exception: the two acknowledgements of the fourth item below, which a Delivery seals in a numbering it did not see begin, at whatever distance it counts there. The Link's own records count in the distance from when they are sealed, because nothing tells a Delivery which of them the peer opened. The fractions of MaxSkip below are whole numbers of records, each taken from MaxSkip divided by 4, by 8 or by 2 without the remainder: three quarters are three times MaxSkip/4 and seven eighths seven times MaxSkip/8, which is 48 and 56 with the default of 64, and 45 and 49 with a MaxSkip of 63 (TestDeliveryCountsItsFractionsOfMaxSkipWithoutTheRemainder). The distance decides what may be sealed:

    • messages, up to a quarter of MaxSkip unacknowledged at a time, while it is under three quarters;
    • an acknowledgement while it is under seven eighths, and one that answers a frame which opened for the first time while it is under MaxSkip;
    • from one half, when nothing is sealed and unacknowledged, one acknowledgement marked to be answered, which asks for the peer's position and is sent again as the same bytes until the peer reports it: it goes out five times, the wait doubling, and then again whenever a record of the peer's opens. Without it, probes that pass on an idle channel use the distance up and the next message is never sealed;
    • two acknowledgements, and no more in one numbering, past the limit that stops them, when only records sealed before the Delivery first saw the numbering put the distance there: a new Delivery over a channel in use counts every earlier record as if the peer had opened none, and the answer to either acknowledgement reports the peer's position;
    • past these limits nothing but the last frame again, as the same bytes.
  • Acknowledgements wait a short time and ride on any message sealed meanwhile. Each one takes a sequence number, and they alone can carry the numbering past a frame that was lost.

  • A frame that is not acknowledged is sent again as the same bytes, which takes no number, until NextSequence has left it more than the replay window behind. Then the message is sealed again under a new number, because the old frame may be refused as too old for good. How long a frame waits follows the time acknowledgements take, as a transport's wait does: the time is measured from the messages that went out once, one measurement for each acknowledging record, smoothed with its deviation as RFC 6298 does it, but for the start: the first measurement is the time and an eighth of it the deviation, where RFC 6298 takes half, so that the first wait after it is one and a half times that measurement and not three times it. The first wait is that time plus four times the deviation, and ResendInterval where that is less. Each further wait is double the one before, up to sixteen intervals (TestDeliveryFirstWaitFollowsTheTimeAcknowledgementsTake). A fixed wait shorter than a slow reader's acknowledgements, or than a path that grew slower, sends every frame twice, the copies are more for the reader to read, and its queue grows with what it is sent, with nothing to report it, since acknowledgements go on arriving. While every frame goes out twice nothing is measured, so the first waits also double each time the first wait of a frame, or any wait of the first unacknowledged one, ends with the peer heard, once for the frames of a burst, until an acknowledgement is measured (TestDeliveryFirstWaitsDoubleWhileThePeerIsHeardAndAcknowledgesLate, TestDeliveryFirstWaitsOfABurstDoubleOnce). With acknowledgements that come 0.3 to 1.5 s later than the path takes, an end sends 1.00 to 1.03 frames a message a minute after the change (TestDeliveryFirstWaitFollowsAnAcknowledgementTimeThatGrows). What it costs is in "A stall": a frame lost waits the measured time and not ResendInterval. Two things end a wait sooner: the peer reports a position past the frame without acknowledging its message, so that the frame was lost or overtaken, and it goes out one interval after it last did, once for a frame behind the first unacknowledged one and for every later position for that first one, which is missing at the peer for as long as it is not acknowledged (TestDeliveryPositionPastAFrameEndsItsWaitAfterOneInterval); and a record of the peer's opens after sixteen intervals in which none did, as after a cut, which sends what waits and drops what was measured. No other record that opens sends anything. The one interval an overtaken frame is left has a price on a path that reorders by more than that: the frame is sent again and arrives twice. Over two minutes of ten messages a second each way on a path that loses nothing and delays each frame by 10 ms and a random part of a spread, the lowest and the highest over eight seeds, an end sent 1.08 to 1.11 frames for each message handed over with a spread of 240 ms, 1.35 to 1.45 with 500 ms, 2.20 to 2.39 with 1 s and 4.68 to 5.24 with 2 s; with a ResendInterval of 1 s, 1.00 up to 500 ms, 1.49 to 1.57 with 1 s and 3.18 to 3.41 with 2 s. Other seeds can give figures outside these ranges. Leaving the frame four times the measured deviation where that is longer lowered this little and slowed the lost frames as well, which look the same: a path that loses a fifth carried 15 messages a second, below the figures under "The rate". On such a path an application raises ResendInterval.

    A slow reader's queue drains when it takes more frames a second than it is sent: one for each message, an acknowledgement by itself where no message of the other direction carries one, and the frames sent again. A reader that takes no more than the messages offered never drains. Measured with readers of 0.8 to 5 times the messages a second, 10, 25 and 50 messages a second each way, one end reading slowly and both, and the reader stopped once for 2, 20 and 90 seconds, 378 runs in each of three sets of seeds, the queue was back a quarter of an hour after the stop in (TestDeliveryQueueOfASlowReaderDrainsWhenItReadsTwiceTheMessages):

    Reader, in messages a second offered 5 to 20 ms, nothing lost 5 to 20 ms, a tenth lost 100 to 200 ms, nothing lost
    no more than the messages no run no run no run
    1.5 times 4 of 18 runs no run 0 or 1 of 18
    twice every run no run 9 or 10 of 18
    three times every run 8 to 11 of 18 12 of 18
    four and five times every run 12 to 14 of 18 12 of 18

    The test holds the first row and the first column from twice on; the rest is what the runs measured, and nothing guarantees it. Where a tenth is lost the runs that kept a queue were mostly at 50 messages a second; on the path of 100 to 200 ms every run at 50 messages a second kept one, since sixteen messages unacknowledged at once carry fewer than 50 a second there. With first waits of ResendInterval whatever was measured, a reader of twice the messages on the first path had its queue back in 0 or 1 of 18 runs. The price of sending the first unacknowledged frame for every later position is paid to a party on the path that lets everything through but that frame: it draws the frame once for each ResendInterval, 1,210 to 1,213 times in five minutes of ten messages a second each way, in which the end's Delivery sent 5,584 to 5,641 frames where the traffic by itself takes 3,000, one run in each set (TestDeliveryFrameThatNeverArrivesIsSentForPositionsOnceAnInterval).

  • A frame the Link refuses as a replay or as too old is answered, since its sender may have missed the last acknowledgement, but the refusal comes from a header that nothing authenticates. The answer is the last frame again, as the same bytes, when the peer has not reported that frame and it still says what an acknowledgement would; nothing when the peer has reported it; and a new acknowledgement only when that frame is out of date or too old to open, under seven eighths of MaxSkip and at most MaxSkip/8 of them until the count starts over; past either limit the last frame again, out of date as it is, which uses no number and still carries the acknowledgement. Such answers go out once per ResendInterval at the most, each wait double the one before, up to sixteen intervals. The waits and the count start over only for a frame of the peer's Delivery, sealed for this stream, that opens for the first time and moves a message: it acknowledges one, brings a new one, or moves the first message expected. The peer's application is sending then, and what it sends again must not wait behind the answers that refused frames drew. A position that moves starts nothing over, in either direction: the answer to a refused frame moves both where it opens, and two ends handed refused frames at the same moment would otherwise draw a sealed record from each other with every exchange, for as long as the frames arrive. The Link's own records that open, the echoes of a probe and their answers, start nothing over, and a frame that opened before never gets that far. So for frames that the channel in use refuses as a replay or as too old, which carry its tag, the Delivery of an idle end seals at most MaxSkip/8+2 records more than it seals with no refused frame, ten with the defaults, however many arrive and at whichever end, until a message moves: the sealed answers, one record that asks for the peer's position, and one answer to the peer's. Its answers settle at one frame per sixteen intervals, four seconds with the default. Measured over an idle hour with refused frames at both ends at the same instant, at one end, and at the two in turn, from one a second to a thousand a second, with and without probing: at most 8 sequence numbers more than in the same hour with none (TestDeliveryRefusedFramesAtBothEnds). Over an idle hour with both applications probing after ten seconds of silence and 35,918 refused frames at random moments, the end that sent most sent 890 frames, one per 4.04 seconds, and its Delivery sealed 15 records, one more than in the same hour with none (TestDeliveryRefusedFramesWhileProbesPass). The ten bound the records of the Delivery for such frames, not the sequence numbers an idle pair uses. The Link seals records of its own whenever it probes, and a party on the path can make it probe, with frames under a tag no channel has and by holding genuine frames back so that every echo is sent again. Those records are the Link's, and SPEC section 13 states their limit under "Limits". A Delivery adds its exchange of positions: from a distance of half of MaxSkip it asks with one record and the peer answers with one. Measured per end over an idle hour:

    Schedule Sequence numbers The Link's records The Delivery's records
    frames under an unknown tag, one a second 258 to 259 240 18 to 19
    the same, every genuine frame held 3.5 s 1,832 1,680 152
    the same, every genuine frame held 7.2 s 3,907 3,601 306
    no such frame, genuine frames held 7.2 s, applications probing after ten seconds of silence 2,459 to 2,467 2,301 to 2,309 158

    That is one record of the Delivery for every 11 to 15 of the Link's, and the pair kept its channel and delivered afterwards. TestDeliveryIdleUnderProbesDrawnByAParty holds each Delivery to one record for every MaxSkip/8 of its Link's and the ten.

  • The receiver keeps a message that arrives ahead of a missing one within a window of MaxSkip/4 messages, 16 with the defaults. With d the number of the last message handed over and n the number of a message in a frame sealed for the receiver's stream that opened: the message is kept when n is more than d and no more than d + MaxSkip/4 and none with that number is held; d+1, d+2 and so on are handed over for as long as the next one is held. A message numbered d or less was handed over before. One numbered more than d + MaxSkip/4 is further ahead than a sender seals before d+1 is acknowledged: it is not kept and not acknowledged, and its sender sends it again. Either frame is still answered with an acknowledgement, which states d. A frame that states a first unacknowledged message past d+1 moves d to one less than it before the rule is applied, and what is held below is dropped.

  • Every frame names the stream of the Delivery that sealed it, the stream of the peer's that it is sealed for, and the first message its sender holds unacknowledged. A Delivery takes messages and acknowledgements only from frames sealed for its own stream. Numbers alone cannot tell a new Delivery from the one it replaced: its messages would be dropped as repeats, and acknowledged. The stream a Delivery receives is decided by the frame sealed latest in the channel's numbering among those it has opened, not by the one that arrived last: a Link numbers what its end's Deliveries seal in order, so a frame of a Delivery that is gone, held back on the path, never displaces the stream of the one in its place. A latest frame that is not sealed for the stream of the Delivery that opens it is answered, the answer states that stream, and such answers wait twice as long each time until a frame sealed for the stream opens.

The frame. A frame of a Delivery is one record of the Link whose plaintext is a header of 61 bytes and, in a message frame, the message after it. Every number is big-endian.

Offset Size Field
0 1 Kind: 1 for a message, 2 for an acknowledgement. The top bit, 0x80, is a flag added to either: the sender asks for an answer.
1 8 The marker: the first eight bytes of the SHA-384 of the label ake-delivery-frame-v1, the same in every frame.
9 8 Stream of the Delivery that sealed the frame, eight random bytes, never zero.
17 8 Stream of the peer's Delivery the frame is sealed for; zero while the sender receives none.
25 8 Number of the message, from 1 through 2^64 - 2; zero in an acknowledgement.
33 8 Number of the first message the sender holds unacknowledged: one more than the number acknowledged to it, also when it holds none, from 1 through 2^64 - 1.
41 8 Number of the last message handed over of the stream named at offset 17: everything through it is acknowledged, from zero through 2^64 - 2.
49 4 Epoch of the frame of the peer's that the sender opened latest; zero before it opened one.
53 8 The position: one more than the sequence number of that frame, so the next sequence number and not the highest opened; zero before the sender opened one.

A frame's own epoch and sequence number are not in the plaintext: they are its record's, in the record's header, which the Link authenticates. The sender has them from Link.SealNumbered and the receiver from LinkOutput.OpenedAt. The frame opened latest is the one sealed latest among the frames of a Delivery opened on the channel in use, by the epoch and sequence number of their records. A receiver takes a position only when the frame opened on the channel whose numbering it keeps (the RecordPosition.Tag of LinkOutput.OpenedAt), the epoch beside the position is its own sending epoch, and the position is past the one it holds and no more than its NextSequence. A sender sets the flag while its distance is half of MaxSkip or more, and a receiver answers with an acknowledgement every message and every flagged frame that is sealed for its stream and opens for the first time. A plaintext shorter than the header, whose first byte is no kind of a frame, or that does not carry the marker, is not a Delivery's: it is dropped, and counted in DeliveryStatus.NotFrames. Its position is its record's, so it cannot move the numbering frames are compared by. An authenticated frame with a message number outside the ranges in the table is a malformed Delivery frame and is dropped before its counters move the receiver. TestDeliveryFrameHeaderLayout compares one acknowledgement and one message frame with this table byte by byte.

The rate. At most MaxSkip/4 messages are sealed and unacknowledged at a time, 16 with the defaults, whatever QueueLimit is, and the next is sealed when an acknowledgement arrives, so the rate follows the time to the peer and back. Measured with the defaults, one end sending as fast as its queue takes messages, over two minutes, three runs in each of three sets of seeds: 112 to 113 messages a second on a path that loses nothing and delays by 10 to 50 ms; 157 a second with a delay of 1 ms; 28 to 30 a second on a path that loses a tenth of the frames and delays them by 10 to 250 ms; 16 to 18 a second on one that loses a fifth and delays them by 10 to 400 ms. A backlog of one hour of messages offered at ten a second into a cut, 36,000 of them, drained, one run in each set, in 5 m 20 s to 5 m 22 s on the first of these paths, in 20 m 22 s to 20 m 38 s on the one that loses a tenth, and in 34 m 50 s to 35 m 23 s on the one that loses a fifth (TestDeliveryRateAndBacklogAreTheFiguresTheDocumentsState). With first waits of ResendInterval whatever was measured the same runs carried 31 to 33 and 20 to 21 messages a second on the two paths that lose frames, and drained the backlog in 18 m 37 s to 18 m 50 s and 28 m 46 s to 29 m 11 s: a frame lost waits the measured time. ErrDeliveryQueueFull from Send is the only sign that an application offers more than the path carries. Send also refuses, with an error matching ake.ErrUsage, a message that no record carries with the 61-byte header of its frame: one longer than 68,719,476,642 bytes on a 64-bit platform and than 2,147,483,534 bytes on a 32-bit one. After it takes message number 2^64 - 2, Send returns ErrDeliveryExhausted and takes nothing. The application keeps that Delivery until its status reports no queued message, makes a new one whose fresh stream starts at one, and offers the refused message to it. Making the new Delivery has the consequences under "A restart": in particular, a peer message already handed over whose acknowledgement was in flight may be handed over again. Exhaustion takes precedence over a full queue; an invalid message size takes precedence over both.

A stall. A Delivery never rekeys and never asks for a new channel. When messages wait and nothing is acknowledged for StallAfter, the output of Tick says so, again every StallAfter for an application whose Ticks are on time, and no other call's does. The report is information and asks for nothing: what an application does at it is wait. A path that is cut and a peer that is gone for a time need nothing else. The Delivery keeps its messages and sends its frames again, and it bounds its own numbering, so what it sealed into the cut opens when the path is back and delivery goes on over the channel the Link had, with no handshake performed.

Calling Link.Probe at a report is the application's choice, and it has a price: a probe that gets no answer makes the Link seek, and a Link that seeks asks for handshakes for as long as the cut lasts, each of which reserves one of the peer's one-time prekeys ("What probing costs and gains" in the record package's documentation). Measured with ten messages a second offered each way, over a path that loses a tenth, through cuts of both directions and of one, eight runs of each length in each of three sets of seeds (TestDeliveryWaitingThroughACutPerformsNoHandshake):

Cut Applications Handshakes a run from the start of the cut Channel kept First message after the path's return within
1 minute wait 0 8 of 8 1.1 to 1.8 s
1 minute probe at every report 2 0 of 8 1.5 to 1.8 s
10 minutes wait 0 8 of 8 0.6 to 2.1 s
10 minutes probe at every report 15 2 to 6 of 8 1.8 to 2.6 s
1 hour wait 0 8 of 8 0.8 to 1.9 s
1 hour probe at every report 32 to 33 6 to 8 of 8 1.8 to 3.3 s

Where the sets differ, a figure is the least and the most of the three, and the times of the last column are the latest run of each set, and no bound, for these three lengths or for another: cut toward the first end as well, the latest run of the same lengths took 1.1 to 2.5 s in the runs below, and other lengths longer. With first waits of ResendInterval whatever was measured the ends that waited were handed the first message within 0.7 to 0.8 s: a frame lost after the return waits the measured time. A frame that waits for its acknowledgement through a cut is sent again once every sixteen ResendIntervals, 4 seconds with the default, and the first message is handed over when a frame sent after the path's return has crossed the path. The time therefore depends on where in those sixteen intervals the path returns, for each of the frames that wait, which makes it rise and fall with the length of the cut, and on the path's delay and loss. For ends that wait, measured over cuts of a minute and of ten minutes with nothing to 4 seconds added in steps of a quarter of a second, toward either end and of both directions, and of an hour with up to 2 seconds added, toward either end, 440 runs in each of three sets of seeds on a path that delays by 10 to 250 ms: no handshake, the channel kept in every run, and the first message within 2.4 to 3.8 s of the path's return (TestDeliveryFirstMessageAfterACutFollowsTheResendWait).

Each of these figures is the latest run of its test in each of three sets of seeds, which the tests draw their delays and losses from (AKE_DELIVERY_SEED_SET names the set), and where the sets differ it is the least and the most of the three; other seeds measure other figures, outside those ranges as well. None is a bound, and under loss the time has none: a frame lost after the path's return is sent again when its wait is over, each wait double the one before up to sixteen intervals, or one interval after it went out when the peer reports a position past it, and nothing limits how many are lost in a row. Over paths that lose two and three tenths, cuts of a minute with nothing to 4 seconds added in steps of 50 ms, 972 runs in each set, the first message came within 3.2 to 4.8 s. On a path that loses six tenths from its return on, 246 runs in each set, it came within 4.4 to 9.4 s, and later than 4.5 s in 0 to 17 runs. Where most frames are lost, the first unacknowledged frame is lost several times in a row and each of its waits is double the one before: that path is what sending it for every later position of the peer's is for. Measured with that frame sent for one position alone, as the frames behind it are, the first message came within 16.4 to 33.9 s in the same runs, and within 8.3 to 12.4 s where two and three tenths are lost. A shorter ResendInterval shortens the time and a longer one lengthens it: on the path that loses a tenth, 198 runs of each in each set, the first message came within 1.1 to 1.4 s with a ResendInterval of 100 ms and within 15 to 19 s with one of 1 s (TestDeliveryFirstMessageAfterACutUnderLossAndOtherResendIntervals).

The 4.5 s are sixteen times ResendInterval plus the path's longest delay each way, and on a path that loses nothing after its return that is a bound, for ends that both hold a message sealed and unacknowledged when the path returns: each end sends every such frame again within sixteen intervals, the peer has them one delay later and is handed the first message it lacks, and an end that lacked none is handed the first message its peer seals on taking an acknowledgement from those frames, one delay after that. DeliveryUnacknowledged states the steps and what the last one takes. On the path that loses a tenth until the cut ends and nothing from then on, with a ResendInterval of 100 ms, of 250 ms and of 1 s, 450 runs in each set: every run within sixteen times its interval plus the delays, and the first message within 2.3 to 3.2 s with the default interval (TestDeliveryFirstMessageAfterACutOnAPathThatLosesNothingAfterIt). An application that needs the first message sooner lowers ResendInterval, which costs frames while the path is cut.

A probe is worth that in two cases. The application has to learn that the peer is not there while it is not there, to tell a user or to send its messages another way: the Link's LinkStalled says so half a RekeyTimeout after the probe, or says that the path lost what the probe sent. Or the application has a reason of its own to believe that the path carries records while nothing is acknowledged: the channel's numbering may then have run away from what the peer accepts, which only a probe that passes can show and which needs Link.Rebuild or a rekey by the channel's initiator. An application that never probes does not learn of that case; no schedule of the tests has produced it.

If a local seal fails with record.ErrExhausted, the output of Send, Receive or Tick carries the error in SealError. The application processes the other output and calls Link.Rebuild to replace the channel. A successful probe tests connectivity, and a successful rekey resets the per-epoch sequence. Neither restores the Driver's lifetime application budget. Keep the Delivery and its queue. A message accepted by Send is already there and will be sealed on the replacement channel.

When the only indication is a stall, an application calls Link.Rebuild, or has the channel's initiator rekey, at a report of DeliveryUnacknowledged at which the test below shows that a probe of this channel passed since the report before and that nothing was acknowledged in between. An application that waits never calls it.

An application that chose to probe does so by this test. At every report of DeliveryUnacknowledged it reads the Link's status and does one of two things. It calls Link.Rebuild when all of this holds: the report before it came from the same Delivery with the same Acknowledged in its status, so that count stood still for twice StallAfter; Link.Probe, called at that earlier report, returned nil; the status has the Tag it had at that earlier report, so the channel is the same one; and the status has Up and none of Probing, Seeking and Confirming. At every other report it calls Link.Probe, whatever the status shows, and keeps the Delivery, its Acknowledged, the Tag and whether Probe returned nil for the next report; an error from Probe means no test was started, and needs nothing more. A nil error from Probe does not by itself say that a probe passed: Probe also returns nil while a probe or a confirmation is running, and a Link that seeks may be probed. The conditions together say it: the channel that was being tested then is still the Link's, the test has ended, and the Link does not seek, so the peer held this channel when it sealed the record that passed the test, and still nothing is acknowledged. Without the tag, the rest holds as well for a channel the Link adopted seconds ago. Of the 560 schedules of delivery_test.go, half have applications that follow this test and half have applications that wait: Rebuild is called in none, and none of their stalls needed it.

A restart. A Delivery has no stored form and no way to export or restore one: it lives as long as its process. Within the process it outlives its Link: an application that replaces the Link passes the new one to SetLink, and nothing is lost and nothing is handed over twice. The new Link is toward the same peer identity key: SetLink cannot check it, and a Delivery passed a Link toward another key hands that key's holder the messages the peer had not acknowledged. A peer that returns with another identity key gets a new Delivery. A restart of the process makes a new Delivery. The peer's output then has PeerRestarted, and Unconfirmed counts the peer's own messages that were sealed for the lost Delivery and not acknowledged: the new Delivery hands those over, in order, and the lost one may have handed them over before, so across a lost Delivery a message is delivered at least once, and exactly once when it was acknowledged before PeerRestarted. Unconfirmed is a count, and Send returns no handle: the messages meant are the first that many of the ones the Delivery holds unacknowledged, in the order they were passed to Send. The Delivery sends all of them to the new stream by itself, so an application that passes its own copies to Send again after PeerRestarted has each handed over a second time. Each report has its own count, and the counts of two reports in a row together cover the messages that may be handed over twice. What the lost Delivery had taken and not delivered is gone with it. The type's documentation lists what holds.

An application that needs exactly once across its own restarts has to write the stored form itself. As an outline, not something this package provides or tests, it would hold the two stream identifiers (stream, peerStream); for sending, the number of the next message, the number acknowledged through and every unacknowledged message with its number and whether it was sealed for the peer's stream (nextID, acked, queue), stored before Send returns; and for receiving, the number of the last message of the peer's stream handed over and the count handed over in all (delivered, handed), committed together with the application's own handling of each delivered message. Nothing of the channel belongs in it. The outline does not cover a crash between the storing of a message and the return of Send: Send returns no handle, so an application that did not see it return passes the message again after its restart, and a message that was stored is handed over twice.

The tests in delivery_test.go run two ends through steady traffic, cuts of one direction or both from five seconds to an hour, a Link replaced under a Delivery that is kept, a rekey, replaced channels, a channel whose probes are spent, an idle channel whose probes pass, a Delivery lost at one end, at both, twice in a row and over a channel that has sealed more than MaxSkip records, a held frame of a lost Delivery, forged frames, an idle hour of refused frames, the edges of each limit, and seeded schedules of these. Example_delivery runs two ends over a path that loses every third frame. The package cannot be imported from outside this module: Delivery is there to be read and ported. A port takes delivery.go and two things from outside it: readSystemRandom (random.go), with which each new Delivery draws its stream identifier from crypto/rand.Reader as the package found it when it was initialised, and Delivery's Format method with the writeName it calls (text.go), with which fmt prints a Delivery as its name alone. A port without the second prints, with fmt, the fields of a Delivery, its stream identifiers, counters and timers among them, though not its messages.

Example_recordChannel, described at the start of this section, ends by destroying both record channels and calling Party.Restart. Restart reconstructs the identity and prekey.Manager from the backend while preserving tombstones, completed replenishment IDs, the timestamp floor, and the current and grace epochs. It keeps the same in-memory backend alive to stand in for durable storage; a real restart of this backend would lose all of that state, which a durable adapter must not. Volatile handshake fingerprints are deliberately lost, so the tombstone remains the replay barrier. Record channels are not restored; the peers establish a fresh authenticated session instead.

Integration decisions

Each runnable example below shows the correct reaction to one error or export a deployer must handle. They remain illustrations, not production policy.

Example Decision
Example_duplicateDelivery ake.ErrAuthentication: drop a duplicate or retired-key envelope; the sender re-sends under a fresh OTK.
Example_oneTimeKeySpent ake.ErrOneTimePreKeySpent: retransmit the original initial message instead of initiating again.
Example_keyMismatch ake.ErrKeyMismatch: refuse a wrong peer identity or channel; do not retry blindly.
Example_sessionExports Session.Export, Session.Binding, Session.ConsumeExport, and the reserved built-in record label.
Example_recordDeliveryErrors record.ErrTooFarAhead (drop, and never act on this error alone; the direction resumes when missing records are retransmitted as sealed, or at the next rekey where the confirmations travel outside the record sequence), ErrTooOld/ErrReplay (drop), ErrEpoch (drop; never rekey on it).
Example_recordRekeyState Channel.Epoch/ReceiveEpoch pacing; record.ErrRekeyState (wait, or rebuild the pair); record.ErrRekeyCommitted (wait for the initiator's record or for its next attempt, whose confirmation supersedes the commitment).
Example_graceActive prekey.ErrGraceActive: retry the rotation after the grace window ends.

Package tests cover the decisions that need internal fault injection: PendingSession.ExportUnconfirmed for an external confirming record layer, the held-rotation reactions above, prekey.ErrReplenishmentPending, prekey.ErrEpochRollback, and a restart refused for prekey.ErrEpochFuture or a rolled-back epoch.

Directory limitations

The illustrative Directory:

  • is untrusted for authenticity;
  • stores no private keys;
  • atomically reserves a public OTK record;
  • serves the bundle and the reserved OTK record in one reply, which the record package's documentation advises against for a deployment: a requester whose bundle does not verify has spent the OTK, so a deployment's directory serves the bundle by itself first;
  • has no client authentication or rate limit, so callers can exhaust OTKs;
  • has no persistence, replication, transparency, fairness, or rollback protection.

Applications must replace it with their own distribution and trust system.

Per-member statement signatures

ExampleCluster_memberStatementSignatures gives Alice, Bob and Carol independent identity-certified statement keys. Each member verifies the other members' certificates against the identities already configured through Party.Trust; no identity carried with a message becomes a trust root. A certificate traverses its public wire encoding before installation, but this in-process example delivers it directly rather than specifying a certificate distribution protocol. A statement and its signature are then sealed inside the shared group channel. Group encryption supplies confidentiality and proves possession of the selected epoch key, while the independent statement signature attributes the opened content to one member's key. The example applies current-membership policy by checking the cluster roster and its committed epoch separately. Its signed input also binds the claimed member and the group-key epoch, so changing either outer field invalidates the signature. An operation id is scoped to one statement key. The retained operation intent therefore includes that key id, the operation id, the member, group epoch, signed business id and application statement. An exact retry uses the same key and input to recover its stored receipt; a decision for a successor key or later group epoch is a new operation, not a retry.

The signature is publicly verifiable and transferable, not restricted to cluster members. VerifyStatement is stateless. The example therefore separates repeatable cryptographic verification from an application transaction that atomically records the statement-key id and XMSS leaf, the signed business identifier and the business effect. The identifier has its own length-prefixed field in the signed input and the encrypted application frame; it is never supplied out of band at acceptance. A failed effect consumes none of them; an exact committed retry is idempotent; and signing the same business identifier at another leaf or key does not apply it twice. Production code makes those writes one durable transaction. Current membership, authorization, quorum policy, trusted time and transaction semantics also stay with the application. Removing a member stops granting that member new authority; it does not make historical signatures invalid. Live verification and commit in the example are bound to the member that opened the group message and check the cluster's committed epoch as well as that receiver's local state, so neither a different receiver nor a straggler accepts delayed evidence. Installing a successor does not by itself make earlier-generation evidence invalid; any generation cutover rule for live decisions is also application policy. A signature position prevents cryptographic replay only: signing the same business transaction at another leaf or key produces new valid evidence, so transaction deduplication and the application effect remain an atomic application responsibility. A receiver that retains a removed member's statement-key lineage refuses a new identity under that name, while a fresh receiver follows the cluster's new identity binding. Correct use of this example therefore requires globally unique, never-reused member names. A deployment that reuses names needs an explicitly authorized new membership incarnation, with rollback-protected trust and archive updates at each receiver.

Group replay state advances when the outer message opens. If the corresponding statement-key successor has not arrived yet, retain that group-authenticated plaintext and verify it after installing the successor; reopening the same group ciphertext is correctly a replay. Before statement verification, its claimed sender is not attributable to that member. A production buffer applies a small frame-size limit before retention, global byte and count limits, a bounded number of pending generations and an expiry. A per-peer quota is safe only when the transport independently authenticated that peer. Close, removal and epoch change evict ineligible entries, and no deferred value reaches a business effect before verification and the live-policy recheck.

Each statement-key generation permits 1,023 ordinary signatures before its reserved final leaf authorizes one exact successor. The example uses a separate in-memory StatementBackend for each member and exercises successor installation. Its independent public archive keeps the root certificate and every ordered, verified successor certificate, operation id, transition intent and authorization after private predecessor state and receipts are destroyed. A staged intent is separate from the authorized head, and a malformed authorization cannot advance it. That archive lets a late member verify the complete lineage against its own trusted identity binding. Its completeness and freshness still depend on rollback-protected authoritative storage. A production backend and public archive must make the contract's transactions, fences, erasure, tombstones and monotonic accepted head durable across journals, replicas, snapshots and backups. Before calling SignStatementSuccessor, the application publishes the successor and durably records the exact certificate, operation id and transition intent. It then durably adds the returned authorization. Receivers persist the new pin and evidence before acknowledging it. The predecessor remains available until every intended receiver has acknowledged that pin. With those production boundaries, every retained ordinary operation for the predecessor must also have been recovered and settled, or explicitly abandoned, before retiring that signer; retirement erases its receipts. After an authorization epoch has ended, an execute-or-replay signing call is unsafe for recovery because an earlier attempt may not have committed. The example backend therefore exposes a receipt-only lookup, and the application verifies that stored receipt against its durable operation intent without advancing signing state. The example's successful installation returns are synchronous stand-ins for receiver acknowledgements; it does not implement an acknowledgement protocol, a receipt journal or durable application replay positions. StatementSigner.Close is ordinary process shutdown: retain the verified key and backend and call RestoreStatementSigner on restart. StatementSigner.Retire is irreversible key destruction. The test teardown is named accordingly and also clears the cluster's independent recovery key. This pattern is intended for durable control decisions and transactions, not as a signature on every transport record. Statement signing is unavailable in FIPS 140-only mode, as SPEC section 20 describes.

Group-control example

Cluster, AsyncRotator, and the group-key helpers exercise pairwise AKE channels as a transport for prepare/ack/commit and recovery messages. They are useful tests of integration and failure handling, but they are not a production group protocol.

The example assumes an honest coordinator and one process. It does not provide consensus, Byzantine fault tolerance, durable decisions, signed quorum proofs, membership transparency, or cross-process rollback protection. A proposal digest alone would not stop a malicious coordinator from equivocating.

A deployment that must withstand coordinator equivocation needs a consensus log with that fault model, or a verifiable certificate of signed votes under a quorum rule whose intersections include an honest voter. Each decision binds the cluster, transition slot or decision identifier, leader term or incarnation, prior epoch, roster, and new key commitment. Voters durably record their vote before replying and follow a safe voting and leader-change protocol. Receivers durably record the decision and a rollback-protected high-water mark before accepting its effects. Fence superseded leaders and externally synchronize rotation, membership changes and operations that use that state. Counting acknowledgements alone supplies none of those guarantees.

The group layer also has deliberate cryptographic limits:

  • shared epoch keys prove possession of an epoch key, not current membership or individual sender attribution;
  • the fallback key is readable by every party that ever held the cluster secret and is suitable only for low-volume recovery signalling;
  • random-nonce budgets and epoch rotation are described but not durably enforced;
  • replay sets are in-memory and unbounded.

It also takes one side of a choice every group design has to make, and a deployment should make that choice on purpose. RekeyExcluding rotates the shared key without the members it cannot reach, and Recover brings a member that fell behind to the current epoch. Earlier epoch keys are not kept, so a member that was away cannot read what the others sent under the epochs it missed. The rule behind this is general: a returning member can read whatever is encrypted under keys the group still holds, and nothing else.

  • Keeping earlier keys for as long as messages are kept lets a returning member read its backlog, and means that a compromise during that time exposes the backlog too.
  • Refusing to rotate until every member agrees means no rotation is ever missed, so the current key reads the whole backlog. It also gives every member, and anyone who can keep one member offline, a veto over rotation: the key lives as long as the longest outage, and a member that never returns has to be removed before the group can rotate again.
  • In practice the two are combined with a deadline: rotate when all agree, remove a member that stays unreachable past a limit or when the key reaches its age or usage limit, and keep the previous key for as long as the message queue keeps messages.

None of this is in the library, which delivers a key to a member over an authenticated handshake and takes no view on who should hold it.

Main API

API Meaning
NewParty(id, dir) Create an in-memory endpoint and identity.
Party.Trust(id, identity) Configure an independently authenticated peer identity.
Party.Publish(n) Publish the bundle and add n signed hybrid OTKs.
Party.Send(id, plaintext) Strict 4DH send; fails if no OTK is available.
Party.Receive(envelope) Verify, tombstone, confirm, and open. Holds the pending handshake, so an intact retransmission opens after a damaged first record.
Party.SealTo(id, plaintext) Seal one self-contained ake.Envelope and return its wire bytes.
Party.OpenFrom(wire) Open an ake.Envelope; stateless. Content no trusted sender signed is refused with no OTK spent while each trusted sender has an uncompromised signing component. Another trusted sender with the OTK public record can sign a changed copy in its own name and spend the key. One valid randomized signature witness for the same content can consume the OTK before another. Example_envelope queues messages for a party that restarts.
Party.ReplenishIfLow(low, batch) Refill available OTK inventory.
Party.RotateSignedPreKey() Publish a new epoch and retain one grace SPK.
Party.DropPreviousSignedPreKey() Atomically retire the grace epoch.
Party.Restart() Rebuild identity and managed prekeys from backend state.
Party.Close() Scrub process-local keys and illustrative backend state; later error-returning calls except Close report ErrPartyClosed, and accessors return zero values.
EstablishConfirmedSessions(a, b, channelID) Complete and confirm an in-process handshake pair.
EstablishRecordChannels(a, b, channelID) Consume confirmed sessions into matching record channels.
RekeyRecordChannels(a, b, left, right, channelID) Run one initiator-decided record rekey: confirm, reply, activate, follow.
EstablishDriverLink(a, b, channelID) Join two parties' record.Drivers by a link that can lose records.
DriverLink.Send/StartRekey/Rebuild/Advance Data, a marked rekey handshake, a marked new-channel handshake, and the receive-and-tick loop.
NewLinkPair(a, b, channelID) Give each party a record.Link toward the other, joined by a record path and a handshake path that can lose what they carry.
LinkPair.Send/StartRekey/Restart/Advance/Status/Settled/Close Data, a rekey, a restart of one end, the receive-and-tick loop, and what each Link reports.
LinkPair.Lose, LinkPair.FetchDelay A function that loses frames and handshakes on their way, and how long each end takes to fetch the peer's bundle before it reserves a one-time prekey. Zero by default.
LinkPairReport What one LinkPair.Advance observed at each end: LinkPairReport.Delivered, LinkPairReport.Events and LinkPairReport.Hints, and, for a fetch that takes time, LinkPairReport.Repeats, the requests that found a handshake being prepared and began no second one, and LinkPairReport.Stopped, the preparations ended with no one-time prekey reserved because the Link did not want the handshake any more.
NewDelivery(link, opts) Acknowledged, in-order delivery of messages over one record.Link: once while both ends keep their Delivery, at least once when an end makes a new one.
Delivery.Send/Receive/Tick/Wake/Status/SetLink A message for the peer, a frame from the record path, the timer and when it is due, what waits and what was acknowledged, and another Link in the same process.
Directory.FetchForHandshake(id) Fetch bundle and reserve one OTK record.
Cluster.Join/Leave/Recover Illustrative group-control operations.

Run go test -race ./internal/reference from the repository root to exercise pairwise, rotation, rollback, cluster, concurrency, and failure paths.

Documentation

Overview

Package reference is an executable integration example for ake. It is not a production service, distributed store, or group protocol.

Party demonstrates the full strict-v1 lifecycle through prekey.Manager and an in-memory backend: publish a signed bundle and separate signed hybrid OTK records; require an explicitly trusted identity; initiate strict 4DH; atomically consume and tombstone the selected private OTK; confirm with the first ciphertext; replenish inventory; and rotate the signed-prekey epoch with a bounded in-flight grace key.

Example_recordChannel uses the exported synchronous record-channel helpers to carry a confirmed Session into record.Channel, demonstrate reordered delivery, replay rejection, staged rekey, and then rebuild process-lifetime channels after Party.Restart restores the managed prekey state. Real applications transport the same handshake messages themselves.

Example_driverLink does the same with record.Driver, which runs the rekey procedure for the application. DriverLink joins two parties' Drivers by an in-process link that can lose records and marks each handshake as a rekey or as a new channel; its Advance method is the loop a deployment writes around a Driver.

Delivery is acknowledged delivery over one record.Link, which a Link leaves to the application: messages passed to Send are handed to the peer's application in the order sent, across loss, duplication, reordering, cuts of the path, rekeys and the replacement of the channel. While both ends keep their Delivery, every message is handed over once. A Delivery has no stored form and lives as long as its process: when an end makes a new one, a message is handed over at least once, with duplicates only among those the other end's output counts as Unconfirmed, and what the lost Delivery had taken and not handed on is gone with it; when both ends make a new one at the same instant, no message is handed over twice, since what the lost Deliveries held is gone, and an output says anything only where a late frame of a lost Delivery is the first a new one opens. Like a Link it does no I/O and reads no clock. The application passes it the frames of the record path and the time in place of Link.Receive and Link.Tick, goes on running the handshakes and everything else of the Link itself, and makes one call on the Delivery at a time; its calls on the Link may come from other goroutines, since a Delivery takes each frame's position from Link.SealNumbered and LinkOutput.OpenedAt. Its documentation states each decision with its reason: the message numbers and the cumulative acknowledgement inside the sealed plaintext, the position each frame reports so that a sender knows how far ahead of the peer its numbering is, the acknowledgements that wait and ride on messages, and the message sealed again once its frame is more than a replay window behind. It lays out the 61-byte header of a frame field by field, states the rate (16 unacknowledged messages at a time; 112 to 113 messages a second measured on a path that loses nothing and delays by 10 to 50 ms) and outlines what a stored form would have to hold. A Delivery never rekeys and never asks for a new channel; it reports a stall, at which an application waits: a path that is cut needs nothing, and waiting through it costs no handshake. DeliveryUnacknowledged states when Link.Probe is worth its price, and the test by which an application that probes tells a channel that needs Link.Rebuild from a path that is cut. Every frame names the stream of the Delivery that sealed it, so an end whose peer made a new Delivery starts over for that one and says so in its output (PeerRestarted, with Unconfirmed, the count of its own messages that may be handed over a second time: the first that many of its unacknowledged ones, in the order sent). This package cannot be imported from outside the module, so Delivery is there to be read and ported. A port takes delivery.go and two things from outside it: readSystemRandom (random.go), with which each new Delivery draws its stream identifier from crypto/rand.Reader as the package found it when it was initialised, and Delivery's Format method with the writeName it calls (text.go), with which fmt prints a Delivery as its name alone. A port without the second prints, with fmt, the fields of a Delivery, its stream identifiers, counters and timers among them, though not its messages. Example_delivery runs two ends over a path that loses every third frame, on a channel that LinkPair, the reference for an application built on record.Link, brought up.

Further examples show the correct reaction to each error a deployer must handle: Example_duplicateDelivery, Example_oneTimeKeySpent and Example_keyMismatch for the handshake; Example_sessionExports for Session exports and bindings; Example_recordDeliveryErrors and Example_recordRekeyState for record channels; and Example_graceActive for a busy prekey manager. They illustrate the decisions, not a production policy.

Directory is deliberately untrusted for authenticity. It reserves public OTK records atomically, but has no authentication, fairness, rate limiting, durable storage, rollback protection, or multi-replica semantics. The Party backend's in-memory tombstones illustrate the OneTimePreKeyStore contract but do not survive a real process restart. Party.Restart deliberately keeps the same in-memory backend alive to stand in for durable storage, so tombstones surviving Restart show what a durable adapter must preserve, not that this backend preserves it. A real receiver must implement the compare, private-record removal, and non-expiring tombstone as one durable transaction. The illustrative backend implements prekey.Backend's atomic state machine, but has no durable reservation cutoff, crash reconciliation, replication, or rollback protection.

Cluster and the group-key helpers illustrate how pairwise ake channels might carry control messages. They are intentionally not consensus, Byzantine fault tolerance, a secure group-messaging protocol, or production recovery. Their documented trust and nonce limitations remain part of the example.

Example

Example wires the minimal two-party flow: publish a bundle, send one sealed message, receive it.

package main

import (
	"fmt"

	"edo.dev/ake/internal/reference"
)

func main() {
	dir := reference.NewDirectory()
	alice, err := reference.NewParty("alice", dir)
	if err != nil {
		fmt.Printf("create alice: %v\n", err)
		return
	}
	defer func() {
		if err := alice.Close(); err != nil {
			panic(err)
		}
	}()
	bob, err := reference.NewParty("bob", dir)
	if err != nil {
		fmt.Printf("create bob: %v\n", err)
		return
	}
	defer func() {
		if err := bob.Close(); err != nil {
			panic(err)
		}
	}()
	if err := alice.Trust("bob", bob.PublicIdentity()); err != nil {
		fmt.Printf("trust bob: %v\n", err)
		return
	}
	if err := bob.Trust("alice", alice.PublicIdentity()); err != nil {
		fmt.Printf("trust alice: %v\n", err)
		return
	}

	if err := bob.Publish(10); err != nil { // bob makes himself reachable
		fmt.Printf("publish bob: %v\n", err)
		return
	}

	env, err := alice.Send("bob", []byte("hello ake"))
	if err != nil {
		fmt.Printf("send to bob: %v\n", err)
		return
	}
	pt, err := bob.Receive(env)
	if err != nil {
		fmt.Printf("bob receive: %v\n", err)
		return
	}

	fmt.Printf("bob read: %s\n", pt)
}
Output:
bob read: hello ake
Example (Delivery)

Example_delivery runs a Delivery at each end of one record.Link over a record path that loses every third frame. Each end passes its messages to Send, and each receives the other's once and in the order they were sent, whichever frames the path dropped: both ends keep their Delivery from start to end, which is the condition for "once". The example runs on one goroutine; an application with more makes one call on a Delivery at a time, and may make its calls on the Link from any goroutine.

A LinkPair brings the channel up. From then on the example drives the two Deliveries itself, as an application does: every frame that arrives goes to Delivery.Receive, Delivery.Tick runs when Delivery.Wake says so, and what an output holds in Send goes on the path. On this path the Links ask for nothing more; an application also acts on DeliveryOutput.Link, as LinkPair does on a Link's output.

dir := NewDirectory()
alice, err := NewParty("alice", dir)
if err != nil {
	panic(err)
}
defer func() { _ = alice.Close() }()
bob, err := NewParty("bob", dir)
if err != nil {
	panic(err)
}
defer func() { _ = bob.Close() }()
if err := alice.Trust("bob", bob.PublicIdentity()); err != nil {
	panic(err)
}
if err := bob.Trust("alice", alice.PublicIdentity()); err != nil {
	panic(err)
}
if err := alice.Publish(8); err != nil {
	panic(err)
}
if err := bob.Publish(8); err != nil {
	panic(err)
}
pair, err := NewLinkPair(alice, bob, "example-delivery")
if err != nil {
	panic(err)
}
defer pair.Close()
for step := 0; !pair.Settled(); step++ {
	if step == 20 {
		panic("the pair did not settle")
	}
	pair.Advance(time.Second)
}

// One Delivery over each Link. It is the only caller of that Link's Seal
// and Receive from here on, so the LinkPair is not advanced again.
now := pair.now
names := [2]string{"alice", "bob"}
var ends [2]*Delivery
for i, end := range []*linkEnd{pair.first, pair.second} {
	if ends[i], err = NewDelivery(end.link, DeliveryOptions{}); err != nil {
		panic(err)
	}
}

// The record path. It drops every third frame it is given, in whichever
// direction, and hands over the others at the next step of the clock.
var inbox [2][][]byte
var received [2][]string
carried, lost := 0, 0
act := func(from int, out DeliveryOutput) {
	for _, message := range out.Delivered {
		received[from] = append(received[from], string(message))
	}
	for _, frame := range out.Send {
		carried++
		if carried%3 == 0 {
			lost++
			continue
		}
		inbox[1-from] = append(inbox[1-from], frame)
	}
}
send := func(from int, message string) {
	out, err := ends[from].Send(now, []byte(message))
	if err != nil {
		panic(err)
	}
	act(from, out)
}

send(0, "one")
send(0, "two")
send(1, "uno")
send(0, "three")
send(1, "dos")
send(0, "four")

// The application's loop: frames first, then the timer when it is due,
// which it reads only from a Wake that is not zero. It needs no Tick of
// its own at the start: a Delivery that no call has passed a time
// reports one that has passed. The loop ends when each end has had
// every message acknowledged.
for step := 0; ends[0].Status().Queued+ends[1].Status().Queued > 0; step++ {
	if step == 400 {
		panic("the messages were not delivered")
	}
	now = now.Add(50 * time.Millisecond)
	for i := range ends {
		frames := inbox[i]
		inbox[i] = nil
		for _, frame := range frames {
			out, err := ends[i].Receive(now, frame)
			if err != nil {
				panic(err)
			}
			act(i, out)
		}
		if wake := ends[i].Wake(); !wake.IsZero() && !wake.After(now) {
			out, err := ends[i].Tick(now)
			if err != nil {
				panic(err)
			}
			act(i, out)
		}
	}
}

fmt.Println("the path lost frames:", lost > 0)
for i, d := range ends {
	status := d.Status()
	fmt.Printf("%s received %q\n", names[i], received[i])
	fmt.Printf("%s sent %d, acknowledged %d\n", names[i], status.Sent, status.Acknowledged)
}
Output:
the path lost frames: true
alice received ["uno" "dos"]
alice sent 4, acknowledged 4
bob received ["one" "two" "three" "four"]
bob sent 2, acknowledged 2
Example (DuplicateDelivery)

Example_duplicateDelivery shows the receiver's reaction to ake.ErrAuthentication. An envelope the transport delivers twice, and one whose one-time prekey was retired with its signed-prekey epoch while it was in flight, both name a key the receiver no longer holds. The receiver cannot and need not tell these apart: it drops the envelope without releasing anything. A sender that receives no application acknowledgement sends the content again under a fresh handshake, which reserves a fresh one-time prekey.

package main

import (
	"errors"
	"fmt"

	"edo.dev/ake"
	"edo.dev/ake/internal/reference"
)

// newExamplePair returns two mutually trusting parties; bob has published
// otks one-time prekeys.
func newExamplePair(otks int) (alice, bob *reference.Party, closeBoth func()) {
	dir := reference.NewDirectory()
	alice, err := reference.NewParty("alice", dir)
	if err != nil {
		panic(err)
	}
	bob, err = reference.NewParty("bob", dir)
	if err != nil {
		panic(err)
	}
	if err := alice.Trust("bob", bob.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Trust("alice", alice.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Publish(otks); err != nil {
		panic(err)
	}
	return alice, bob, func() {
		if err := errors.Join(alice.Close(), bob.Close()); err != nil {
			panic(err)
		}
	}
}

func main() {
	alice, bob, closeBoth := newExamplePair(4)
	defer closeBoth()

	env, err := alice.Send("bob", []byte("hello"))
	if err != nil {
		panic(err)
	}
	first, err := bob.Receive(env)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(first))
	_, err = bob.Receive(env) // the transport redelivers the same envelope
	fmt.Println("duplicate:", errors.Is(err, ake.ErrAuthentication))

	late, err := alice.Send("bob", []byte("late"))
	if err != nil {
		panic(err)
	}
	if err := bob.RotateSignedPreKey(); err != nil {
		panic(err)
	}
	if err := bob.DropPreviousSignedPreKey(); err != nil {
		panic(err)
	}
	_, err = bob.Receive(late) // its key was retired with the grace epoch
	fmt.Println("retired:", errors.Is(err, ake.ErrAuthentication))

	resent, err := alice.Send("bob", []byte("late"))
	if err != nil {
		panic(err)
	}
	opened, err := bob.Receive(resent)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(opened))

}
Output:
hello
duplicate: true
retired: true
late
Example (Envelope)

Example_envelope queues two messages for a party that is not running. Each is a self-contained ake.Envelope. The party restarts, restores its prekey state, and reads both; a redelivered copy is refused.

package main

import (
	"errors"
	"fmt"

	"edo.dev/ake"
	"edo.dev/ake/internal/reference"
)

func main() {
	dir := reference.NewDirectory()
	alice, err := reference.NewParty("alice", dir)
	if err != nil {
		panic(err)
	}
	defer func() { _ = alice.Close() }()
	bob, err := reference.NewParty("bob", dir)
	if err != nil {
		panic(err)
	}
	defer func() { _ = bob.Close() }()
	if err := alice.Trust("bob", bob.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Trust("alice", alice.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Publish(2); err != nil {
		panic(err)
	}

	var queue [][]byte
	for _, text := range []string{"first", "second"} {
		wire, err := alice.SealTo("bob", []byte(text))
		if err != nil {
			panic(err)
		}
		queue = append(queue, wire)
	}
	_, err = alice.SealTo("bob", []byte("third"))
	fmt.Println("third message refused, no one-time prekey left:", err != nil)

	if err := bob.Restart(); err != nil {
		panic(err)
	}
	for _, wire := range queue {
		sender, plaintext, err := bob.OpenFrom(wire)
		if err != nil {
			panic(err)
		}
		fmt.Printf("%s: %s\n", sender, plaintext)
	}
	_, _, err = bob.OpenFrom(queue[0])
	fmt.Println("redelivered copy refused:", errors.Is(err, ake.ErrAuthentication))

}
Output:
third message refused, no one-time prekey left: true
alice: first
alice: second
redelivered copy refused: true
Example (GraceActive)

Example_graceActive shows a busy prekey manager. While the previous signed prekey is retained for in-flight handshakes, another rotation is refused with prekey.ErrGraceActive. Treat it as "retry later", not as a failure: end the grace window on its schedule with DropPreviousSignedPreKey, then rotate. An outstanding rotation or replenishment reports prekey.ErrRotationPending or prekey.ErrReplenishmentPending: finish or abort the pending value, then retry. A caller that did not keep that value gets it again from prekey.Manager.PendingRotation or prekey.Manager.PendingReplenishment.

package main

import (
	"errors"
	"fmt"

	"edo.dev/ake/internal/reference"
	"edo.dev/ake/prekey"
)

// newExamplePair returns two mutually trusting parties; bob has published
// otks one-time prekeys.
func newExamplePair(otks int) (alice, bob *reference.Party, closeBoth func()) {
	dir := reference.NewDirectory()
	alice, err := reference.NewParty("alice", dir)
	if err != nil {
		panic(err)
	}
	bob, err = reference.NewParty("bob", dir)
	if err != nil {
		panic(err)
	}
	if err := alice.Trust("bob", bob.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Trust("alice", alice.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Publish(otks); err != nil {
		panic(err)
	}
	return alice, bob, func() {
		if err := errors.Join(alice.Close(), bob.Close()); err != nil {
			panic(err)
		}
	}
}

func main() {
	_, bob, closeBoth := newExamplePair(4)
	defer closeBoth()

	if err := bob.RotateSignedPreKey(); err != nil {
		panic(err)
	}
	err := bob.RotateSignedPreKey()
	fmt.Println("rotate during grace:", errors.Is(err, prekey.ErrGraceActive))
	if err := bob.DropPreviousSignedPreKey(); err != nil {
		panic(err)
	}
	fmt.Println("rotate after grace:", bob.RotateSignedPreKey())

}
Output:
rotate during grace: true
rotate after grace: <nil>
Example (KeyMismatch)

Example_keyMismatch shows the reaction to ake.ErrKeyMismatch: refuse, and do not retry blindly. Authenticated material names a different peer or channel than the caller expects. Retrying with the same expectations fails the same way, and adopting whatever the bundle or message claims would discard exactly the binding the check enforces. Treat it as a configuration fault or an attack and correct the trust configuration out of band.

package main

import (
	"errors"
	"fmt"
	"time"

	"edo.dev/ake"
	"edo.dev/ake/internal/reference"
)

// verifiedPrekeys fetches peerID's bundle with one reserved one-time prekey and
// verifies both against the independently trusted identity, as Party.Send does.
func verifiedPrekeys(dir *reference.Directory, peerID string, trusted ake.PublicIdentity) (*ake.VerifiedBundle, *ake.VerifiedOneTimePreKey, error) {
	bundleWire, otkWire, err := dir.FetchForHandshake(peerID)
	if err != nil {
		return nil, nil, err
	}
	bundle, err := ake.UnmarshalBundle(bundleWire)
	if err != nil {
		return nil, nil, err
	}
	verified, err := bundle.Verify(ake.VerifyOptions{
		Context:          reference.SignContext,
		ExpectedPartyID:  peerID,
		ExpectedIdentity: trusted,
		Now:              time.Now(),
		MaxAge:           24 * time.Hour,
		MaxFutureSkew:    time.Minute,
	})
	if err != nil {
		return nil, nil, err
	}
	otk, err := ake.UnmarshalOneTimePreKey(otkWire)
	if err != nil {
		return nil, nil, err
	}
	verifiedOTK, err := otk.Verify(verified)
	if err != nil {
		return nil, nil, err
	}
	return verified, verifiedOTK, nil
}

func main() {
	dir := reference.NewDirectory()
	bob, err := reference.NewParty("bob", dir)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := bob.Close(); err != nil {
			panic(err)
		}
	}()
	if err := bob.Publish(2); err != nil {
		panic(err)
	}
	alice, err := ake.NewIdentity()
	if err != nil {
		panic(err)
	}
	defer alice.Zero()
	if err := bob.Trust("alice", alice.Public()); err != nil {
		panic(err)
	}

	// alice has pinned a different identity for bob than the bundle carries.
	pinned, err := ake.NewIdentity()
	if err != nil {
		panic(err)
	}
	defer pinned.Zero()
	_, _, err = verifiedPrekeys(dir, "bob", pinned.Public())
	fmt.Println("initiator refuses bundle:", errors.Is(err, ake.ErrKeyMismatch))

	// alice names a channel (AppInfo) that bob does not expect. Accept refuses
	// before consuming the one-time prekey.
	bundle, otk, err := verifiedPrekeys(dir, "bob", bob.PublicIdentity())
	if err != nil {
		panic(err)
	}
	session, msg, err := ake.Initiate(alice, bundle, otk, ake.InitiateOptions{InitiatorID: "alice", AppInfo: "another-application-v1"})
	if err != nil {
		panic(err)
	}
	defer session.Zero()
	wire, err := msg.Marshal()
	if err != nil {
		panic(err)
	}
	_, err = bob.Receive(&reference.Envelope{SenderID: "alice", RecipientID: "bob", InitialMessage: wire})
	fmt.Println("receiver refuses channel:", errors.Is(err, ake.ErrKeyMismatch))

}
Output:
initiator refuses bundle: true
receiver refuses channel: true
Example (LinkPair)

Example_linkPair runs two parties with a record.Link each: they settle on a channel, exchange data, one of them restarts, and the pair comes back without either being told what the other holds. The application's part is in LinkPair: the two paths, the handshakes the Link asks for, and the timer.

package main

import (
	"fmt"
	"time"

	"edo.dev/ake/internal/reference"
	"edo.dev/ake/record"
)

func main() {
	dir := reference.NewDirectory()
	alice, err := reference.NewParty("alice", dir)
	if err != nil {
		panic(err)
	}
	defer func() { _ = alice.Close() }()
	bob, err := reference.NewParty("bob", dir)
	if err != nil {
		panic(err)
	}
	defer func() { _ = bob.Close() }()
	if err := alice.Trust("bob", bob.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Trust("alice", alice.PublicIdentity()); err != nil {
		panic(err)
	}
	// Either party may have to start a handshake, so both publish prekeys.
	if err := alice.Publish(8); err != nil {
		panic(err)
	}
	if err := bob.Publish(8); err != nil {
		panic(err)
	}

	pair, err := reference.NewLinkPair(alice, bob, "example-link")
	if err != nil {
		panic(err)
	}
	defer pair.Close()
	// advance runs the pair until it is settled and returns what happened.
	advance := func() (events [2][]record.LinkEvent, delivered [2][][]byte) {
		for range 20 {
			report := pair.Advance(time.Second)
			for i := range 2 {
				events[i] = append(events[i], report.Events[i]...)
				delivered[i] = append(delivered[i], report.Delivered[i]...)
			}
			if pair.Settled() {
				return events, delivered
			}
		}
		panic("the pair did not settle")
	}

	events, _ := advance()
	fmt.Println("alice:", events[0], "bob:", events[1])

	if err := pair.Send(true, []byte("hello bob")); err != nil {
		panic(err)
	}
	report := pair.Advance(time.Second)
	fmt.Printf("bob received %q\n", report.Delivered[1])

	// Bob restarts. He has no channel, and Alice is told nothing.
	if err := pair.Restart(false); err != nil {
		panic(err)
	}
	fmt.Println("bob can seal:", pair.Send(false, []byte("too early")) == nil)
	events, _ = advance()
	fmt.Println("alice:", events[0], "bob:", events[1])

	if err := pair.Send(false, []byte("back again")); err != nil {
		panic(err)
	}
	report = pair.Advance(time.Second)
	fmt.Printf("alice received %q\n", report.Delivered[0])

}
Output:
alice: [up] bob: [up]
bob received ["hello bob"]
bob can seal: false
alice: [replaced] bob: [up]
alice received ["back again"]
Example (OneTimeKeySpent)

Example_oneTimeKeySpent shows the initiator's reaction to ake.ErrOneTimePreKeySpent. A verified one-time prekey authorizes exactly one Initiate, because the receiver can accept at most one handshake against it. After a timeout the tempting retry, initiating again with the same verified key, is refused. The correct retry retransmits the original initial message and first ciphertext unchanged; the receiver accepts the first copy that arrives and reports later copies as duplicates (see Example_duplicateDelivery).

package main

import (
	"errors"
	"fmt"
	"time"

	"edo.dev/ake"
	"edo.dev/ake/internal/reference"
)

// verifiedPrekeys fetches peerID's bundle with one reserved one-time prekey and
// verifies both against the independently trusted identity, as Party.Send does.
func verifiedPrekeys(dir *reference.Directory, peerID string, trusted ake.PublicIdentity) (*ake.VerifiedBundle, *ake.VerifiedOneTimePreKey, error) {
	bundleWire, otkWire, err := dir.FetchForHandshake(peerID)
	if err != nil {
		return nil, nil, err
	}
	bundle, err := ake.UnmarshalBundle(bundleWire)
	if err != nil {
		return nil, nil, err
	}
	verified, err := bundle.Verify(ake.VerifyOptions{
		Context:          reference.SignContext,
		ExpectedPartyID:  peerID,
		ExpectedIdentity: trusted,
		Now:              time.Now(),
		MaxAge:           24 * time.Hour,
		MaxFutureSkew:    time.Minute,
	})
	if err != nil {
		return nil, nil, err
	}
	otk, err := ake.UnmarshalOneTimePreKey(otkWire)
	if err != nil {
		return nil, nil, err
	}
	verifiedOTK, err := otk.Verify(verified)
	if err != nil {
		return nil, nil, err
	}
	return verified, verifiedOTK, nil
}

func main() {
	dir := reference.NewDirectory()
	bob, err := reference.NewParty("bob", dir)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := bob.Close(); err != nil {
			panic(err)
		}
	}()
	if err := bob.Publish(2); err != nil {
		panic(err)
	}
	// alice integrates ake directly rather than through Party.
	alice, err := ake.NewIdentity()
	if err != nil {
		panic(err)
	}
	defer alice.Zero()
	if err := bob.Trust("alice", alice.Public()); err != nil {
		panic(err)
	}

	bundle, otk, err := verifiedPrekeys(dir, "bob", bob.PublicIdentity())
	if err != nil {
		panic(err)
	}
	session, msg, err := ake.Initiate(alice, bundle, otk, ake.InitiateOptions{InitiatorID: "alice", AppInfo: reference.SessionInfo})
	if err != nil {
		panic(err)
	}
	defer session.Zero()
	// The reference Envelope binds both party names as associated data.
	aad, err := ake.BuildAAD([]byte("alice"), []byte("bob"))
	if err != nil {
		panic(err)
	}
	nonce, ciphertext, err := session.Seal([]byte("hello"), aad)
	if err != nil {
		panic(err)
	}
	wire, err := msg.Marshal()
	if err != nil {
		panic(err)
	}

	// No reply arrives in time.
	_, _, err = ake.Initiate(alice, bundle, otk, ake.InitiateOptions{InitiatorID: "alice", AppInfo: reference.SessionInfo})
	fmt.Println("re-initiate:", errors.Is(err, ake.ErrOneTimePreKeySpent))

	plaintext, err := bob.Receive(&reference.Envelope{
		SenderID:       "alice",
		RecipientID:    "bob",
		InitialMessage: wire,
		Nonce:          nonce,
		Ciphertext:     ciphertext,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("retransmitted:", string(plaintext))

}
Output:
re-initiate: true
retransmitted: hello
Example (RecordChannel)

Example_recordChannel demonstrates a confirmed, channel-bound handshake; multiple ordered and reordered records; replay rejection; staged rekey; and rebuilding a process-lifetime record channel after the receiver restarts.

package main

import (
	"errors"
	"fmt"

	"edo.dev/ake/internal/reference"
	"edo.dev/ake/record"
)

func main() {
	dir := reference.NewDirectory()
	alice, err := reference.NewParty("alice", dir)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := alice.Close(); err != nil {
			panic(err)
		}
	}()
	bob, err := reference.NewParty("bob", dir)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := bob.Close(); err != nil {
			panic(err)
		}
	}()
	if err := alice.Trust("bob", bob.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Trust("alice", alice.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Publish(8); err != nil {
		panic(err)
	}

	aliceRecords, bobRecords, aad, err := reference.EstablishRecordChannels(alice, bob, "channel-7")
	if err != nil {
		panic(err)
	}
	defer aliceRecords.Zero()
	defer bobRecords.Zero()
	firstRecord, err := aliceRecords.Seal([]byte("one"), aad)
	if err != nil {
		panic(err)
	}
	secondRecord, err := aliceRecords.Seal([]byte("two"), aad)
	if err != nil {
		panic(err)
	}
	second, err := bobRecords.Open(secondRecord, aad)
	if err != nil {
		panic(err)
	}
	first, err := bobRecords.Open(firstRecord, aad)
	if err != nil {
		panic(err)
	}
	_, replayErr := bobRecords.Open(secondRecord, aad)
	fmt.Println(string(second), string(first), errors.Is(replayErr, record.ErrReplay))

	replyRecord, err := bobRecords.Seal([]byte("reply"), aad)
	if err != nil {
		panic(err)
	}
	reply, err := aliceRecords.Open(replyRecord, aad)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(reply))

	epoch, err := reference.RekeyRecordChannels(alice, bob, aliceRecords, bobRecords, "channel-7")
	if err != nil {
		panic(err)
	}
	afterRekey, err := aliceRecords.Seal([]byte("new epoch"), aad)
	if err != nil {
		panic(err)
	}
	afterRekeyPlaintext, err := bobRecords.Open(afterRekey, aad)
	if err != nil {
		panic(err)
	}
	fmt.Println("rekeyed:", epoch, string(afterRekeyPlaintext))

	// Record channels are intentionally process-lifetime state. A restart
	// restores Bob's identity, managed prekeys, tombstones, and rollback floor,
	// then the peers perform a fresh authenticated handshake for new channels.
	aliceRecords.Zero()
	bobRecords.Zero()
	if err := bob.Restart(); err != nil {
		panic(err)
	}
	aliceAfterRestart, bobAfterRestart, restartAAD, err := reference.EstablishRecordChannels(alice, bob, "channel-7")
	if err != nil {
		panic(err)
	}
	defer aliceAfterRestart.Zero()
	defer bobAfterRestart.Zero()
	restartedRecord, err := aliceAfterRestart.Seal([]byte("after restart"), restartAAD)
	if err != nil {
		panic(err)
	}
	restarted, err := bobAfterRestart.Open(restartedRecord, restartAAD)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(restarted))

}
Output:
two one true
reply
rekeyed: 1 new epoch
after restart
Example (RecordDeliveryErrors)

Example_recordDeliveryErrors shows the receiver's reaction to record.Open errors caused by delivery rather than by a broken channel. None of them changes channel state, so the receiver keeps using the channel:

  • ErrTooFarAhead: more records are missing than the receiver will derive keys for ahead of authentication (the default MaxSkip is 64). The header is not authenticated, so drop the record and never act on this error alone. The direction resumes when missing records are retransmitted as they were sealed. A rekey resumes it too, but only where its confirmations travel outside the record sequence, as record.Driver sends them; carried in records, as in these examples, they would have to cross the stopped direction.
  • ErrTooOld and ErrReplay: a late or duplicate copy. Drop it silently.
  • ErrEpoch: a header naming an epoch the receiver does not hold. Headers are not authenticated, so anyone can cause this error: drop the record and never start a rekey because of it.
alice, bob, closeBoth := newExamplePair(2)
defer closeBoth()
aliceRecords, bobRecords, aad, err := reference.EstablishRecordChannels(alice, bob, "stream")
if err != nil {
	panic(err)
}
defer aliceRecords.Zero()
defer bobRecords.Zero()

sent := make([][]byte, record.DefaultReplayWindow+2)
for i := range sent {
	if sent[i], err = aliceRecords.Seal(fmt.Appendf(nil, "record %d", i), aad); err != nil {
		panic(err)
	}
}
newest := sent[len(sent)-1]
_, err = bobRecords.Open(newest, aad) // every earlier record is missing
fmt.Println("too far ahead:", errors.Is(err, record.ErrTooFarAhead))
for _, retransmitted := range sent[1:] {
	if _, err := bobRecords.Open(retransmitted, aad); err != nil {
		panic(err)
	}
}
_, err = bobRecords.Open(sent[0], aad)
fmt.Println("too old:", errors.Is(err, record.ErrTooOld))
_, err = bobRecords.Open(newest, aad)
fmt.Println("replay:", errors.Is(err, record.ErrReplay))

genuine, err := aliceRecords.Seal([]byte("still working"), aad)
if err != nil {
	panic(err)
}
forged := bytes.Clone(genuine)
forged[5] ^= 0x01 // low byte of the header's epoch word
_, err = bobRecords.Open(forged, aad)
unknownEpoch := errors.Is(err, record.ErrEpoch)
epoch, err := bobRecords.ReceiveEpoch()
if err != nil {
	panic(err)
}
fmt.Println("unknown epoch:", unknownEpoch, "receive epoch:", epoch)
opened, err := bobRecords.Open(genuine, aad)
if err != nil {
	panic(err)
}
fmt.Println(string(opened))
Output:
too far ahead: true
too old: true
replay: true
unknown epoch: true receive epoch: 0
still working
Example (RecordRekeyState)

Example_recordRekeyState shows how Channel.Epoch and Channel.ReceiveEpoch pace rekeys, and the two reactions to record.ErrRekeyState.

The channel initiator decides a rekey. ActivateRekey moves only the sending direction; a receiving direction promotes when the peer's first new-epoch record authenticates. The responder's ActivateRekey refuses with ErrRekeyState until the initiator's first new-epoch record has arrived: wait for it. Until both directions of both endpoints have promoted, StageRekey and AddRekeyCandidate refuse with ErrRekeyState and leave the offered Session unconsumed: wait for traffic in both directions, then rekey.

A responder that has answered the initiator's confirmation is committed: its AbortRekey refuses with ErrRekeyCommitted. If the initiator withdraws that attempt it sends nothing; the responder stays committed, with the current epoch working, until the confirmation of the initiator's next attempt, which carries a higher attempt number, supersedes the commitment. The initiator may abort until it activates. Once it has activated, AbortRekey refuses with ErrRekeyState. That step cannot be undone, so if the peer never follows (ReceiveEpoch stays behind Epoch past the application's timeout), rebuild the channel pair from a fresh handshake.

alice, bob, closeBoth := newExamplePair(8)
defer closeBoth()
aliceRecords, bobRecords, aad, err := reference.EstablishRecordChannels(alice, bob, "rekey")
if err != nil {
	panic(err)
}
defer func() {
	aliceRecords.Zero()
	bobRecords.Zero()
}()

// stageBoth stages one fresh handshake on both ends and exchanges alice's
// confirmation and bob's reply. A deployment sends both values through
// the still-active authenticated channel. Afterwards alice may activate
// and bob is committed. It returns the attempt number both values carry.
stageBoth := func() uint32 {
	aliceNext, bobNext, _, err := reference.EstablishConfirmedSessions(alice, bob, "rekey")
	if err != nil {
		panic(err)
	}
	confirmation, err := aliceRecords.StageRekey(aliceNext)
	if err != nil {
		panic(err)
	}
	if err := bobRecords.AddRekeyCandidate(bobNext); err != nil {
		panic(err)
	}
	reply, err := bobRecords.AcceptRekeyConfirmation(confirmation)
	if err != nil {
		panic(err)
	}
	if err := aliceRecords.VerifyRekeyConfirmation(reply); err != nil {
		panic(err)
	}
	return reply.Attempt
}

stageBoth()
if _, err := aliceRecords.ActivateRekey(); err != nil {
	panic(err)
}
fmt.Println("activated:", channelEpochs(aliceRecords))
_, err = bobRecords.ActivateRekey()
fmt.Println("responder before the first record:", errors.Is(err, record.ErrRekeyState))

early, earlyPeer, _, err := reference.EstablishConfirmedSessions(alice, bob, "rekey")
if err != nil {
	panic(err)
}
_, err = aliceRecords.StageRekey(early)
fmt.Println("early rekey:", errors.Is(err, record.ErrRekeyState))
early.Zero()
earlyPeer.Zero()

// alice's first new-epoch record lets bob follow; bob's promotes alice.
fromAlice, err := aliceRecords.Seal([]byte("epoch 1 from alice"), aad)
if err != nil {
	panic(err)
}
if _, err := bobRecords.Open(fromAlice, aad); err != nil {
	panic(err)
}
if _, err := bobRecords.ActivateRekey(); err != nil {
	panic(err)
}
fromBob, err := bobRecords.Seal([]byte("epoch 1 from bob"), aad)
if err != nil {
	panic(err)
}
if _, err := aliceRecords.Open(fromBob, aad); err != nil {
	panic(err)
}
fmt.Println("promoted:", channelEpochs(aliceRecords))
epoch, err := reference.RekeyRecordChannels(alice, bob, aliceRecords, bobRecords, "rekey")
if err != nil {
	panic(err)
}
fmt.Println("rekeyed to", epoch)

// alice gives up on the next attempt, say on a timeout, and sends nothing
// about it. bob has answered and cannot withdraw on his own: he stays
// committed to the withdrawn attempt, on the current epoch.
withdrawn := stageBoth()
err = bobRecords.AbortRekey()
fmt.Println("committed responder abort:", errors.Is(err, record.ErrRekeyCommitted))
if err := aliceRecords.AbortRekey(); err != nil {
	panic(err)
}
fmt.Println("withdrawn:", channelEpochs(bobRecords))

// alice's next attempt carries a higher attempt number, so its
// confirmation supersedes bob's commitment. She activates it, then bob
// fails before following.
next := stageBoth()
fmt.Println("superseded by a later attempt:", next > withdrawn)
if _, err := aliceRecords.ActivateRekey(); err != nil {
	panic(err)
}
err = aliceRecords.AbortRekey()
fmt.Println("abort after activation:", errors.Is(err, record.ErrRekeyState))
aliceRecords.Zero()
bobRecords.Zero()
aliceRecords, bobRecords, _, err = reference.EstablishRecordChannels(alice, bob, "rekey")
if err != nil {
	panic(err)
}
fmt.Println("rebuilt:", channelEpochs(aliceRecords))
Output:
activated: send 1, receive 0
responder before the first record: true
early rekey: true
promoted: send 1, receive 1
rekeyed to 2
committed responder abort: true
withdrawn: send 2, receive 2
superseded by a later attempt: true
abort after activation: true
rebuilt: send 0, receive 0
Example (SessionExports)

Example_sessionExports shows what a confirmed Session hands to the layer above it:

  • Export derives a key for a caller-named purpose; both ends derive the same value. The built-in record layer's label is reserved and refused.
  • Binding names the authenticated peers and channel rather than one handshake. Compare it to check that a fresh Session belongs to an existing channel.
  • ConsumeExport derives the same kind of key and closes the Session: a one-shot handoff to state that must never be initialized twice.
package main

import (
	"errors"
	"fmt"

	"edo.dev/ake"
	"edo.dev/ake/internal/reference"
)

// newExamplePair returns two mutually trusting parties; bob has published
// otks one-time prekeys.
func newExamplePair(otks int) (alice, bob *reference.Party, closeBoth func()) {
	dir := reference.NewDirectory()
	alice, err := reference.NewParty("alice", dir)
	if err != nil {
		panic(err)
	}
	bob, err = reference.NewParty("bob", dir)
	if err != nil {
		panic(err)
	}
	if err := alice.Trust("bob", bob.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Trust("alice", alice.PublicIdentity()); err != nil {
		panic(err)
	}
	if err := bob.Publish(otks); err != nil {
		panic(err)
	}
	return alice, bob, func() {
		if err := errors.Join(alice.Close(), bob.Close()); err != nil {
			panic(err)
		}
	}
}

func main() {
	alice, bob, closeBoth := newExamplePair(4)
	defer closeBoth()
	aliceSession, bobSession, _, err := reference.EstablishConfirmedSessions(alice, bob, "files")
	if err != nil {
		panic(err)
	}
	defer aliceSession.Zero()
	defer bobSession.Zero()

	aliceKey, err := aliceSession.Export("example-file-key-v1")
	if err != nil {
		panic(err)
	}
	defer clear(aliceKey[:])
	bobKey, err := bobSession.Export("example-file-key-v1")
	if err != nil {
		panic(err)
	}
	defer clear(bobKey[:])
	fmt.Println("same key on both ends:", aliceKey == bobKey)
	_, err = aliceSession.Export("ake-record-root-v1")
	fmt.Println("reserved label refused:", errors.Is(err, ake.ErrUsage))

	again, againPeer, _, err := reference.EstablishConfirmedSessions(alice, bob, "files")
	if err != nil {
		panic(err)
	}
	defer again.Zero()
	defer againPeer.Zero()
	other, otherPeer, _, err := reference.EstablishConfirmedSessions(alice, bob, "other-channel")
	if err != nil {
		panic(err)
	}
	defer other.Zero()
	defer otherPeer.Zero()
	binding, err := aliceSession.Binding()
	if err != nil {
		panic(err)
	}
	againBinding, err := again.Binding()
	if err != nil {
		panic(err)
	}
	otherBinding, err := other.Binding()
	if err != nil {
		panic(err)
	}
	fmt.Println("same channel:", binding == againBinding, "other channel:", binding == otherBinding)

	handoff, err := bobSession.ConsumeExport("example-handoff-v1")
	if err != nil {
		panic(err)
	}
	defer clear(handoff[:])
	_, _, err = bobSession.Seal([]byte("after handoff"), nil)
	fmt.Println("closed after handoff:", errors.Is(err, ake.ErrSessionClosed))

}
Output:
same key on both ends: true
reserved label refused: true
same channel: true other channel: false
closed after handoff: true

Index

Examples

Constants

View Source
const (
	DriverResendInterval = time.Second
	DriverRekeyTimeout   = 30 * time.Second
)

Timing of the Drivers a DriverLink creates.

View Source
const (
	// SignContext binds signed-prekey signatures to this deployment.
	SignContext = "ake-reference-spk-v1"
	// SessionInfo is the HKDF label for derived session secrets.
	SessionInfo = "ake-reference-session-v1"
)

Domain-separation labels for the reference deployment. A real application chooses its own unique, versioned values.

View Source
const EnvelopeInfo = "ake-reference-envelope-v1"

EnvelopeInfo is the application label of the reference's self-contained messages. It differs from SessionInfo so that a handshake made for one use is not accepted for the other.

View Source
const GroupKeyLen = 32

GroupKeyLen is the size of the shared symmetric group key.

Variables

View Source
var (
	// ErrDeliveryQueueFull is Delivery.Send's refusal when QueueLimit
	// messages are waiting to be acknowledged. Nothing was taken: offer the
	// message again once an output has delivered acknowledgements, which
	// Status shows.
	ErrDeliveryQueueFull = errors.New("reference: delivery queue is full")

	// ErrDeliveryExhausted is Delivery.Send's refusal after it has taken the
	// last message its stream can number. Nothing was taken. Keep this
	// Delivery until Status reports no queued message, then make a new one,
	// whose fresh stream starts its numbering over, and offer the refused
	// message to that one. Replacing it has the duplicate/loss boundary of
	// "A lost Delivery" in Delivery's documentation: a peer message already
	// handed over whose acknowledgement was in flight may be handed again.
	ErrDeliveryExhausted = errors.New("reference: delivery message counter exhausted")
)
View Source
var (
	// ErrIdentityUnknown reports an operation for a peer whose trusted identity
	// has not been configured explicitly.
	ErrIdentityUnknown = errors.New("reference: peer identity is not trusted")
	// ErrIdentityPinMismatch reports a peer presenting a different identity key
	// than the one configured by Trust.
	ErrIdentityPinMismatch = errors.New("reference: peer identity key does not match trusted key")
	// ErrPartyClosed reports use of a Party after Close.
	ErrPartyClosed = errors.New("reference: party is closed")
)

Functions

func EstablishConfirmedSessions

func EstablishConfirmedSessions(initiator, responder *Party, channelID string) (*ake.Session, *ake.Session, []byte, error)

EstablishConfirmedSessions performs the reference handshake synchronously between two in-process parties. The channelID is bound through AppInfo and the returned AAD. The responder opens a fixed, non-sensitive challenge and the initiator authenticates its confirmation before either Session is returned.

This helper demonstrates orchestration, not a transport. A real application sends the initial message, challenge, and confirmation over its own framed protocol while preserving the same checks and ownership transitions.

func EstablishRecordChannels

func EstablishRecordChannels(initiator, responder *Party, channelID string) (*record.Channel, *record.Channel, []byte, error)

EstablishRecordChannels confirms a fresh pair of Sessions and consumes them into matching process-lifetime record channels. The returned AAD includes channelID and should accompany every record in this illustrative channel.

func RekeyRecordChannels

func RekeyRecordChannels(initiator, responder *Party, initiatorRecords, responderRecords *record.Channel, channelID string) (uint32, error)

RekeyRecordChannels performs another confirmed handshake with the original channel initiator and runs one record rekey in which the initiator decides. Both channels stage the handshake. The initiator sends its confirmation over the existing authenticated channel; the responder checks it with AcceptRekeyConfirmation and only then sends its reply; the initiator verifies the reply, activates, and sends one fixed, non-sensitive record on the new epoch. The responder activates after that record authenticates and answers with a record of its own, so both receive directions have promoted and another rekey may begin when the helper returns.

The helper is synchronous, so where a deployment's initiator would time out, it withdraws at once: if the responder cannot stage, or either value does not match, the initiator calls AbortRekey, and both channels stay usable on their current epoch. The initiator sends nothing about the withdrawal. A responder that had already answered stays committed to the withdrawn attempt until the confirmation of the next one, which carries a higher attempt number, supersedes that commitment; a responder that had not keeps the staged handshake as a candidate until a transition completes. Either way the next call simply succeeds. Each control message carries a one-byte message type that tells the receiver how to decode it. A failure of the withdrawal itself, or any failure after the initiator has activated, zeroes both channels: that transition can no longer be rolled back.

Types

type AsyncRotator

type AsyncRotator struct {
	AckWait  time.Duration
	SlowWait time.Duration
	// contains filtered or unexported fields
}

AsyncRotator runs an explicit prepare/ack/commit rotation over a Cluster's members. Defaults: a 200ms ACK deadline and a 1s "slow" delay (comfortably past the deadline). Tests may shorten both.

func (*AsyncRotator) Rotate

func (r *AsyncRotator) Rotate() (committed bool, stragglers []string, err error)

Rotate runs one prepare/ack/commit rotation. It distinguishes the DECISION from CONVERGENCE:

  • committed reports whether a quorum was reached and the coordinator committed the new epoch. Once true, the decision is final (as in any two-phase commit); a member that later fails to receive the COMMIT does not undo it.
  • stragglers lists the members that are NOT on the committed epoch: those that never ACKed (dropped or slow) and those that ACKed but whose COMMIT delivery failed. They have not activated the newly committed epoch and still hold their prior active epoch; they MUST be fenced from confidential sends and Recover before they rejoin. A production coordinator records the decision durably and re-delivers or answers recovery queries; here the caller is expected to Recover each straggler. Recovery also requires 4DH: if a straggler's bundle was withdrawn or lists no one-time key, it must first publish a bundle with at least one one-time key. Low-watermark replenishment runs only after a successful reservation, so it cannot restore an absent or empty bundle.

stragglers is empty on an aborted rotation (nothing moved). A non-nil error can accompany committed=true when post-decision ACK cleanup or OTK replenishment fails; committed remains the authoritative decision.

type Cluster

type Cluster struct {
	// contains filtered or unexported fields
}

Cluster is an illustrative group of members that share one rotating symmetric group key — a common cluster pattern: a cluster-wide shared key distributed and re-keyed over the pairwise ake control plane, rather than a group or threshold primitive of its own.

Trust model: two tiers

Possession of the cluster secret is what defines membership. From it, two keys are derived:

  • The rotating group key is the CONFIDENTIAL channel. A committed membership change selects a fresh epoch. Traffic sealed under the committed post-leave epoch cannot be opened by the leaver, and the post-join epoch cannot open pre-join traffic. Group data travels here. A remaining straggler can still hold and send under the retired epoch, however, so production code must fence stale epochs and recover or evict stragglers before treating the change as converged.
  • The eternal initial key is the RECOVERY channel. It is derived deterministically from the cluster secret, never rotates, and is therefore held by everyone who ever joined — including a member that has since left. It carries recovery signalling ("the epoch advanced, recover now"), NOT confidential data. A former member reading or forging fallback traffic is expected and harmless, because the fallback carries nothing secret and never carries the current group key.

This is why revoking a member is a two-step idea. Leave makes a new group epoch canonical; confidential traffic sealed under that epoch excludes the departed member. It does NOT make retired-epoch traffic confidential from that member: an unfenced straggler may still send with the old key they share. Nor does it revoke the departed member's possession of the cluster secret (and thus the eternal initial key). Production code fences old epochs and repairs stragglers before declaring convergence. Truly retiring the trust root requires rotating the cluster secret itself and re-deriving the initial key for the remaining members — a heavier operation an application performs on compromise, not on every routine leave.

Membership operations

  • Scale-up (Join): a new member publishes its bundle and meshes, then the group key rotates to a fresh epoch that includes it, so it never receives the pre-join epoch (backward secrecy).
  • Scale-down (Leave): the member's bundle is withdrawn after a quorum commits a new group epoch. New-epoch traffic excludes the departed member; any remaining member still on the retired epoch is a straggler that must be fenced and recovered.

Rotation uses a prepare/commit protocol (see rekey): it decides only on a quorum, and no candidate becomes active before that decision. Decision is not convergence: a committed rotation can leave unreachable members on the prior epoch. The coordinator (leader) mints and distributes keys; if it leaves, the lexicographically-first remaining member takes over — a deterministic stand-in for real leader election.

A member that missed a rotation (a transient partition) recovers the current group key from the coordinator over authenticated pairwise ake — see Recover — not over the eternal key. This in-memory illustration trusts the coordinator's current key as canonical; production recovery validates an ordered decision log and a persistent epoch high-water mark.

Not safe for concurrent use; illustrative, not a production API.

Example (MemberStatementSignatures)
ctx := context.Background()
cluster, members, err := newThreeMemberStatementCluster(ctx)
if err != nil {
	panic(err)
}
defer func() {
	if err := destroyStatementClusterForTest(ctx, cluster, members); err != nil {
		panic(err)
	}
}()

for senderNumber, sender := range members {
	groupEpoch := sender.party.GroupKeyID()
	businessID := fmt.Sprintf("transaction-%d", senderNumber+1)
	statement := []byte(fmt.Sprintf(
		"cluster=example-cluster-7;epoch=%s;claimed-sender=mallory;action=approve;transaction=%d",
		groupEpoch, senderNumber+1,
	))
	message, err := sender.sealStatement(ctx, clusterStatementOperation(1), sender.signer.Key().ID(), groupEpoch, businessID, statement)
	if err != nil {
		panic(err)
	}
	for _, receiver := range members {
		if receiver == sender {
			continue
		}
		opened, err := receiver.openStatement(message)
		if err != nil {
			panic(err)
		}
		verified, err := receiver.verifyStatement(opened)
		if err != nil {
			panic(err)
		}
		if _, err := receiver.commitStatement(verified); err != nil {
			panic(err)
		}
		fmt.Printf("%s verified %s at index %d\n", receiver.party.ID, verified.Sender(), verified.Index())
	}
}
Output:
bob verified alice at index 0
carol verified alice at index 0
alice verified bob at index 0
carol verified bob at index 0
alice verified carol at index 0
bob verified carol at index 0

func NewCluster

func NewCluster() (*Cluster, error)

NewCluster returns an empty cluster over a fresh directory, with a fresh random cluster secret from which every member derives the eternal initial recovery key. It reports an entropy or derivation failure as an error.

func (*Cluster) Directory

func (c *Cluster) Directory() *Directory

Directory exposes the shared bundle directory (for inspection/tests).

func (*Cluster) Format

func (c *Cluster) Format(f fmt.State, _ rune)

Format writes "Cluster(…)" for every verb, %s, %x, %q and %#v included, and nothing of the Cluster's state: not its initial key, nor anything of its members. A nil Cluster prints as "<nil>".

func (*Cluster) Join

func (c *Cluster) Join(id string) (*Party, error)

Join adds a member (scale-up). The first member becomes coordinator and mints the initial group key. Every later join rotates the group key to a fresh epoch that includes the newcomer, so the newcomer only ever holds the post-join epoch and cannot decrypt group traffic sealed before it joined (backward secrecy across joins). The newcomer also derives the eternal initial key — the trust-root recovery channel, which is not confidential across membership changes (see the Cluster docs).

func (*Cluster) Leave

func (c *Cluster) Leave(id string) error

Leave removes a member (scale-down). Membership removal and the group-key rotation share one in-memory decision: the group key is first proposed to the REMAINING members, and the member (and its bundle and, if applicable, the coordinator role) is removed only if a quorum commits that rotation. If the rotation cannot reach a quorum of the remaining members, nothing changes and Leave returns an error — the member stays in the cluster on the current key, so the caller can retry, rather than being removed from the roster while still holding a live key.

A successful decision is not full convergence. A remaining member whose PREPARE failed retains the retired epoch that the leaver also holds. Only traffic sealed under the committed new epoch excludes the leaver; production code must identify and fence such stragglers until they recover.

func (*Cluster) Member

func (c *Cluster) Member(id string) (*Party, bool)

Member returns a member by id.

func (*Cluster) Members

func (c *Cluster) Members() []string

Members returns the current member ids, sorted.

func (*Cluster) NewAsyncRotator

func (c *Cluster) NewAsyncRotator() *AsyncRotator

NewAsyncRotator returns a rotator over the cluster with default timings.

func (*Cluster) Recover

func (c *Cluster) Recover(id string) error

Recover brings a member that fell behind (missed a rotation) to the epoch held by the coordinator, over a pairwise ake session. This illustrative method trusts the in-memory coordinator as canonical and performs no freshness, monotonicity, or rollback check. Production recovery must derive the canonical epoch from an ordered durable decision log and never accept a decision older than the member's persistent log-position high-water mark. Recovery requires 4DH, so the member must first publish a bundle containing at least one one-time key if its bundle was withdrawn or exhausted. The normal low-watermark replenishment follows a successful reservation and therefore cannot repair an absent or empty bundle.

func (*Cluster) RekeyExcluding

func (c *Cluster) RekeyExcluding(unreachable ...string) error

RekeyExcluding rotates the group key while treating the named members as unreachable — an illustrative partition. The excluded members keep their old epoch and must Recover to catch up. Naming the coordinator has no effect: the coordinator always stages its own candidate and counts toward quorum.

type Delivery

type Delivery struct {
	// contains filtered or unexported fields
}

Delivery gives the two ends of one record.Link what the Link does not: acknowledged delivery of messages in the order sent, across loss, duplication, reordering, cuts of the path, rekeys and the replacement of the channel. How often a message is handed over depends on whether the ends keep their Deliveries, and a Delivery lives as long as its process:

  • While both ends keep their Delivery, every message passed to Send is handed to the peer's application once, in the order sent.
  • When one end makes a new Delivery, as every restart of its process does, a message of the other end is handed over at least once, in order. The ones handed over twice are among those the other end's output counts as Unconfirmed, and what the lost Delivery had taken and not handed on is gone with it.
  • When both ends make a new one at the same instant, what the two lost Deliveries had taken and not handed on is gone, and no message is handed over twice: a new Delivery takes messages only from frames sealed for its own stream, which no Delivery that was gone before it started has sealed. Measured: none in 300 such runs. Neither output says anything, except where the first frame a new Delivery opens is a late one of the peer's lost Delivery, sealed for no stream: then the peer's new one is reported as PeerRestarted there, as described under "A lost Delivery".
  • When the second end makes its new one a moment after the first, each loss has an end that kept its Delivery through it, and the case of one end applies to each. Where the second loss comes before the end that kept its Delivery opened a frame of the first's new one, neither end is told anything, as for losses at the same instant. Measured on a path that loses a tenth of the frames, duplicates three tenths and delays them by 5 to 600 ms, with ten messages a second each way throughout: 5 seconds of traffic, then one end made its new Delivery and the other made its own 0.1 to 3 seconds later in steps of 0.1 s, then 10 seconds more of traffic; either end first, half the runs with a new Link at each loss and half over the Link in use, 120 runs. Up to 14 messages were handed over twice in a run, every one of them among those an output of its sender counted as Unconfirmed. The runs draw from one set of seeds; other seeds give other counts, higher ones as well.

"A restart" and "A lost Delivery" state these in full.

It is the acknowledged delivery that "Operating a Link" in the record package's documentation leaves to the application, written out because the limits it has to respect are easy to get wrong: a layer that respects them less carefully stops delivering with the Link up and nothing reporting it.

Like a Link it does no I/O, starts no goroutine and reads no clock. The application passes every frame of the record path to Receive in place of Link.Receive, calls Tick in place of Link.Tick whenever the time Wake reports has come, and puts what each output holds in Send on the record path. After a pause in which frames queued up, of its own process or of its reading of the path, it passes all of them to Receive before it calls Tick, which is the Link's rule too (SPEC section 13, rule 15).

The times passed to its calls are the ones passed to the Link, and they must never go backwards, which is the Link's rule too: time.Now() as it is, with its monotonic reading. A Delivery keeps the time at which each of its waits ends and compares it with the time of the call, as a Link does. With times set back, a wait that was running ends later by as much as they were set back: a frame waiting to be sent again, an acknowledgement that is due, the report of a stall. A wait that begins afterwards ends when it should, and a frame the peer reports a position past is sent again whatever its wait. So what a step back costs depends on what was waiting when it came. Measured with one end's times set back by ten minutes and that end passed 3,000 messages in the next five: with nothing waiting at the step, its peer was handed all of them; with the step in the middle of traffic both ways, over twenty runs on each path, it was handed all of them in every run on a path that loses nothing, and in all but three and all but two, which lacked up to four messages, on paths that lose a twentieth and a tenth (TestDeliveryTimesSetBackLengthenTheWaitsThatWereRunning, TestDeliveryTimesSetBackDoNotHoldAFrameThePeerReportsAPositionPast, TestDeliveryTimesSetBackWithNothingWaitingDelayNothing; the runs in traffic are measured, and no test repeats them).

Tick is the one call that reports a stall, and a Tick that finds the report more than ResendInterval overdue makes none. Wake had reported that time, so the application did not run its timers when it came: its process was stopped or busy, and the acknowledgements that end the stall may wait in its queue. The report is put off by sixteen ResendIntervals from that Tick, 4 seconds with the defaults, and by StallAfter where that is less. Sixteen intervals are the longest a frame waits before it is sent again, so every frame that waits goes out once more within them. An acknowledgement read in that time starts StallAfter over. Without one, a Tick that comes no more than ResendInterval after the end of that time reports, and a later one puts the report off again: the process stopped a second time, or is as busy as it was. The times a report is put off by add up to StallAfter at the most, and the Tick that finds it due after that makes it, however late that Tick is itself (TestDeliveryReportsAStallFromTickAlone, TestDeliveryPutsAnOverdueReportOffWhileItsTicksAreLate).

So how far apart the reports of a lasting stall are depends on the application's Ticks. Called when Wake says so, and up to ResendInterval after that, Tick reports once every StallAfter. An application whose Ticks are later than that is told of every stall all the same, and less often: two reports are StallAfter apart at the least, and twice StallAfter and the time its Ticks between them were late at the most. Measured through a cut of an hour, with each Tick the same time after the time Wake reported: 120 reports with Ticks on time, 65 with Ticks 251 ms late, 34 with 5 s and 11 with 31 s (TestDeliveryReportsEveryStallToAnApplicationWhoseTicksAreLate).

Without the putting off, the order decides whether an application that tests its channel at every report (DeliveryUnacknowledged) replaces a channel that works. Measured over the 36 schedules of TestDeliveryReportsNoStallForAcknowledgementsThatQueuedUp, in which the peer's process stops, this end reports and probes, its own process stops for longer than StallAfter and resumes with the peer's acknowledgements queued, with a Tick that reported whenever StallAfter had passed: the whole queue passed before Tick, no report and no Rebuild; Tick before the first queued frame, a report in all 36 and no Rebuild, the Link probing or seeking; Tick after one queued frame, a report and a Rebuild in 23; after two frames in 16, after three in 11, after five in 7, after ten in 1, and after twenty or more in none. With the report put off, no order of these makes a report or a Rebuild in any of the schedules, which the test holds. Neither does a process that stops again for 20 seconds after that Tick, with the rest of its queue unread, and calls Tick before it reads on (TestDeliveryReportsNoStallWhenItsProcessStopsAgainWithItsQueueUnread): that second Tick finds the report overdue again and puts it off again, and the acknowledgements in the rest of the queue are read before it is due.

What is put off is the report of the Delivery, and nothing of the Link. The same Tick runs the Link's timers, and the Link allows a queue one of its own resend intervals where the deadline of a probe or a confirmation is more than RekeyTimeout past, and none where it is less (SPEC section 13, rule 15): an application that calls Tick first and passes its queue later than that has a Link that probes, seeks or replaces a channel that works, with no report from its Delivery. Measured over the same schedules with the Tick before the first queued frame and the queue 1.1 seconds later: the pair ended on another channel in 35 of the 36, against 14 with the whole queue passed before Tick. The Delivery is silent through it and the Link is not: in each of those 35 the Link's events of the resume, LinkStalled and LinkReplaced, are in DeliveryOutput.Link.Events, which is where an application learns of it. So the rule above stands for a Delivery as for its Link: the whole queue first, then Tick.

One case of the report itself is left to the order: a queue that the application is reading when the report comes due, or no more than ResendInterval after that, as when its pause ended just before that time, or a second stop ended at the time the report was put off to. A Tick among the queued frames is on time then, and reports. An application that passes all of its queue before it calls Tick has no such case.

Everything else of the Link stays the application's: it acts on DeliveryOutput.Link, runs the handshakes, and calls Probe, StartRekey or Rebuild on the Link directly. A Delivery uses the Link's exported methods only, and reads Status after every call, so what such a direct call changed is seen at the next call; Wake reports a time that has passed when there is something to see. The Delivery must be the only caller of the Link's Receive, since it reads every record that opens.

A Delivery is not safe for concurrent use: the application makes one call on it at a time, of Send, Receive, Tick, Wake, Status and SetLink, and holds a mutex of its own over them where several goroutines call. That is all it serialises. The calls it makes on the Link beside the Delivery, Probe, ReceiveHint, CannotInitiate, ResetBackoff, StartRekey, Rebuild, the handshake calls and a Seal of its own, may come from other goroutines at any moment, during a call of the Delivery included: the Link is safe for concurrent use, and a Delivery takes the position of each frame it seals from the call that sealed it (Link.SealNumbered) and that of each frame it opens from the Link's output (LinkOutput.OpenedAt), never from a status read before. A position names the channel the record is on (RecordPosition.Tag) and its epoch, and the Delivery compares it only with the positions of that channel and epoch. Of the calls another goroutine may make while a call of the Delivery runs, these take a sequence number of the channel: Seal or SealNumbered, for a record of the application's, and Probe or ReceiveHint, whose echo is a record, as is that of OfferHandshake or AcceptHandshake when it refuses a handshake for its options (LinkOptionsMismatch) and tests the channel as a hint does. Such a record takes a number and nothing else: the Delivery counts it as it counts the Link's own records, and every frame keeps the position of its record (TestDeliveryDeliversWithRecordsSealedBesideItFromAnotherGoroutine). No other call takes one: SealPurpose seals with a handshake's Session, outside the channel's numbering, StartRekey sends the rekey's confirmation as a control frame, which is not sealed, CannotInitiate and ResetBackoff seal nothing, and the other records the Link seals of itself on the channel, the opener of a new epoch among them, are sealed within Receive and Tick. A channel or an epoch that comes between the status a call of the Delivery read and a frame it seals or opens is told by the frame's position: a frame sealed on another channel or in another epoch is not sent, the accounting starts over in the numbering the position names, and the same call seals the waiting messages again in that numbering; and a frame that opened on another channel moves no position. Any other change that a call on the Link makes, the Delivery sees at its next call, as above.

The decisions, and their reasons

Messages have their own numbers, from 1, and the acknowledgement is cumulative: "everything through n". Both travel inside the sealed plaintext, in a header of 61 bytes. A record's sequence number cannot serve: sealing a message again gives it another one, and a new channel or epoch starts from zero. The receiver delivers by message number alone, so a message that was sealed twice is delivered once.

A frame's own epoch and sequence number are those of its record: the sender learns them from Link.SealNumbered and the receiver from LinkOutput.OpenedAt, and the record's header carries them, authenticated by the Link. The receiver sends back its position: one more than the sequence number of the frame of the Delivery's that it opened latest, which is the least the number it expects next can be. NextSequence less the position the peer reported is the distance: how many numbers past the one the peer expects next the next record sealed would be. The true figure is never more than the distance, and it can be less. The Link seals records of its own on the same numbering, the echoes of a probe and the answers to the peer's, and a Delivery is not told which of them the peer opened: every one sealed after the last frame the peer reported counts as if it were lost. The peer refuses a record that is more than MaxSkip numbers past the one it expects next, the one after the highest it opened (SPEC section 10), so a record sealed at a distance of MaxSkip would still open. A Delivery stops one short of that, at a distance of MaxSkip less one, and the distance decides what may be sealed:

  • at most MaxSkip/4 messages are sealed and unacknowledged at once, and none is sealed while the distance is 3/4 of MaxSkip or more. The Link keeps half of MaxSkip for echoes nobody answered, so a quarter of messages sealed into a cut path still leaves every frame openable when the path returns;
  • an acknowledgement is sealed while the distance is under 7/8 of MaxSkip, and one that answers a frame which opened for the first time while it is under MaxSkip: that frame told the peer's position, the answer tells ours, and this exchange is what brings both distances down again;
  • a Delivery with nothing sealed and unacknowledged asks for the peer's position when the distance is half of MaxSkip or more: probes that pass on an idle channel raise it with every echo and every answer, and nothing else would bring it down before it stops the next message. Asking is sealing one acknowledgement marked to be answered, under 7/8 of MaxSkip like any other, and sending it again as the same bytes until the peer has reported it: it goes out five times, the wait doubling, and then again whenever a record of the peer's opens. A last frame the peer has not reported and that gets an answer by itself, a message or a marked frame, is sent again in place of a new one. Into a path that carries nothing asking seals one record and no more;
  • a Delivery counts from zero in a numbering it did not see begin: the records sealed before it came to the Link, a lost Delivery's and the Link's own, count as if the peer had opened none of them, and it cannot know. Where those records alone put the distance past the limit of an acknowledgement, due or asking, because the peer has reported no position after them and the records sealed since are under that limit by themselves, the acknowledgement is sealed all the same: twice in one numbering, and no more. Each is marked to be answered, and the answer reports the peer's position, from which the distance is then counted. No message is sealed this way;
  • past these limits nothing is sealed. The last frame sealed is sent again as the same bytes, which uses no number: opened for the first time it moves the peer forward.

The fractions of MaxSkip are whole numbers of records, each taken from MaxSkip divided by 4, by 8 or by 2 without the remainder: a quarter is MaxSkip/4, three quarters three times that, an eighth MaxSkip/8, seven eighths seven times that, and half MaxSkip/2. With the default of 64 they are 16, 48, 8, 56 and 32, and with a MaxSkip of 63 they are 15, 45, 7, 49 and 31 (TestDeliveryCountsItsFractionsOfMaxSkipWithoutTheRemainder).

A frame that is not acknowledged when its wait ends is sent again as the same bytes, which costs no sequence number, unless NextSequence has left it more than the replay window behind. Such a frame may be refused as too old for good, whatever is done, so the message is sealed again under a new number. Sending old bytes forever is the stall this rule removes.

How long a frame waits follows the time acknowledgements take, as the wait of a transport does. The time is measured from the messages that went out once: for each record of the peer's that acknowledges such messages and no other, one measurement, the time since the last of them went out, which waited least for the record. A message that went out twice, by its own wait or as the last frame sealed sent again, measures nothing, because the acknowledgement may be of either sending, and neither do the messages acknowledged with it, which waited at the peer for it (TestDeliveryLastFrameSentAgainCountsASending, TestDeliveryMeasuresOneRecordOnce). A smoothed time and a smoothed deviation are kept as RFC 6298 keeps them: the time moves an eighth of the way to each measurement, and the deviation a quarter of the way to the distance of the measurement from the time, so that one acknowledgement out of line moves the wait little and a lasting change is followed within some tens of them. The first measurement is the time, and an eighth of it the deviation, where a transport takes half: the first measurement comes at the start and after a silence, when the frames that wait are those lost on a path that has just returned, and the doubling below covers a first wait that is short. The first wait of a frame is the time plus four times the deviation, which leaves all but the slowest acknowledgements of a steady peer inside it, and ResendInterval where that is less or nothing has been measured. The frame's next waits are the first doubled once for each time it went out, or as often as the first waits are doubled where that is more, and no wait is longer than sixteen ResendIntervals, the first included (TestDeliveryFirstWaitFollowsTheTimeAcknowledgementsTake).

The measured wait is for a peer that is there and slow. An application that reads its frames late acknowledges late, and a path can grow slower. A wait shorter than that sends every frame a second time, the second copies are more for the peer to read, and its queue grows with what it is sent, with nothing to report it, since acknowledgements go on arriving. And while every frame goes out twice no acknowledgement is measured. So the first waits double as well, up to sixteen intervals, each time the first wait of a frame, or any wait of the first unacknowledged one, ends with a record of the peer's opened since the frame went out, until an acknowledgement is measured or the peer reports a position past the first unacknowledged frame's last sending. Only a wait that was set at the doubling in force counts, so the frames of a burst, whose waits end together, double the first waits once and not once each (TestDeliveryFirstWaitsOfABurstDoubleOnce). A wait that ends with nothing heard doubles nothing: through a cut every frame keeps to its own waits (TestDeliveryFirstWaitsDoubleWhileThePeerIsHeardAndAcknowledgesLate). With acknowledgements that come 0.3 to 1.5 seconds later than the path takes, from one moment on, under ten messages a second each way, the first waits pass the time they take within ten seconds, and over the minute after that an end sends 1.00 to 1.03 frames for each message handed to its peer (TestDeliveryFirstWaitFollowsAnAcknowledgementTimeThatGrows, which holds it to 1.1).

Following the measured time gains and costs, measured on the same three sets of seeds against first waits of ResendInterval whatever was measured, with no doubling of them. It gains where acknowledgements are slow: in the runs above, 1.00 to 1.03 frames a message against 2.00 to 3.03; and a reader of twice the messages a second on a path of 5 to 20 ms that loses nothing has its queue back after a stop in every run of the grid below, against 0 or 1 of the 18 runs of each set. It costs where frames are lost, since a frame lost waits the measured time and not ResendInterval: the first message after a cut came within 1.1 to 2.1 seconds to ends that waited against 0.7 to 0.8 (DeliveryUnacknowledged), one end sending as fast as it can carried 28 to 30 messages a second against 31 to 33 on a path that loses a tenth, and 16 to 18 against 20 to 21 on one that loses a fifth, and the backlog of an hour's cut drained in 20 m 22 s to 20 m 38 s against 18 m 37 s to 18 m 50 s, and in 34 m 50 s to 35 m 23 s against 28 m 46 s to 29 m 11 s, on those two paths (DeliveryOptions).

Two things end the wait of a frame sooner and start its waits over:

  • the peer reports a position past the frame and has not acknowledged its message. It opened a frame sealed later, so this one was lost or overtaken on the path, and its wait ends one ResendInterval after it went out: that long an overtaken frame is left to arrive. From then on the frame waits by ResendInterval, doubling, whatever was measured: it is missing at the peer, and the time the peer takes to acknowledge what it has says nothing of when to send it again. For a frame behind the first unacknowledged one that is done once: its message is not acknowledged before the ones ahead of it, whether the peer holds it or not, so a later position says nothing new of it. The first unacknowledged frame is missing for as long as its message is not acknowledged, and is sent again for every position past the numbering as it stood when it was last sent for one, an interval after its last sending at the earliest. The frame the position is one past is the one the peer opened, and is not sent for it (TestDeliveryPositionPastAFrameEndsItsWaitAfterOneInterval);
  • a record of the peer's opens after sixteen intervals and more in which none opened. The waits grew through a cut, or through the peer's absence, and say nothing of the peer that is back: every frame that has waited an interval goes out, and what was measured before the silence is dropped, so that the first waits start from ResendInterval (TestDeliveryRecordAfterSixteenSilentIntervalsSendsAWaitingFrameAtOnce).

A record of the peer's that opens sooner after another starts no wait over: were every waiting frame sent again for each record that opens, an end whose peer reads slowly would send its sixteen frames again for every record the peer sends.

The one interval an overtaken frame is left to arrive has a price on a path that reorders by more than that: a frame overtaken by more is sent again, and arrives twice. Measured over two minutes of ten messages a second each way on a path that loses nothing and delays each frame by 10 ms and a part, drawn at random, of a spread, the lowest and the highest over eight seeds: with the default ResendInterval an end sent 1.08 to 1.11 frames for each message its peer was handed with a spread of 240 ms, 1.35 to 1.45 with 500 ms, 2.20 to 2.39 with 1 s and 4.68 to 5.24 with 2 s; with a ResendInterval of 1 s, 1.00 up to a spread of 500 ms, 1.49 to 1.57 with 1 s and 3.18 to 3.41 with 2 s. Other seeds can give figures outside these ranges. Every message was handed over once and in order. Leaving such a frame four times the measured deviation where that is longer lowered the price little: over the first two of those seeds, 2.04 to 2.35 and 4.40 to 5.13 frames a message with spreads of 1 and 2 s, against 2.29 to 2.32 and 4.75 to 5.12; and it cost elsewhere: a frame that was lost and one that was overtaken look the same, so the lost frames waited longer too, and on a path that loses a fifth and delays by 10 to 400 ms one end sending as fast as it can carried 15 messages a second, below the figures stated under DeliveryOptions. An application on a path that reorders by more than ResendInterval raises ResendInterval.

What that comes to for a slow reader: its queue drains when it takes more frames a second than it is sent, and it is sent one frame for each message, an acknowledgement by itself where no message of the other direction carries one, at most one for each AckDelay, and the frames that go out again. A reader that takes no more than the messages offered to it never drains, whatever a sender does. Measured over a grid of readers of 0.8 to 5 times the messages a second, 10, 25 and 50 messages a second each way, one end reading slowly and both, the reader's process stopped once for 2, 20 and 90 seconds, on three paths, 378 runs in each of three sets of seeds. Two things held in every run, and the test holds them: on a path of 5 to 20 ms that loses nothing, every reader of twice the messages a second and more had its queue back a quarter of an hour after the stop, with no stall reported; and on every path, no reader of the messages a second or fewer had. Nothing else is guaranteed, and what the runs measured depends on the path and the rate. On the same path losing a tenth, where the frames lost and the frames sent for a position go out again, readers of four times the messages and more had their queue back in every run at 10 and 25 messages a second, and in 0 to 2 of 6 at 50, five times included; readers of twice the messages in none. On a path of 100 to 200 ms that loses nothing, readers of twice the messages had it back in every run at 10 messages a second, in 3 or 4 of 6 at 25, and in none at 50 at any multiple: sixteen messages unacknowledged at once carry fewer than 50 a second over that path, and the end that offers them builds a queue of its own (TestDeliveryQueueOfASlowReaderDrainsWhenItReadsTwiceTheMessages, and TestDeliveryQueueOfASlowReaderDrainsAfterItsPause for one reader of four times the messages).

The price of sending the first unacknowledged frame for every later position is paid to a party on the path that lets everything through but that frame: it draws the frame once for each ResendInterval, and no more. Measured over five minutes of ten messages a second each way, one run in each of three sets of seeds: the frame went out 1,210 to 1,213 times, and the end's Delivery sent 5,584 to 5,641 frames where the traffic by itself takes 3,000 (TestDeliveryFrameThatNeverArrivesIsSentForPositionsOnceAnInterval, which holds the end to one sending an interval and to 6,000 frames). What it gains is on a path that loses most of what it carries, where the first frame is lost several times in a row and each of its waits is double the one before (DeliveryUnacknowledged has the figures).

Acknowledgements wait AckDelay and ride on any message sealed meanwhile; there is never one per message, since each uses a sequence number and they alone can carry the numbering past a frame that was lost.

A frame the channel in use refuses as a replay or as too old may mean that its sender did not get the last acknowledgement, and it is answered. The refusal comes from the frame's tag and header, which nothing authenticates: anyone who can put a frame on the path can cause it, as often as it likes. So the answer costs a sequence number only when it has to. If the peer has reported the last frame sealed, it has what there is to say and nothing is sent. If it has not, and that frame says what an acknowledgement sealed at that moment would say, the frame is sent again as the same bytes. Only when that frame is out of date, or the numbering has left it the replay window behind, or there is none, is one acknowledgement sealed, while the distance is under 7/8 of MaxSkip, and at most MaxSkip/8 of these until the count starts over. Past either limit the answer is the last frame again for as long as it can open, out of date as it is: that uses no number, and what the frame lacks is a later position and no acknowledgement, since the acknowledgement of a message handed over is due by itself AckDelay later. Refusals are answered once per ResendInterval at the most, each wait double the one before up to sixteen intervals.

The waits and the count of sealed answers start over for one thing only: a frame of a Delivery of the peer's, sealed for this stream, that opens for the first time and moves a message: it acknowledges one, brings one that is new, or moves the first message expected. The peer's application is sending then, and what its Delivery sends again is to be answered without the waits that refused frames built up before. Nothing else starts them over. A record of the Link's own that opens, the echo of a probe or its answer, says nothing of the peer's Delivery, and a frame that opened before is refused and never gets that far. A frame that moves a position and nothing else, the one this end sends back or the one the peer reports, starts nothing over either, because the answer to a refused frame is such a frame. Two ends that are handed refused frames at the same moment seal answers that cross on the path; each answer moves both positions where it opens and leaves the last frame there out of date and unreported; and were a position to start the count over, every exchange would draw one more record from both ends, for as long as refused frames arrive, which costs their sender nothing.

So refused frames draw MaxSkip/8 sealed answers from an end and no more until a message moves, however many arrive, at one end or at both, and whatever the Links exchange meanwhile, and the answers settle at one frame per sixteen intervals, four seconds with the default. The frames meant are those the channel in use refuses as a replay or as too old, which carry its tag. For them, the Delivery of an idle end seals at most MaxSkip/8+2 records more than it seals with no refused frame, ten with the defaults: the sealed answers, one record that asks for the peer's position because the answers used numbers, and one answer to the peer's. Measured over an idle hour with refused frames at both ends at the same instant, at one end, and at the two in turn, from one a second to a thousand a second, with and without probing: at most 8 sequence numbers more than in the same hour with none (TestDeliveryRefusedFramesAtBothEnds, which holds each end to the ten). Measured over an idle hour in which both applications probed after ten seconds of silence and 35,918 refused frames arrived at random moments: 890 frames from the end that sent most, one per 4.04 seconds, of which its Delivery sealed 15, one more than in the same hour with none (TestDeliveryRefusedFramesWhileProbesPass, which holds each end to the ten records and to one frame per sixteen intervals).

The ten are a bound on the Delivery's records for such frames. They are no bound on the sequence numbers an idle pair uses, because the Link seals records of its own whenever it probes, and a party on the path can make it probe: with frames under a tag no channel has, which anyone can make, and by holding genuine frames back so that every echo is sent again. Those records are the Link's, and SPEC section 13 states their limit under "Limits". What a Delivery adds is its exchange of positions: the Link's records raise the distance, and from half of MaxSkip the Delivery asks for the peer's position with one record and the peer answers with one. Measured per end over an idle hour: with frames under an unknown tag at one a second, 258 to 259 sequence numbers, 240 of them the Link's records and 18 to 19 the Delivery's; with every genuine frame held 3.5 seconds as well, 1,832, of them 1,680 and 152; held 7.2 seconds, 3,907, of them 3,601 and 306; and with no such frame, a hold of 7.2 seconds and applications that probe after ten seconds of silence, 2,459 to 2,467, of them 2,301 to 2,309 and 158. Where two figures are given, one end measured the lower and the other the higher. That is one record of the Delivery's for every 11 to 15 of the Link's, and the pair delivered a message each way afterwards on the channel it had (TestDeliveryIdleUnderProbesDrawnByAParty, which holds each end to these figures and each Delivery to one record for every MaxSkip/8 of its Link's and the ten).

On a new channel (LinkUp, LinkReplaced) and on a new sending epoch (a rekey completing, which has no event: LinkStatus.Epoch is compared after every call) the numbering starts over, so the distance is taken from zero and every unacknowledged message is sealed again. Without a channel the messages wait.

Memory is bounded: QueueLimit messages wait at the sender, and the receiver holds at most MaxSkip/4 that arrived ahead of a missing one. The receiver's rule, with d the number of the last message handed over and n the number of a message in a frame sealed for its stream that opened: it keeps the message when n is more than d and no more than d plus MaxSkip/4, 16 with the defaults, and it holds none with that number already. It hands over d+1, d+2 and so on for as long as it holds the next one. A message numbered d or less was handed over before, and one numbered more than d plus MaxSkip/4 is further ahead than a sender seals before d+1 is acknowledged: neither is kept, the second is not acknowledged, and its sender sends it again. Either frame is answered with an acknowledgement all the same, which states d. When the frame states a first unacknowledged message past d+1, d is moved to one less than it before the rule is applied, and what is held below it is dropped.

A Delivery never rekeys and never asks for a new channel. When messages wait and nothing is acknowledged for StallAfter, the output of Tick says so, and again StallAfter later for as long as that lasts, or later where Ticks are late ("Like a Link" above). The application waits: a path that is cut needs nothing, and waiting through it costs no handshake. A channel whose numbering ran away needs Link.Rebuild or a rekey, and telling the two apart takes Link.Probe, which has a price through a cut. DeliveryUnacknowledged states when a probe is worth it, what it costs, and the test by which an application that probes decides on Rebuild.

The frame

A frame of a Delivery is one record of the Link. Its plaintext is a header of 61 bytes and, in a message frame, the message after it, which may be empty. Every number is big-endian. In order:

offset  size  field
0       1     kind: 1 for a message, 2 for an acknowledgement. The
              top bit, 0x80, is a flag added to either: the sender
              asks for an answer
1       8     the marker: the first eight bytes of the SHA-384 of
              the label "ake-delivery-frame-v1", the same in every
              frame
9       8     stream of the Delivery that sealed the frame, never zero
17      8     stream of the peer's Delivery the frame is sealed for;
              zero while the sender receives none
25      8     number of the message, from 1 through 2^64 - 2;
              zero in an acknowledgement
33      8     number of the first message the sender holds
              unacknowledged: one more than the number acknowledged
              to it, also when it holds none, from 1 through 2^64 - 1
41      8     number of the last message handed over of the stream
              named at offset 17: everything through it is
              acknowledged, from zero through 2^64 - 2
49      4     epoch of the frame of the peer's that the sender opened
              latest; zero before it opened one
53      8     the position: one more than the sequence number of that
              frame, so the next sequence number and not the highest
              opened; zero before the sender opened one

The frame's own epoch and sequence number are not in the plaintext: they are its record's, in the record's header, which the Link authenticates (SPEC section 10). The sender has them from Link.SealNumbered, and the receiver from LinkOutput.OpenedAt of the Receive that opened the frame. The frame opened latest is the one sealed latest among the frames of a Delivery opened on the channel in use: the highest epoch and, within it, the highest sequence number, as OpenedAt reports them. The position is counted in the peer's sending epoch, and a receiver takes it only when the frame opened on the channel whose numbering it keeps (the RecordPosition.Tag of LinkOutput.OpenedAt), the epoch at offset 49 is its own sending epoch, and the position is past the one it holds and no more than its NextSequence.

An acknowledgement ends with the header. A sender sets the flag while its distance is half of MaxSkip or more, and a receiver answers with an acknowledgement, AckDelay later, every message and every flagged frame that is sealed for its stream and opens for the first time.

A plaintext shorter than 61 bytes, whose first byte is no kind of a frame, or whose bytes at offsets 1 to 8 are not the marker, is a record the application sealed on the Link itself: a Delivery drops it, takes nothing from it, and counts it in DeliveryStatus.NotFrames (TestDeliveryCountsTheRecordsThatAreNoFrameOfADelivery). Its position is its record's like any other, so it cannot move the numbering a Delivery compares frames by. Read as a frame, such a record would do harm: its bytes would be taken for streams, and one that was the latest frame and seemed to name a stream other than the one received would have the receiver report PeerRestarted and start receiving over, as for a Delivery of the peer's that was lost. The marker is what tells the two apart, whatever the record begins with: one of the application's carries it by accident with a chance of about 2^-64, and only one written to pass for a frame, with the kind and the marker in place, is read as one (TestDeliveryKeepsReceivingAfterARecordThatBeginsWithAnotherByte, TestDeliveryCountsARecordThatBeginsWithTheKindOfAFrameWithoutTheMarker). TestDeliveryFrameHeaderLayout compares one acknowledgement and one message frame with this layout byte by byte.

A restart

The message numbers, the queue and the two stream identifiers are the Delivery's state, and they are in memory only. A Delivery has no stored form and no way to export or restore one: it lives as long as its process. Within the process it outlives its Link. An application that replaces the Link passes the new one to SetLink, and nothing is lost and nothing is handed over twice.

A restart of the process makes a new Delivery, with the consequences of "A lost Delivery": the peer's unacknowledged messages are handed over at least once, the duplicates are among the Unconfirmed the peer reports, and what the lost Delivery had taken from this end's application and not handed on is gone with it.

An application that needs more has to write the stored form itself. What follows is an outline of what that form would hold, not something this package provides or tests:

  • the two stream identifiers: the Delivery's own (stream) and the one it receives (peerStream);
  • the sending side: the number of the next message (nextID), the number acknowledged through (acked), and every unacknowledged message with its number and whether it was sealed for the peer's stream (queue: id, data, sealed), stored before Send returns;
  • the receiving side: the number of the last message of the peer's stream handed over (delivered) and the count handed over in all (handed), committed together with the application's own handling of each delivered message. Stored after it, a restart in between hands the message over again; stored before it, the message is acknowledged and lost.

Nothing of the channel belongs in it: the frames, their sequence numbers, the positions, the timers and the messages held ahead of a missing one start over with the Link, as they do after SetLink.

The outline does not cover a crash between the storing of a message and the return of Send. Send returns no handle to a message, so an application that did not see Send return cannot tell whether the message is in the stored form: it passes the message again after its restart, and a message that was stored is then handed over twice. A stored form that closes this needs a handle of the application's own stored with each message, by which a second offer of the same message is recognised.

A lost Delivery

An end that makes a new Delivery where it had one starts its numbers at 1 again, and its peer still counts in the old ones. By numbers alone the peer would drop the new messages as repeats and acknowledge them, and the new Delivery would take the peer's count of the old messages for an acknowledgement of its own. So NewDelivery draws a stream identifier, eight random bytes, and every frame states three things more: the stream of its sender, the stream of the peer's that the frame is sealed for, zero before its sender has opened a frame of the peer's, and the number of the first message its sender holds unacknowledged.

Which stream a Delivery receives follows from the order in which frames were sealed, not from the order in which they arrive. An end has one Delivery at a time and its Link numbers what they seal in the order they seal it, so on a channel every frame of a Delivery that is gone comes before every frame of the one in its place, and the latest frame a Delivery has opened, in the channel's numbering, is the one that says most about the peer:

  • A Delivery that receives no stream takes the stream of the latest frame when that frame is sealed for its own stream or for none. One sealed for another Delivery of its end, which is gone, it does not take: the sender may be gone too.
  • A Delivery that receives a stream and opens a latest frame of another takes that one, whichever stream the frame is sealed for: the Delivery it was receiving is gone. This is what the output reports as PeerRestarted.
  • A frame of a stream it does not receive that is not the latest is of a Delivery that is gone. It is dropped and not answered.
  • A latest frame that is not sealed for its own stream it answers with an acknowledgement, which states its stream and the one it receives. The answer is sealed after every frame of the Deliveries that are gone, so it is the latest frame where it opens.

So each of two Deliveries that hold a wrong idea of the other's stream, or none, is put right by frames of the other's, whatever was held back on the path and in whatever order it arrives: one that receives a stream that is gone takes the present one from the first of its frames, and one that receives none takes it from the answer to its own. That is also how a peer with nothing to send learns of a new Delivery, and how two Deliveries learn of each other at the start.

A Delivery takes messages and acknowledgements only from a frame sealed for its own stream. A message sealed before its Delivery has opened a frame of the peer's therefore goes out twice: as sealed, which draws the answer, and sealed again for the peer's stream. The answers to frames sealed for another stream follow one another by ResendInterval at the least, each wait double the one before up to sixteen intervals, until a frame sealed for this stream opens: an end whose answers change nothing at the peer does not answer every frame.

The end that kept its Delivery opens a frame of a stream other than the one it was receiving, sealed later in the channel's numbering than every frame it opened before. It starts receiving over for that stream: it drops what it held of the old one and expects the new one's first message, its output has PeerRestarted and Unconfirmed, and it seals its unacknowledged messages again, for the new stream and under the numbers they have. The new Delivery takes the peer's messages from the first one the peer holds unacknowledged: the Delivery that is gone acknowledged everything before that one, and so handed it over.

Unconfirmed counts the messages sealed for the stream that ended, and each event has its own count. When the peer loses its Delivery twice in a row, a message the first event counted and that was not sealed again in between is not counted by the second: the counts of the two events together cover the messages that may be handed over twice.

A new Delivery cannot tell a Delivery of the peer's that was gone before it started from one that is lost afterwards. If the first frame it opens is a held one that a Delivery which is gone sealed for no stream, it takes that stream, and the first frame of the peer's present Delivery makes its output say PeerRestarted, once: Unconfirmed then counts messages it sealed for a stream that nothing received.

What holds across a lost Delivery:

  • A Delivery acknowledges what it handed over itself and what its peer states was acknowledged before it, and takes an acknowledgement only from a frame sealed for its own stream: no message counts as acknowledged that no Delivery handed to its application.
  • Each Delivery hands over the messages of one stream once and in order, from the first it is handed on.
  • A message of the end that kept its Delivery is handed over at least once, and one that was acknowledged before PeerRestarted exactly once. The Unconfirmed ones may have been handed to the application by the lost Delivery, and the new one hands all of them over and acknowledges them: an application that cannot take a message twice recognises them itself. It does so at the end that restarted, where the duplicates are handed over by a new Delivery that is told nothing of them; only the end that kept its Delivery reports Unconfirmed. Either end may be the one that restarts, so handling every message exactly once takes an identifier of the application's own in each message and, at each end, the identifiers of the messages handled, kept in durable storage and committed with the handling.
  • A message the lost Delivery had taken and its peer was not handed is gone, unless the application kept it and passes it to Send again. The peer is told that a stream ended, not how many messages it missed.
  • An end that had opened no frame of the lost Delivery is told nothing. For it the new stream is the first, and nothing of its own was handed over before.
  • When both ends lose their Deliveries at the same instant, no message is handed over twice. A new Delivery that opens a frame the peer's lost one sealed for no stream takes that stream as the one it receives and takes no message from the frame: the frame is not sealed for its own stream, and take returns before the message for every such frame. Where that frame is the first it opens, the Receive that opens the first frame of the peer's new Delivery reports PeerRestarted, and the messages that output counts as Unconfirmed were never handed over; otherwise neither end is told anything. What the two lost Deliveries held is gone with them. An application that kept its messages and passes them to the new Delivery has them handed over again, and recognises the repeats itself.

A new Delivery takes the distance from zero, like any other. Over a Link whose channel has sealed 3/4 of MaxSkip records or more it seals no message until a frame of the peer's reports a position. A peer with traffic of its own reports one in every frame. For a peer that is idle, or whose Delivery is new as well, the Delivery seals the two acknowledgements that "The decisions" allow it past the limits, the first of them one ResendInterval after it has something to send or half of MaxSkip to ask about, and the answer to either reports the position. Into a path that carries nothing it seals those two records and no more, however long it waits, for as long as no frame of the peer's reports a position.

func NewDelivery

func NewDelivery(link *record.Link, opts DeliveryOptions) (*Delivery, error)

NewDelivery returns a Delivery over link, which the application goes on operating. It returns an error wrapping ake.ErrUsage for a nil Link, for a Link after Zero, for a negative duration or limit, for a duration of at least 1<<59 ns (about 18 years: the longest wait is sixteen times ResendInterval), and for a MaxSkip or a ReplayWindow that is neither zero nor the value LinkStatus reports for link. It reads the stream identifier from crypto/rand.Reader as the package found it when it was initialised, and returns that source's error.

func (*Delivery) Format

func (d *Delivery) Format(f fmt.State, _ rune)

Format writes "Delivery(…)" for every verb, as Cluster.Format writes its name, and nothing of the Delivery's state: not the messages it holds, its own that wait for an acknowledgement and the peer's that wait for one before them, nor its Link. Status reports the counts.

func (*Delivery) Receive

func (d *Delivery) Receive(now time.Time, frame []byte) (DeliveryOutput, error)

Receive takes one frame from the record path and passes it to the Link. The output holds the messages that became deliverable and the frames to send. The error is Link.Receive's, for a Link that cannot be used.

func (*Delivery) Send

func (d *Delivery) Send(now time.Time, message []byte) (DeliveryOutput, error)

Send takes a message for the peer. The message is copied. It is sealed at once when the channel has room, and the output's Send then holds its frame; otherwise it waits. Send returns an error wrapping ake.ErrUsage, and takes nothing, for a message that no record carries with the 61-byte header of its frame: one longer than 68,719,476,642 bytes on a 64-bit platform and than 2,147,483,534 bytes on a 32-bit one. It returns ErrDeliveryQueueFull, and takes nothing, when QueueLimit messages are waiting. After taking message number 2^64 - 2 it returns ErrDeliveryExhausted and takes nothing. Keep this Delivery until Status reports no queued message, then make a new one and offer the refused message to it, with the duplicate/loss boundary under "A lost Delivery". Exhaustion takes precedence over a full queue; an invalid message size takes precedence over both. It returns no handle to the message: DeliveryStatus.Sent and Acknowledged count the messages in the order of the calls, and that order is how an application tells which of its messages a count means. A nil method error means the Delivery took the message, including when the output has a SealError. Keep the Delivery and let it send the queued message once the channel is replaced.

func (d *Delivery) SetLink(link *record.Link) error

SetLink passes the Delivery another Link in place of the one it has, for an application that replaces its Link within one process: a Delivery does not outlive its process ("A restart"). The messages not yet acknowledged are sealed again once that Link has a channel. The new Link is toward the same peer identity key as the one it replaces: SetLink does not check the keys, so the caller compares the Identities of the two Links before it calls SetLink, and a Delivery passed a Link toward another key hands that key's holder the messages its peer had not acknowledged, as if the peer had restarted. For a peer that returns with another identity key, make a new Delivery. It returns an error wrapping ake.ErrUsage for a nil Link, for a Link after Zero, and for a Link whose MaxSkip or ReplayWindow is not the one the Delivery counts with, which it took from the Link it was made over: the limits of what it holds and of what its peer seals ahead are fractions of that MaxSkip. A refused call changes nothing, and the Delivery keeps the Link it had.

func (*Delivery) Status

func (d *Delivery) Status() DeliveryStatus

Status returns a snapshot of the Delivery.

func (*Delivery) Tick

func (d *Delivery) Tick(now time.Time) (DeliveryOutput, error)

Tick runs the Link's timers and the Delivery's, and it is the one call whose output reports a stall. Call it whenever the time Wake reports has come, which for a new Delivery is at once, after all the frames that queued up meanwhile were passed to Receive, which the Link asks for; calling it at other times is harmless. A Tick that finds the report of a stall more than ResendInterval overdue makes none and puts it off by sixteen ResendIntervals, and a report is put off by no more than StallAfter in all (report). The error is Link.Tick's.

func (*Delivery) Wake

func (d *Delivery) Wake() time.Time

Wake returns when Tick is next due, for the Link and the Delivery together, or the zero time when no timer is needed. Read it after every call, of the Delivery or of the Link. A time that has passed means Tick is due now. Until a call has passed the Delivery a time, it reports a time that has passed, the earliest after the zero time, as a Link does until its first Tick: an application that sets its timer only from a Wake that is not zero runs the first Tick at once, whether the Link is new or has a channel already.

type DeliveryOptions

type DeliveryOptions struct {

	// ResendInterval is the shortest time a sent message waits for its
	// acknowledgement before it is sent again. The wait follows the time
	// the peer's acknowledgements take where that is longer, and each
	// further wait doubles, up to sixteen intervals. It is also how long a
	// frame that the peer reports a position past is left to arrive before
	// it is sent again, and a record of the peer's that opens after sixteen
	// intervals in which none did sends what waits ("The decisions" in the
	// documentation of Delivery). Zero means 250 ms. A value below the time
	// to the peer and back plus the peer's AckDelay costs frames sent twice
	// until that time has been measured, not correctness.
	ResendInterval time.Duration
	// AckDelay is how long an acknowledgement waits for more to
	// acknowledge, or for a message to ride on. Zero means 100 ms.
	AckDelay time.Duration
	// StallAfter is how long messages may wait with nothing acknowledged
	// before an output says so. Zero means 30 s.
	StallAfter time.Duration
	// MaxSkip and ReplayWindow are the Link's Channel options of the same
	// names. A Delivery counts with the values its Link was made with,
	// which LinkStatus reports, and zero, for either, means those. A value
	// that is not zero has to be the Link's: NewDelivery returns an error
	// wrapping ake.ErrUsage for another, and SetLink for a Link made with
	// other values than the Delivery counts with
	// (TestNewDeliveryCountsWithItsLinksLimitsAndRefusesOthers).
	//
	// The check is made because nothing else shows a difference. Every
	// limit of a Delivery is a fraction of MaxSkip, and ReplayWindow is
	// where it stops sending a frame again and seals the message anew. What
	// the refusal prevents happens on a path that loses frames: there a
	// Delivery that counted with higher values than its Link's would stop
	// delivering for good, with no error from any call. Measured with both
	// Deliveries made to count with a MaxSkip and a ReplayWindow of 256
	// over Links of the default 64, which only a test can do, ten messages
	// a second offered each way, twenty minutes after a cut of two
	// minutes: neither backlog had drained, and no message was
	// handed over in the last ten of those minutes. The Links held the
	// channel they had and performed no handshake. Two things showed it.
	// Each end reported DeliveryUnacknowledged every StallAfter, as it
	// does through a cut. And in those ten minutes each Link refused every
	// frame of the peer's Delivery that arrived as older than its replay
	// window: record.ErrTooOld in DeliveryOutput.Link.Dropped, hundreds of
	// times, and record.ErrTooFarAhead not once
	// (TestDeliveryCountingWithLimitsAboveItsLinksStopsDelivering).
	MaxSkip      uint
	ReplayWindow uint
	// QueueLimit is how many messages may wait for their acknowledgement,
	// sent or not. Zero means 1024. It bounds memory, not the rate: of the
	// messages that wait, MaxSkip/4 at the most are on the path.
	QueueLimit int
	// contains filtered or unexported fields
}

DeliveryOptions configures a Delivery. Both ends may choose differently, except MaxSkip and ReplayWindow, which are the Link's.

No option makes a Delivery fast. At most MaxSkip/4 messages are sealed and unacknowledged at once, 16 with the Link's defaults, whatever QueueLimit is, and the next one is sealed when an acknowledgement arrives, so the rate follows the time to the peer and back. Measured with the defaults, one end sending as fast as its queue takes messages, over two minutes, three runs in each of three sets of seeds: 112 to 113 messages a second on a path that loses nothing and delays by 10 to 50 ms, 157 a second with a delay of 1 ms, 28 to 30 a second on a path that loses a tenth of the frames and delays them by 10 to 250 ms, and 16 to 18 a second on one that loses a fifth and delays them by 10 to 400 ms. A backlog of one hour of messages offered at ten a second into a cut, 36,000 of them, which the application kept and offered again as the queue took them, drained, one run in each set, in 5 m 20 s to 5 m 22 s on the first of these paths, in 20 m 22 s to 20 m 38 s on the one that loses a tenth, and in 34 m 50 s to 35 m 23 s on the one that loses a fifth (TestDeliveryRateAndBacklogAreTheFiguresTheDocumentsState). An application that offers more than that learns of it in one way only: Send returns ErrDeliveryQueueFull once QueueLimit messages wait. No stall is reported while acknowledgements arrive.

type DeliveryOutput

type DeliveryOutput struct {

	// Link is the output of the Link call this call made, if it made one,
	// without the three fields that are not the application's to use: Send
	// is nil, because the Link's frames are in Send below and are sent
	// once; Plaintext is nil and Delivered false, because what the Link
	// opened is a frame of the Delivery's, whose messages are in Delivered
	// below. The application acts on the rest as it would without a
	// Delivery: its handshakes, its hint, its request for a handshake, its
	// events, and Lost, Opened and Dropped
	// (TestDeliveryOutputLinkHasNoFramesAndNoPlaintext). Known is never
	// set: Link.OfferHandshake sets it, which no call of a Delivery makes.
	Link record.LinkOutput
	// Send holds frames for the record path, the Link's and the Delivery's,
	// in order. The caller owns them.
	Send [][]byte
	// SealError is set when sealing an outgoing Delivery frame failed
	// locally with an error matching record.ErrExhausted. The queue keeps
	// its messages, including one accepted by this Send. Act on the rest
	// of the output and call Link.Rebuild to replace the channel. Rekeying
	// preserves the Driver's lifetime application count.
	SealError error

	// Delivered holds the peer's messages that became deliverable, in the
	// order the peer passed them to Send: each once for as long as both
	// ends keep their Delivery, and as the documentation of Delivery
	// states when an end made a new one. The caller owns them.
	Delivered [][]byte
	// Stalled is set for as long as messages wait and none is acknowledged:
	// once every StallAfter for an application that calls Tick when Wake
	// says so, and further apart for one whose Ticks are late. Tick alone
	// sets it: the outputs of Send and Receive never have it. A Tick that
	// comes more than ResendInterval after the report was due does not set
	// it and puts the report off by sixteen ResendIntervals, and so does
	// each late Tick after that, until the report has been put off by
	// StallAfter in all ("Like a Link" in the documentation of Delivery).
	Stalled DeliveryStall
	// PeerRestarted is set by the Receive that opens the first frame of
	// another Delivery at the peer than the one this end was receiving
	// from: the peer lost its Delivery and made a new one. What the lost
	// one had taken and this end was not handed is gone with it. This end's
	// messages that were not acknowledged go to the new one, and
	// Unconfirmed is how many of them, the first in order, had been sealed
	// for the one that is gone: the lost Delivery may have handed any of
	// those to its application, and the new one hands over all of them.
	//
	// Unconfirmed is a count, and Send returns no handle to a message, so
	// the application tells which messages are meant by their order: they
	// are the first Unconfirmed of the messages this Delivery holds
	// unacknowledged, in the order they were passed to Send, which are the
	// messages numbered DeliveryStatus.Acknowledged+1 onward when Send's
	// calls are counted from one. The Delivery sends every unacknowledged
	// message to the new stream by itself: an application that passes its
	// own copies to Send again after PeerRestarted has each of them handed
	// over a second time.
	//
	// The count is this event's alone. "A lost Delivery" in the
	// documentation of Delivery says what holds across it, and what the
	// counts of two events in a row cover.
	PeerRestarted bool
	Unconfirmed   int
	// contains filtered or unexported fields
}

DeliveryOutput is what a Delivery call asks the application to do.

type DeliveryStall

type DeliveryStall uint8

DeliveryStall says why a Delivery reports that it is not getting anywhere.

const (
	// DeliveryNotStalled is the zero value: nothing to report.
	DeliveryNotStalled DeliveryStall = iota
	// DeliveryNoChannel means messages are waiting and the Link holds no
	// channel. The Link is seeking one by itself; what stands in the way is
	// in its outputs (LinkOptionsMismatch, a handshake that cannot be
	// started).
	DeliveryNoChannel
	// DeliveryUnacknowledged means the Link holds a channel and the peer
	// acknowledged nothing for StallAfter. The report is information, and
	// asks the application for nothing. The path may be cut, the peer may
	// be gone, or the distance the Delivery counts on the channel's
	// numbering may have reached what stops it sealing: the numbering ran
	// away from what the peer accepts, or the peer's reports of its position
	// did not arrive while the Link went on sealing records of its own.
	//
	// What an application does at a report is wait: it calls nothing on
	// the Link. That is the right reaction to a path that is cut and to a
	// peer that is gone for a time. The Delivery keeps its messages and
	// sends its frames again, and it bounds its own numbering: it seals
	// nothing at a distance of MaxSkip or more, so what it sealed
	// into the cut opens when the path is back, and delivery goes on over
	// the channel the Link had, with no handshake performed. Measured with
	// ten messages a second offered each way through cuts of a minute, ten
	// minutes and an hour, of both directions and of one, over a path that
	// loses a tenth, eight runs of each length in each of three sets of
	// seeds: the ends that waited performed no handshake from the start of
	// the cut, kept their channel in every run, and were handed the first
	// message within 1.1 to 2.1 seconds of the path's return
	// (TestDeliveryWaitingThroughACutPerformsNoHandshake).
	//
	// Those times are the latest run of each set, and no bound, for these
	// three lengths or for another: cut toward the first end as well, the
	// latest run of the same lengths took 1.1 to 2.5 seconds in the runs
	// below, and other lengths longer. A
	// frame that waits for its acknowledgement through a cut is sent again
	// once every sixteen ResendIntervals, 4 seconds with the default, and
	// the first message is handed over when a frame sent after the path's
	// return has crossed the path. So the time depends on where in those
	// sixteen intervals the path returns, for each of the frames that
	// wait, which makes it rise and fall with the length of the cut, and
	// on the path's delay and loss.
	// Measured over cuts of a minute and of ten minutes with nothing to 4
	// seconds added in steps of a quarter of a second, toward either end
	// and of both directions, and of an hour with up to 2 seconds added,
	// toward either end, 440 runs in each of three sets of seeds on a path
	// that delays by 10 to 250 ms: no handshake, the channel kept in every
	// run, and the first message within 2.4 to 3.8 seconds of the path's
	// return (TestDeliveryFirstMessageAfterACutFollowsTheResendWait).
	//
	// Each of these figures is the latest run of its test in each of three
	// sets of seeds, which the tests draw their delays and losses from
	// (AKE_DELIVERY_SEED_SET names the set), and where the sets differ the
	// figure is the least and the most of the three; other seeds measure
	// other figures, outside those ranges as well. None is a bound, and
	// under loss the time has none. A frame
	// lost after the path's return is sent again when its wait is over,
	// each wait double the one before up to sixteen intervals, or one
	// interval after it went out when the peer reports a position past
	// it, and nothing limits how many are lost in a row. Measured over
	// paths that lose two and three tenths,
	// cuts of a minute with nothing to 4 seconds added in steps of 50 ms,
	// toward either end and of both directions, 972 runs in each set: no
	// handshake, the channel kept in every run, and the first message
	// within 3.2 to 4.8 seconds of the path's return.
	// On a path that loses six tenths from its return on, 246 runs in each
	// set, it came within 4.4 to 9.4 seconds, and later than 4.5 seconds
	// in 0 to 17 runs.
	// Where most frames are lost, the first unacknowledged frame is lost
	// several times in a row, and each of its waits is double the one
	// before: that path is what sending it for every later position of
	// the peer's is for ("The decisions" in the documentation of
	// Delivery). Measured with that frame sent for one position alone, as
	// the frames behind it are, the first message came within 16.4 to
	// 33.9 seconds in the same runs, and within 8.3 to 12.4 seconds where
	// two and three tenths are lost. A shorter ResendInterval shortens the
	// time and a longer one lengthens it: on the path that loses a tenth,
	// 198 runs of each in each set, the first message came within 1.1 to
	// 1.4 seconds with a ResendInterval of 100 ms and within 15 to 19
	// seconds with one of 1 s
	// (TestDeliveryFirstMessageAfterACutUnderLossAndOtherResendIntervals).
	//
	// The 4.5 seconds are sixteen times ResendInterval plus the path's
	// longest delay each way, and on a path that loses nothing after its
	// return that is a bound, for ends that both hold a message sealed
	// and unacknowledged when the path returns. Every such frame is sent
	// again when its wait is over, and no wait is longer than sixteen
	// intervals: within that time of the return each end has sent every
	// frame it holds sealed, and its peer has them one delay later. An
	// end that lacked one of those messages is handed the first it lacks
	// then. An end that lacked none, the cut having been toward its peer
	// alone, is handed the first message its peer seals after the return:
	// the peer seals it when it takes an acknowledgement from one of this
	// end's frames, and it arrives one delay later. That last step takes
	// one of those frames to acknowledge a message the peer still holds;
	// where none does, an acknowledgement sealed after the return has to
	// cross first. Measured on the path that loses a tenth until the cut
	// ends and nothing from then on, cuts of a minute with nothing to
	// sixteen intervals added, toward either end and of both directions,
	// with a ResendInterval of 100 ms, of 250 ms and of 1 s, 450 runs in
	// each set: every run within sixteen times its interval plus the
	// delays, and the first message within 2.3 to 3.2 seconds with the
	// default interval
	// (TestDeliveryFirstMessageAfterACutOnAPathThatLosesNothingAfterIt).
	// An application that needs the first message sooner after a cut
	// lowers ResendInterval, which costs frames while the path is cut.
	//
	// Calling Link.Probe at a report is the application's choice, and it
	// has a price. A probe that gets no answer makes the Link seek, and a
	// Link that seeks asks for handshakes for as long as the cut lasts,
	// each of which reserves one of the peer's one-time prekeys; "What
	// probing costs and gains" in the record package's documentation has
	// the schedule of those requests and what they gain. In the same cuts,
	// ends that probed at every report as described below performed 2
	// handshakes a run through a cut of a minute, 15 through ten minutes
	// and 32 to 33 through an hour, ended on another channel in 8, 2 to 6
	// and 0 to 2 of the eight runs, and were handed the first message
	// within 1.5 to 1.8, 1.8 to 2.6 and 1.8 to 3.3 seconds, against 1.1 to
	// 1.8, 0.6 to 2.1 and 0.8 to 1.9 for the ends that waited. A probe is
	// worth that in two cases. The
	// application has to learn that the peer is not there while it is not
	// there, to tell a user or to send its messages another way: the
	// Link's LinkStalled says so half a RekeyTimeout after the probe, or
	// says that the path lost what the probe sent. Or the application has
	// a reason of its own to believe that the path carries records, and
	// still nothing is acknowledged: that is the
	// third cause, which only a probe that passes can show, and which
	// needs Link.Rebuild, or a rekey by the channel's initiator. An
	// application that never probes does not learn of the third cause; no
	// schedule of the tests has produced it.
	//
	// When the only indication is a stall, an application calls Link.Rebuild,
	// or has the initiator rekey, at a report of DeliveryUnacknowledged at which the
	// test below shows that a probe of this channel passed since the report
	// before and that nothing was acknowledged in between. An application
	// that waits never calls it.
	//
	// An application that chose to probe does so by this test. At every
	// report of DeliveryUnacknowledged it reads the Link's status, and
	// does one of two things.
	//
	// It calls Link.Rebuild, or has the initiator rekey, when all of this
	// holds:
	//
	//   - the report before it was made by the same Delivery with the same
	//     DeliveryStatus.Acknowledged: reports are StallAfter apart at the
	//     least, so that count stood still for twice StallAfter and more;
	//   - Link.Probe, called at that earlier report, returned nil;
	//   - LinkStatus.Tag is what it was at that earlier report: the Link
	//     holds the channel it held then;
	//   - LinkStatus has Up set, and none of Probing, Seeking and
	//     Confirming.
	//
	// At every other report it calls Link.Probe, whatever the status
	// shows, and keeps four things for the next report: the Delivery, its
	// Acknowledged, LinkStatus.Tag, and whether Probe returned nil. An
	// error from Probe (ErrNoChannel, ErrAttemptPending, ErrProbeLimited,
	// ErrProbeSpent) means the Link started no test of the channel; the
	// application does nothing more about it. At a report at which it
	// called Rebuild it called no Probe, so the report after that one
	// never calls Rebuild.
	//
	// A nil error from Probe does not say that a probe passed, or that this
	// call started one: Probe also returns nil while a probe or the
	// confirmation of a newly adopted channel is running, and a Link that
	// seeks may be probed again. The conditions together say it. The channel
	// is the one that was being tested at the earlier report, the test
	// has ended, and the Link does not seek, so the test did not fail, or
	// a later one passed: the peer held this channel when it sealed the
	// record that passed it, and still nothing is acknowledged. Without the
	// tag the other conditions hold
	// as well for a channel the Link adopted since the earlier report,
	// seconds old, which nothing has shown to need replacing.
	//
	// The schedules of delivery_test.go, 200 with cuts, replaced Links and
	// rekeys and 360 with lost Deliveries, have applications that follow
	// this test in half of them and applications that wait in the other
	// half. Rebuild is called in none, and none of their stalls needed
	// it: each ended when the path returned or when the Link replaced its
	// channel by itself.
	DeliveryUnacknowledged
)

func (DeliveryStall) String

func (s DeliveryStall) String() string

String returns the name of the stall.

type DeliveryStatus

type DeliveryStatus struct {

	// Queued is the number of messages not yet acknowledged, and InFlight
	// how many of them are sealed on the channel in use.
	Queued, InFlight int
	// Sent counts the messages Send took, Acknowledged those a Delivery of
	// the peer's has acknowledged, and Delivered the peer's messages handed
	// out. Sent and Acknowledged stop with their stream at 2^64 - 2;
	// Delivered, which spans peer streams, saturates at 2^64 - 1.
	Sent, Acknowledged, Delivered uint64
	// Room is how many more records could be sealed on the channel before
	// the distance the Delivery counts reaches MaxSkip: its numbering less
	// the last position the peer reported. It is zero without a channel.
	Room uint64
	// NotFrames counts the records the Link opened for the application
	// that are no frame of a Delivery: a plaintext shorter than the header,
	// one whose first byte is no kind of a frame, or one that does not carry
	// the marker after it ("The frame" in the documentation of Delivery).
	// One thing puts a record there: the peer's
	// application sealed it on its Link directly, with no Delivery or
	// beside one. A frame of the peer's Delivery is never counted, whatever
	// other goroutines had the peer's Link seal meanwhile: its position is
	// its record's. The Delivery drops these records, and DeliveryOutput.Link
	// carries no plaintext, so this count is the one trace such a record
	// leaves: an application that sees it rise has a peer that seals beside
	// its Delivery. The count saturates at 2^64 - 1
	// (TestDeliveryCountsTheRecordsThatAreNoFrameOfADelivery).
	NotFrames uint64
	// contains filtered or unexported fields
}

DeliveryStatus is a snapshot of a Delivery.

type Directory

type Directory struct {
	// contains filtered or unexported fields
}

Directory is an in-memory stand-in for an untrusted prekey directory. It publishes the signed medium-term bundle separately from individually signed hybrid one-time prekeys. FetchForHandshake atomically removes one public one-time record, so concurrent initiators cannot select the same record.

Authenticity never comes from Directory: callers configure a trusted identity independently and verify both records. Availability, reservation fairness and rate limiting remain a deployment concern.

FetchForHandshake serves the bundle and a one-time prekey in one reply, which the documentation of package record advises against for a deployment: a requester whose bundle does not verify, such as a peer that still expects a replaced node's identity key, has reserved a prekey it cannot use, and it is not given back. A deployment's directory serves the bundle by itself first, so that the requester verifies it before it reserves a prekey.

func NewDirectory

func NewDirectory() *Directory

NewDirectory returns an empty directory.

func (*Directory) FetchForHandshake

func (d *Directory) FetchForHandshake(partyID string) (bundleWire, otkWire []byte, err error)

FetchForHandshake returns the current bundle and atomically reserves the first available one-time prekey. Strict v1 has no 3DH fallback: an empty inventory is an error.

func (*Directory) OneTimeKeyCount

func (d *Directory) OneTimeKeyCount(partyID string) (int, error)

OneTimeKeyCount reports the number of unreserved public OTK records.

func (*Directory) Publish

func (d *Directory) Publish(partyID string, wire []byte)

Publish replaces only a party's bundle. It is retained as a deliberate corruption/withdrawal seam in the illustrative tests; normal publication uses update, which replaces the bundle and its available OTK records atomically.

func (*Directory) Remove

func (d *Directory) Remove(partyID string)

Remove withdraws both the bundle and the available public OTK inventory.

type DriverLink struct {
	// Lose, when not nil, is asked once for every record about to be
	// delivered and drops the record when it returns true. toResponder is
	// the direction of travel.
	Lose func(toResponder bool) bool
	// Tap, when not nil, is shown every record an endpoint put in flight,
	// before Lose is consulted, as an observer on the path would see it. It
	// must not modify wire.
	Tap func(toResponder bool, wire []byte)
	// contains filtered or unexported fields
}

DriverLink joins the record Drivers of two in-process parties by a path that can lose records, with a clock the caller advances. It stands in for what a deployment builds around record.Driver: a transport, a receive loop that passes every record to Driver.Receive and sends what comes back, a timer that calls Driver.Tick, and a handshake path that tells the responder whether a handshake is a rekey or replaces the channel.

Records sealed during one Advance are delivered by the next, so nothing arrives in the instant it was sent. A DriverLink is not safe for concurrent use.

func EstablishDriverLink(initiator, responder *Party, channelID string) (*DriverLink, error)

EstablishDriverLink performs a handshake marked as a new channel between the two parties and returns a link whose Drivers are built from it. initiator is the channel initiator for the life of the link: it starts every later handshake.

func (*DriverLink) Advance

func (l *DriverLink) Advance(d time.Duration) (LinkReport, error)

Advance moves the clock forward by d, delivers the records in flight except those Lose drops, and runs both Drivers' timers. It returns record.ErrRebuildRequired when a Driver reports that the pair must be rebuilt.

func (*DriverLink) Close

func (l *DriverLink) Close()

Close scrubs both Drivers.

func (*DriverLink) Crash

func (l *DriverLink) Crash(initiator bool)

Crash discards one endpoint's Driver as a process that died would lose it, with no notice to the peer. Records still in flight stay in flight. The endpoint drops everything it receives until Rebuild gives it a Driver again; pair it with Party.Restart to model a restarted process.

func (*DriverLink) DropNextHandshake

func (l *DriverLink) DropNextHandshake()

DropNextHandshake makes the responder's half of the next handshake go missing, as when the message carrying it is lost.

func (*DriverLink) Epochs

func (l *DriverLink) Epochs() (initiatorSend, initiatorReceive, responderSend, responderReceive uint32, err error)

Epochs returns the sending and receiving epoch of each endpoint.

func (*DriverLink) InFlight

func (l *DriverLink) InFlight() int

InFlight reports how many records are waiting to be delivered.

func (*DriverLink) InitiatorID

func (l *DriverLink) InitiatorID() string

InitiatorID returns the name of the party that is this link's channel initiator.

func (*DriverLink) Inject

func (l *DriverLink) Inject(toResponder bool, wire []byte)

Inject puts wire in flight toward one endpoint as an attacker on the path would: a replayed, reflected, altered or invented record. It is delivered by the next Advance without consulting Lose or Tap.

func (*DriverLink) Rebuild

func (l *DriverLink) Rebuild() error

Rebuild replaces both Drivers from a handshake marked as a new channel, as after a restart of either party or a record.DriverRebuildRequired event. Records still in flight belong to the old channel and are discarded.

It replaces both ends in one step, which only this in-process link can do: it sees both parties and its handshake path loses and delays nothing. It is here to put a DriverLink back in working order for the rekey tests, and it is not a procedure for a deployment, where an endpoint that destroyed its channel because a handshake arrived could be made to do so by a delayed or repeated one. LinkPair shows the replacement as each endpoint carries it out by itself, with record.Link.

func (*DriverLink) Rekeying

func (l *DriverLink) Rekeying() bool

Rekeying reports whether either endpoint has a rekey in progress.

func (*DriverLink) Send

func (l *DriverLink) Send(fromInitiator bool, plaintext []byte) error

Send seals plaintext as application data at one endpoint and puts the record in flight.

func (*DriverLink) StartRekey

func (l *DriverLink) StartRekey() error

StartRekey performs a handshake marked as a rekey and gives each Driver its half. The rekey then proceeds through Advance. It returns record.ErrRekeyState, before any handshake, while a rekey is in progress.

type Envelope

type Envelope struct {
	SenderID       string
	RecipientID    string
	InitialMessage []byte // ake wire format
	Nonce          []byte
	Ciphertext     []byte
}

Envelope is the unit that crosses the wire between parties: the handshake data plus one AEAD-sealed payload. A production system maps this onto its transport frame.

type GroupMessage

type GroupMessage struct {
	KeyID  string
	Sender string // member id; selects the per-sender subkey (see GroupSeal)
	// Nonce is the 12-byte AES-GCM nonce, drawn by Go's cryptographic module
	// (its SP 800-90A DRBG in FIPS mode, the operating system's generator
	// otherwise), never from crypto/rand.Reader.
	Nonce      []byte
	Ciphertext []byte // the ciphertext and its 16-byte tag
}

GroupMessage is a message sealed under the cluster's shared group key. KeyID names the group-key epoch it was sealed under, so a member holding a different epoch fails to open it (which is how a re-key after a member leaves excludes the departed member).

type LinkPair

type LinkPair struct {
	// Lose, when not nil, is asked once for every frame or handshake about
	// to be delivered and drops it when it returns true. toFirst says
	// whether it is on its way to the first party.
	Lose func(toFirst bool) bool

	// FetchDelay is how long each end takes to fetch the peer's bundle and
	// reserve a one-time prekey, the first party's value first. With zero
	// the fetch ends before anything else happens at that end. With more,
	// the end goes on receiving and running its timer while it fetches, as
	// a deployment does: its Link asks again meanwhile, and may have
	// stopped wanting the handshake when the fetch returns.
	//
	// An end does not call record.Link.CannotInitiate before it fetches,
	// which the documentation of package record advises an application
	// that expects to be slow to do so that the hint is sent meanwhile. It
	// calls it only when a handshake could not be made. An end that
	// restarted therefore sends nothing for the whole of its fetch, and a
	// peer that holds the earlier channel and does not probe it does not
	// notice the restart in that time.
	FetchDelay [2]time.Duration
	// contains filtered or unexported fields
}

LinkPair joins two in-process parties by a record.Link at each end, a record path and a handshake path that can lose what they carry, and a clock the caller advances. It stands in for what a deployment builds around record.Link, and each end does only what one endpoint can: it sees its own Link and the frames that reach it, never the other end's state.

The two ends keep one channel between them. When an end restarts it has none, asks for a handshake, and the pair comes back by the Link's procedure; nobody tells the other end, and nothing is destroyed because a handshake arrived.

What an end sends during one Advance is delivered by the next, so nothing arrives in the instant it was sent. A LinkPair is not safe for concurrent use.

func NewLinkPair

func NewLinkPair(first, second *Party, channelID string) (*LinkPair, error)

NewLinkPair gives each of the two parties a Link toward the other for the channel named channelID. Neither holds a channel yet: the first Advance has both ask for a handshake, and the pair settles on one.

func (*LinkPair) Advance

func (p *LinkPair) Advance(d time.Duration) LinkPairReport

Advance moves the clock forward by d: each end takes what the other sent before this call, then runs its timer if it is due.

func (*LinkPair) Close

func (p *LinkPair) Close()

Close destroys both Links.

func (*LinkPair) Restart

func (p *LinkPair) Restart(first bool) error

Restart replaces one end's Link with a new one, as a process restart does: that end has lost its channel and everything it had received, and the other end is told nothing.

func (*LinkPair) Send

func (p *LinkPair) Send(fromFirst bool, plaintext []byte) error

Send seals plaintext at one end for the other. It returns record.ErrNoChannel while that end has no channel: the application keeps the message and sends it when the channel is up.

func (*LinkPair) Settled

func (p *LinkPair) Settled() bool

Settled reports whether the two ends hold the same channel, one of them as its initiator, and neither has anything else in progress.

func (*LinkPair) StartRekey

func (p *LinkPair) StartRekey() error

StartRekey rekeys the current channel from the end that started it. It reads that end's status before it reserves a one-time prekey of the peer, as the documentation of package record says to ("Rekeys"): it returns an error wrapping record.ErrAttemptPending while a channel attempt of that end is in flight, and one matching record.ErrLinkState and record.ErrRekeyState while a rekey of the channel runs, with no prekey reserved for a handshake the Link would refuse. It returns an error wrapping record.ErrNoChannel when neither end holds a channel it started. The texts of these three begin "reference: " and name package record once. It seals the handshake's first record with Link.SealPurpose and passes Link.StartRekey the tag that call returned, not one read from the status.

func (*LinkPair) Status

func (p *LinkPair) Status() (first, second record.LinkStatus)

Status returns the Link status of each end, the first party's first.

type LinkPairReport

type LinkPairReport struct {

	// Delivered are the application plaintexts each end received, in order.
	Delivered [2][][]byte
	// Events are the changes each end's Link reported.
	Events [2][]record.LinkEvent
	// Hints counts the hints each end sent because it could not start a
	// handshake.
	Hints [2]int
	// Repeats counts the requests for a handshake that reached each end
	// while it was preparing one, and began no second preparation: the
	// same request asked again, with the Request of the preparation, or a
	// request the Link made since, which the preparation answers.
	Repeats [2]int
	// Stopped counts the preparations each end ended without reserving a
	// one-time prekey, because its Link did not want the handshake any
	// more when the fetch returned.
	Stopped [2]int
	// contains filtered or unexported fields
}

LinkPairReport is what one LinkPair.Advance observed at each end, the first party's values first.

type LinkReport

type LinkReport struct {

	// ToInitiator and ToResponder are the application plaintexts each
	// endpoint received, in order of delivery.
	ToInitiator, ToResponder [][]byte
	// InitiatorEvents and ResponderEvents are the rekey events each Driver
	// reported.
	InitiatorEvents, ResponderEvents []record.DriverEvent
	// Dropped counts records an endpoint refused, such as duplicates.
	Dropped int
	// NoChannel counts records that reached an endpoint which has no Driver
	// because it crashed. It is the only sign that endpoint has of a peer
	// still using the old channel.
	NoChannel int
	// contains filtered or unexported fields
}

LinkReport is what one DriverLink.Advance observed.

type Party

type Party struct {
	ID string
	// contains filtered or unexported fields
}

Party is one endpoint: an identity, a prekey.Manager backed by the illustrative authoritative store, and an explicit trusted-identity map. Not safe for concurrent use — a production runtime owns its own synchronization.

A reserved key whose handshake never arrives lingers in the local pool indefinitely; a production adapter needs a reservation-expiry or GC policy for orphaned one-time keys.

The backend implements both prekey.Backend and ake.OneTimePreKeyStore. Its monotonic tombstones are the rollback-sensitive state that prevents a restored private record from being honoured twice. Party itself does not implement the store, so holding a *Party never yields a private one-time key.

After Close, every error-returning operation except the idempotent Close reports ErrPartyClosed; accessors such as PublicIdentity and GroupKeyID return zero or empty values.

func NewParty

func NewParty(id string, dir *Directory) (*Party, error)

NewParty creates a party with a fresh identity. Call Publish before peers can initiate to it.

func (*Party) Close

func (p *Party) Close() error

Close scrubs the process-local manager, illustrative backend, identity, and group keys. It does not withdraw public directory records. Close first tries to settle a held replenishment or rotation and fails, leaving the Party open, while one remains. Repeating Close after success returns nil.

func (*Party) DropPreviousSignedPreKey

func (p *Party) DropPreviousSignedPreKey() error

DropPreviousSignedPreKey ends the rotation grace window, tombstones every remaining OTK bound to it, and scrubs the old private material as far as its implementation permits. A held replenishment is abandoned first (see Publish): the manager refuses to retire while one is outstanding.

func (*Party) Format

func (p *Party) Format(f fmt.State, _ rune)

Format writes "Party(…)" for every verb, as Cluster.Format writes its name, and nothing of the Party's state: not its group keys, its initial key, its identity or its prekeys.

func (*Party) GroupKeyID

func (p *Party) GroupKeyID() string

GroupKeyID returns the epoch of the group key this member currently holds (empty if none).

func (*Party) GroupOpen

func (p *Party) GroupOpen(m *GroupMessage) ([]byte, error)

GroupOpen decrypts a group message. It opens a message sealed under the member's current epoch, or one sealed under the eternal initial key (the recovery fallback). A message from any other epoch — for instance one sealed under a key rotated after this member left — does not open, which is what excludes a departed member from post-rotation traffic.

A replay guard rejects a group message this member has already opened (an exact resend is byte-identical). This bounds replay within the process; a production system needs a durable, bounded replay window (and typically a per-sender sequence number). See GroupSeal for the per-sender authentication scope.

func (*Party) GroupSeal

func (p *Party) GroupSeal(plaintext []byte) (*GroupMessage, error)

GroupSeal encrypts plaintext under a per-sender subkey of the member's current group epoch, binding the epoch id and the sender id as associated data.

NONCE BUDGET: the NIST SP 800-38D random-nonce bound (2^32 per key) applies across every instance sharing a key. Rather than share one epoch key across all members — which would aggregate every member's nonces into a single budget — each member seals under groupSenderKey(epochKey, epochID, memberID). Each sender thus has its own key, so the (key, nonce) domains are separated: two members reusing the same nonce bytes under their different derived keys is harmless, and only a single sender's own nonces contend for its budget. A production group layer still needs enforced epoch rotation and durable per-sender aggregate accounting; the reference enforces neither.

AUTHENTICATION SCOPE: the epoch key is symmetric and shared by every member, so every member can derive every other member's subkey. A successful GroupOpen therefore proves only that the sender held the selected epoch key, not which member sent it: the Sender field is a key selector, not an authenticated claim. A committed rotating epoch can support an application's current-membership policy, while the fallback key proves only past possession because every former member retains it. This layer provides group confidentiality and epoch-key-possession authentication, NOT per-sender authentication or non-repudiation. Attributing a message to an individual sender needs a per-sender signing key. The ExampleCluster_memberStatementSignatures example composes independent ake statement keys with this group layer: group encryption supplies confidentiality, while the statement signature supplies attribution.

func (*Party) GroupSealFallback

func (p *Party) GroupSealFallback(plaintext []byte) (*GroupMessage, error)

GroupSealFallback seals under the eternal initial key, which is derived from the cluster secret and shared by everyone who ever held it. It is the trust-root-level recovery channel: a member that has fallen behind the current epoch can always read it, so it is used to signal "the epoch advanced, recover now", not to carry roster-confidential data.

Because possession of the cluster secret is what defines membership in this model, anyone who ever joined — including a member that has since left the active roster — can read and produce fallback traffic. Do NOT put anything here that must stay confidential from former members; confidentiality from former members applies only to traffic sealed under a committed rotating epoch they do not hold (see Cluster). Old-epoch traffic from an unfenced straggler remains exposed to them, and true revocation requires rotating the cluster secret itself.

NONCE BUDGET: the initial key is never rotated, so even under the per-sender subkey derivation below, a single sender's random-96-bit-nonce budget spans the cluster's whole lifetime. This channel is acceptable only for low-volume recovery signalling; a production fallback needs enforced key rotation plus durable aggregate invocation accounting, not just "low volume."

func (*Party) OpenFrom

func (p *Party) OpenFrom(wire []byte) (senderID string, plaintext []byte, err error)

OpenFrom opens one wire-encoded ake.Envelope addressed to this party and returns the sender it authenticated and the plaintext. It keeps no state and needs none: the sender's signature covers the authenticated envelope content, so a change no trusted sender signed is refused before a one-time prekey is spent. That holds while every trusted sender has at least one uncompromised signing component. Another trusted sender that has the one-time prekey's public record can sign a changed copy in its own name and spend the key, as ake.Envelope describes. Another valid randomized signature witness over identical content is an equivalent delivery and may open first. A later copy is refused, its one-time prekey being spent.

func (*Party) PublicIdentity

func (p *Party) PublicIdentity() ake.PublicIdentity

PublicIdentity returns the party's public identity key.

func (*Party) Publish

func (p *Party) Publish(freshOTKs int) error

Publish creates the initial managed signed-prekey epoch, or replenishes the current epoch after it has been published. The backend atomically persists private records and replaces or extends the public directory inventory.

A publication whose backend result stays ambiguous after bounded retries leaves its prekey.Rotation held rather than dropped, and a later Publish first resumes that same Rotation. While it stays unsettled, Publish returns an error wrapping prekey.ErrRotationPending: the manager is busy, and the caller retries later rather than preparing anything new. A retry that publishes the held Rotation has completed the earlier request and returns without preparing another batch; Publish continues only when the held candidate was aborted instead.

A replenishment whose Commit fails is abandoned with Replenishment.Abort. The Party holds the batch from before Commit until that Abort succeeds, so a Commit that exits abnormally leaves it held rather than dropped, and the next Publish, RotateSignedPreKey, DropPreviousSignedPreKey, Restart or Close abandons it first. Either way a batch that did commit stays public.

func (*Party) Receive

func (p *Party) Receive(env *Envelope) ([]byte, error)

Receive completes the strict signed 4DH handshake and opens the envelope. Accept verifies the initiator signature, then atomically consumes and tombstones the OTK and scrubs its private half before returning; Open then confirms possession of the derived session key before plaintext is released. A failed Open still burns the one-time key, but the reference retains that PendingSession for a bounded time. A retransmission carrying the same authenticated content is routed directly back to PendingSession.Open rather than through Accept again, even when it has another valid randomized signature witness. Once that state expires, the sender needs a fresh handshake and OTK.

During a rotation grace window it selects the signed prekey the initiator named (msg.SignedPreKeyID) from the current and previous pairs, rather than trial-decrypting each; an unknown identifier is rejected.

An envelope naming an already tombstoned OTK — a duplicate delivery, or a key retired with its grace epoch — is refused as ake.ErrAuthentication unless its authenticated content digest names a retained failed-confirmation state. Accept deliberately does not reveal whether the id was consumed or never existed before authenticating the initiator.

func (*Party) ReplenishIfLow

func (p *Party) ReplenishIfLow(low, batch int) (replenished bool, err error)

ReplenishIfLow publishes a fresh batch when the directory's available one-time-key inventory drops below low — the low-watermark policy.

func (*Party) Restart

func (p *Party) Restart() error

Restart reconstructs the identity and prekey.Manager from the backend's authoritative state. It simulates a process restart while keeping this in-memory backend alive: volatile handshake fingerprints are lost, but OTK tombstones, the timestamp floor with the context and party kept beside it, completed replenishment IDs, and current and grace epochs survive. Record channels are independent process-lifetime objects and must be established again by the caller.

A held replenishment or rotation (see Publish) is settled first, and Restart refuses while either remains unsettled: a real restart loses the Rotation, so a durable backend must reconcile that candidate before RestoreManager. Restart also refuses restored state that prekey.RestoreManager rejects, such as a timestamp floor beyond the allowed clock skew (prekey.ErrEpochFuture); the Party then keeps its current state, where a real process would refuse to start.

func (*Party) RotateSignedPreKey

func (p *Party) RotateSignedPreKey() error

RotateSignedPreKey replaces the signed prekey and republishes, keeping the previous pair so in-flight handshakes against the old bundle still decrypt during the grace window (see Receive). Callers drop the previous pair on their own schedule via DropPreviousSignedPreKey.

The window MUST be time-bounded: until DropPreviousSignedPreKey runs, the old medium-term private stays in memory and every handshake made against the old bundle remains exposed to its compromise. While that grace epoch is retained, another rotation fails with prekey.ErrGraceActive.

A rotation left held by an earlier call is resumed instead of preparing a new one; RotateSignedPreKey returns nil once that earlier candidate publishes. A held replenishment is abandoned first (see Publish).

func (*Party) SealTo

func (p *Party) SealTo(recipientID string, plaintext []byte) ([]byte, error)

SealTo seals plaintext to recipientID as one self-contained ake.Envelope and returns its wire encoding. It fetches the recipient's bundle and reserves one of its one-time prekeys, as every handshake does, so it fails when the recipient's published inventory is used up. The result can wait in a queue for as long as the recipient's prekey state lasts; the recipient does not have to be running.

func (*Party) Send

func (p *Party) Send(recipientID string, plaintext []byte) (*Envelope, error)

Send fetches the recipient's bundle and reserves one of its one-time prekeys, verifies both against the explicitly trusted identity, performs the handshake, and seals plaintext into an Envelope. Strict v1 always requires a one-time prekey: Send fails when the directory has none available.

func (*Party) Trust

func (p *Party) Trust(peerID string, key ake.PublicIdentity) error

Trust configures the identity key expected for peerID. It is deliberately explicit: the untrusted Directory and an incoming message are never trust roots. Repeating the same binding is safe; changing an existing binding is refused so identity rotation requires an application-level policy.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL