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 (DriverLink) ¶
Example_driverLink runs two parties' record Drivers over an in-process link: data, a rekey started from a handshake marked as a rekey, and, after the responder restarts, a new pair from a handshake marked as a new channel. The application's part is the loop inside DriverLink.Advance: pass each record to Driver.Receive, send what it returns, call Driver.Tick.
package main
import (
"fmt"
"time"
"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(4); err != nil {
panic(err)
}
link, err := reference.EstablishDriverLink(alice, bob, "channel-7")
if err != nil {
panic(err)
}
defer link.Close()
step := func() reference.LinkReport {
report, err := link.Advance(time.Second)
if err != nil {
panic(err)
}
for _, payload := range report.ToResponder {
fmt.Printf("bob received %q\n", payload)
}
for _, event := range report.InitiatorEvents {
fmt.Println("alice:", event)
}
for _, event := range report.ResponderEvents {
fmt.Println("bob:", event)
}
return report
}
if err := link.Send(true, []byte("hello")); err != nil {
panic(err)
}
step()
if err := link.StartRekey(); err != nil {
panic(err)
}
for link.Rekeying() || link.InFlight() > 0 {
step()
}
epoch, _, _, _, err := link.Epochs()
if err != nil {
panic(err)
}
fmt.Println("epoch:", epoch)
if err := bob.Restart(); err != nil {
panic(err)
}
if err := link.Rebuild(); err != nil {
panic(err)
}
epoch, _, _, _, err = link.Epochs()
if err != nil {
panic(err)
}
fmt.Println("epoch after the rebuild:", epoch)
if err := link.Send(true, []byte("hello again")); err != nil {
panic(err)
}
step()
}
Output: bob received "hello" bob: rekey completed alice: rekey completed epoch: 1 epoch after the rebuild: 0 bob received "hello again"
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 ¶
- Constants
- Variables
- func EstablishConfirmedSessions(initiator, responder *Party, channelID string) (*ake.Session, *ake.Session, []byte, error)
- func EstablishRecordChannels(initiator, responder *Party, channelID string) (*record.Channel, *record.Channel, []byte, error)
- func RekeyRecordChannels(initiator, responder *Party, ...) (uint32, error)
- type AsyncRotator
- type Cluster
- func (c *Cluster) Directory() *Directory
- func (c *Cluster) Format(f fmt.State, _ rune)
- func (c *Cluster) Join(id string) (*Party, error)
- func (c *Cluster) Leave(id string) error
- func (c *Cluster) Member(id string) (*Party, bool)
- func (c *Cluster) Members() []string
- func (c *Cluster) NewAsyncRotator() *AsyncRotator
- func (c *Cluster) Recover(id string) error
- func (c *Cluster) RekeyExcluding(unreachable ...string) error
- type Delivery
- func (d *Delivery) Format(f fmt.State, _ rune)
- func (d *Delivery) Receive(now time.Time, frame []byte) (DeliveryOutput, error)
- func (d *Delivery) Send(now time.Time, message []byte) (DeliveryOutput, error)
- func (d *Delivery) SetLink(link *record.Link) error
- func (d *Delivery) Status() DeliveryStatus
- func (d *Delivery) Tick(now time.Time) (DeliveryOutput, error)
- func (d *Delivery) Wake() time.Time
- type DeliveryOptions
- type DeliveryOutput
- type DeliveryStall
- type DeliveryStatus
- type Directory
- type DriverLink
- func (l *DriverLink) Advance(d time.Duration) (LinkReport, error)
- func (l *DriverLink) Close()
- func (l *DriverLink) Crash(initiator bool)
- func (l *DriverLink) DropNextHandshake()
- func (l *DriverLink) Epochs() (initiatorSend, initiatorReceive, responderSend, responderReceive uint32, ...)
- func (l *DriverLink) InFlight() int
- func (l *DriverLink) InitiatorID() string
- func (l *DriverLink) Inject(toResponder bool, wire []byte)
- func (l *DriverLink) Rebuild() error
- func (l *DriverLink) Rekeying() bool
- func (l *DriverLink) Send(fromInitiator bool, plaintext []byte) error
- func (l *DriverLink) StartRekey() error
- type Envelope
- type GroupMessage
- type LinkPair
- func (p *LinkPair) Advance(d time.Duration) LinkPairReport
- func (p *LinkPair) Close()
- func (p *LinkPair) Restart(first bool) error
- func (p *LinkPair) Send(fromFirst bool, plaintext []byte) error
- func (p *LinkPair) Settled() bool
- func (p *LinkPair) StartRekey() error
- func (p *LinkPair) Status() (first, second record.LinkStatus)
- type LinkPairReport
- type LinkReport
- type Party
- func (p *Party) Close() error
- func (p *Party) DropPreviousSignedPreKey() error
- func (p *Party) Format(f fmt.State, _ rune)
- func (p *Party) GroupKeyID() string
- func (p *Party) GroupOpen(m *GroupMessage) ([]byte, error)
- func (p *Party) GroupSeal(plaintext []byte) (*GroupMessage, error)
- func (p *Party) GroupSealFallback(plaintext []byte) (*GroupMessage, error)
- func (p *Party) OpenFrom(wire []byte) (senderID string, plaintext []byte, err error)
- func (p *Party) PublicIdentity() ake.PublicIdentity
- func (p *Party) Publish(freshOTKs int) error
- func (p *Party) Receive(env *Envelope) ([]byte, error)
- func (p *Party) ReplenishIfLow(low, batch int) (replenished bool, err error)
- func (p *Party) Restart() error
- func (p *Party) RotateSignedPreKey() error
- func (p *Party) SealTo(recipientID string, plaintext []byte) ([]byte, error)
- func (p *Party) Send(recipientID string, plaintext []byte) (*Envelope, error)
- func (p *Party) Trust(peerID string, key ake.PublicIdentity) error
Examples ¶
- Package
- Package (Delivery)
- Package (DriverLink)
- Package (DuplicateDelivery)
- Package (Envelope)
- Package (GraceActive)
- Package (KeyMismatch)
- Package (LinkPair)
- Package (OneTimeKeySpent)
- Package (RecordChannel)
- Package (RecordDeliveryErrors)
- Package (RecordRekeyState)
- Package (SessionExports)
- Cluster (MemberStatementSignatures)
Constants ¶
const ( DriverResendInterval = time.Second DriverRekeyTimeout = 30 * time.Second )
Timing of the Drivers a DriverLink creates.
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.
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.
const GroupKeyLen = 32
GroupKeyLen is the size of the shared symmetric group key.
Variables ¶
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") )
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 ¶
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) Format ¶
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 ¶
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 ¶
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) NewAsyncRotator ¶
func (c *Cluster) NewAsyncRotator() *AsyncRotator
NewAsyncRotator returns a rotator over the cluster with default timings.
func (*Cluster) Recover ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 (*Delivery) SetLink ¶
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 ¶
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 (*Directory) FetchForHandshake ¶
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 ¶
OneTimeKeyCount reports the number of unreserved public OTK records.
type DriverLink ¶
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 ¶
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) 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 ¶
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) Restart ¶
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 ¶
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 ¶
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 ¶
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 ¶
NewParty creates a party with a fresh identity. Call Publish before peers can initiate to it.
func (*Party) Close ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ReplenishIfLow publishes a fresh batch when the directory's available one-time-key inventory drops below low — the low-watermark policy.
func (*Party) Restart ¶
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 ¶
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 ¶
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 ¶
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.