Skip to content

18 StakeShuffle Mixing

Note

Status: not consensus. Nothing in this chapter affects the validity of a block or transaction. A completed mix is an ordinary regular-tree transaction validated by the rules of Chapterย 7. StakeShuffle is nevertheless an interoperability protocol: a client that deviates from any byte layout, hash preimage, ordering or key-derivation step described here cannot complete a mix with dcrd and dcrwallet peers, and may be blamed and excluded as a disruptor. The chapter therefore uses MUST and SHOULD in their RFC 2119 sense for interoperability, and labels relay-node behavior as policy. No rule boxes appear in it.

StakeShuffle is Decredโ€™s peer-to-peer coin-mixing protocol. Wallets that wish to break the on-chain link between their coins and their future spending cooperate to build a single CoinJoin transaction in which every participant contributes inputs and receives one or more outputs of an identical, agreed value. The protocol makes sure that no participant, relay node or outside observer learns which participant owns which of the equal-valued outputs. It is an implementation of CoinShuffle++ [49], more precisely of DiceMix Light [50], a simpler protocol inspired by the DiceMix of that paper, in which a separate slot-reservation phase precedes an XOR DC-net. It is carried as eight new message types over the ordinary Decred peer-to-peer network (Chapterย 15), with no coordinating server. Full nodes relay the messages after checking them against a mixpool policy that resists denial of service.

The reference implementation is the mixing module of dcrd: the packages mixing (cryptographic primitives), mixing/mixclient (the participant state machine used by dcrwallet [22]), mixing/mixpool (the message pool used by both relays and wallets) and mixing/utxoproof, together with the message encodings in wire/msgmix*.go.

18.1 Overview

18.1.1 What is mixed

Each participant, called a peer in this chapter, contributes one or more unspent outputs it controls, asks for ๐‘šโ‰ฅ1 fresh outputs of the common mix amount (its message count), and may ask for one change output. The final transaction contains every peerโ€™s inputs, every peerโ€™s change output, and โˆ‘๐‘š outputs of exactly the mix amount, each paying a pay-to-pubkey-hash (P2PKH) script to a key freshly generated by its owner. Only the mixed outputs are anonymized: inputs and change are publicly linked to the peer that contributed them. Amounts are public; equality of the mixed outputs is what makes them indistinguishable.

dcrwallet uses mixing in two ways (informative): to mix ordinary funds into a โ€œmixedโ€ account in standard denominations, and in its ticket buyer, which mixes the outputs of the split transaction that funds ticket purchases (Chapterย 8) so that a ticket cannot be traced to the coins that paid for it. Both produce the same kind of CoinJoin; the denominations a wallet chooses are wallet policy and are not specified by dcrd, but peers can only mix together when their mix amounts are exactly equal (Sectionย 18.5).

18.1.2 Threat model and guarantees

The guarantees are those of CoinShuffle++ [49]:

  • Unlinkability. An adversary who controls the network and all but two of the peers of a successful run cannot tell which honest peer owns which honest mixed output with probability better than guessing. The anonymity set of an output is the set of honest peers in the final run. The adversary does learn the full set of inputs, change outputs and mixed outputs.
  • Termination. A malicious peer can force a run to fail, but every failure either identifies the misbehaving peers to all honest peers, publicly and verifiably, or is attributable to a timeout. The honest peers then rerun without them. The papers assume an honest bulletin board or reliable broadcast channel and at least two honest peers for termination; dcrd floods messages through the peer-to-peer network and gives up below MinPeers peers. With ๐‘“ disruptors, at most about ๐‘“+1 runs are needed, since every failed run excludes at least one of them; DiceMix Light states its cost as 4+3๐‘“ communication rounds [50].
  • No custody. Each peer signs only the final transaction, after checking that its own outputs are present. Nothing can be stolen.

Two departures from those designs strengthen it. Pairwise keys combine elliptic-curve Diffie-Hellman with the post-quantum key-encapsulation mechanism Streamlined NTRU Prime 4591761 [51], so that a future adversary able to break secp256k1 from a recorded transcript still faces the lattice scheme (โ€œIf sntrup4591761 is discovered to be broken in the future, the security only reduces to that of ECDHโ€, in the words of the source). And every peer commits, in its first session message, to all secrets it will ever need to reveal, so that blame assignment cannot be gamed by choosing secrets after the fact. DiceMix Light commits only to the messages to be mixed, through an additional DC-net over a group sent with the slot reservation; its other secrets follow deterministically from the key-exchange secret.

The protocol does not hide network-level metadata. Messages are flooded through the peer-to-peer network, so a node directly connected to a participant may infer that a message originated there; random delays (โ€œjitterโ€) on every message reduce, but do not remove, timing correlation. Reusing an address, or spending change together with mixed outputs, undoes the mix; that is wallet policy.

18.1.3 Protocol at a glance

Time is divided into epochs of fixed length (ten minutes on the main network). Between epoch boundaries, peers broadcast pair requests (PR) describing what they want to mix and proving that they own the inputs. At each epoch boundary every waiting peer independently collects the compatible pair requests it knows of, derives a session identifier from them, and runs the protocol of Tableย 18.1. A run is one attempt; if a run fails, the survivors start a new run, which in this implementation is always a new session with its own identifier.

Table 18.1. Messages of a StakeShuffle session, in protocol order
Abbr.CommandSent whenPurpose
PRmixpairreqbefore epochDescribe the requested mix, list inputs with ownership proofs; no session yet.
KEmixkeyxchgrun startFix the session (PR list and order), publish ECDH and KEM public keys and a commitment to all secrets.
CTmixcphrtxtafter all KEsOne KEM ciphertext to every peer (including self).
SRmixslotresafter all CTsSlot reservation: padded power sums over the field ๐”ฝ๐น.
FPmixfactpolywith DCRoots of the slot-reservation polynomial, published by peers able to factor it.
DCmixdcnetafter rootsXOR DC-net vectors carrying the 20-byte output hashes in their reserved slots.
CMmixconfirmafter DCThe CoinJoin with the senderโ€™s input signatures.
RSmixsecretson failureReveal the committed secrets for blame assignment.

18.2 Primitives and Notation

The following primitives are used. Byte strings, ||, le32, be64 and friends follow Chapterย 2; varint, varbytes and the transaction serialization follow Chapterย 4.

BLAKE-256
The 32-byte hash of Chapterย 3, written ๐ป(โ‹…). Every hash in this chapter is a single BLAKE-256, never the double hash.
HASH160
RIPEMD-160 of BLAKE-256, as defined in Chapterย 3.
secp256k1 and EC-Schnorr-DCRv0
The curve and the 64-byte Schnorr signature scheme of Chapterย 3. Public keys in mixing messages are 33-byte compressed SEC encodings.
Field

All slot-reservation arithmetic is in the prime field ๐”ฝ๐น, where

๐น=2127โˆ’1=170141183460469231731687303715884105727

(18.1)

(F, hexadecimal 7fff...ff, 16 bytes). โ€œ๐‘ฅmod๐นโ€ always denotes the non-negative residue. Field elements are serialized as minimal big-endian byte strings (no leading zero bytes; zero is the empty string) inside varbytes, at most MaxMixFieldValLen =32 bytes. A received value is parsed as an unsigned big-endian integer regardless of leading zeros.
ChaCha20 PRNG
PRNG(๐‘˜,๐‘›) is the keystream of the IETF ChaCha20 stream cipher [52] in the 96-bit-nonce, 32-bit-counter variant of RFC 8439 [53], with 32-byte key ๐‘˜, 12-byte nonce le32(n) || 00 00 00 00 00 00 00 00 and initial block counter 0. Reading โ„“ bytes returns the next โ„“ keystream bytes; reads are consecutive. mixing/internal/chacha20prng/prng.go ยท New
sntrup4591761
The key-encapsulation mechanism of Sectionย 18.2.1.

18.2.1 The sntrup4591761 KEM

The KEM is Streamlined NTRU Prime 4591761 as specified in the NTRU Prime paper [51], in the parameters of its August 2017 revision. dcrd uses a Go port of the reference C code of that paper, the package

and an implementation MUST be bit-compatible with it. Its parameters are ๐‘=761, ๐‘ž=4591 and ๐‘ก=143 (the schemeโ€™s own names; this ๐‘ is unrelated to the peer ๐‘ of later sections), so a t-small polynomial has exactly 2๐‘ก=286 non-zero coefficients in {โˆ’1,0,1}. Sizes are fixed:

Table 18.2. sntrup4591761 object sizes
ObjectBytesContent
Public key1218Encoding of โ„Ž=๐‘”/(3๐‘“) in โ„›๏ธ€/๐‘ž.
Private key1600Encode(f) (191) || Encode(1/g mod 3) (191) || public key (1218).
Ciphertext1047First 32 bytes of SHA-512(Encode(๐‘Ÿ)) (confirmation) || rounded encoding of โ„Ž๐‘Ÿ (1015).
Shared key32Last 32 bytes of SHA-512(Encode(๐‘Ÿ)).

Decapsulation reports failure unless the recovered ๐‘Ÿ has weight 286, its re-encryption equals the ciphertext and the confirmation matches.

Implementation pitfall

This is the 2017 โ€œsntrup4591761โ€ scheme, not the later NIST-submission โ€œsntrup761โ€ (whose keys and ciphertexts have different sizes and hashing). Implementations from current cryptographic libraries are not compatible.

Because blame assignment (Sectionย 18.8) recomputes another peerโ€™s keys and ciphertexts from its revealed seed, the consumption of randomness must be reproduced exactly, not only the scheme:

  • Each random 32-bit word is 4 bytes read from the source, interpreted as a little-endian int32.
  • Key generation: repeat { read 761 words ๐‘Ÿ๐‘– and set ๐‘”๐‘–=(((๐‘Ÿ๐‘–AND0x3fffffff)ร—3)โ‰ซ30)โˆ’1 } until ๐‘” is invertible modulo 3; then sample ๐‘“ as a t-small element (below).
  • Encapsulation: sample ๐‘Ÿ as a t-small element.
  • t-small sampling: read 761 words ๐‘ค๐‘–; for ๐‘–<286 set ๐‘ค๐‘–โ†๐‘ค๐‘–AND(โˆ’2), otherwise ๐‘ค๐‘–โ†(๐‘ค๐‘–AND(โˆ’3))OR1; reorder ๐‘ค with the libraryโ€™s fixed sorting network (Algorithmย 18.1, a port of the reference implementationโ€™s); set coefficient ๐‘– to (๐‘ค๐‘–AND3)โˆ’1.

Algorithm 18.1 ยท sntrup4591761 sorting network

def sort761(w, le):              # w: 761 int32 words; le: see pitfall
    n, top = 761, 1
    while top < n - top:
        top += top               # top = 512
    def minmax(i, j):            # exchange so that the "smaller" word is at i
        if le(w[j], w[i]):
            w[i], w[j] = w[j], w[i]
    p = top
    while p > 0:
        for i in range(n - p):
            if i & p == 0: minmax(i, i + p)
        q = top
        while q > p:
            for i in range(n - q):
                if i & p == 0: minmax(i + p, i + q)
            q >>= 1
        p >>= 1

dcrd: github.com/companyzero/sntrup4591761/zx/random.go ยท sort, minmax

Implementation pitfall

minmax evaluates Goโ€™s crypto/subtle.ConstantTimeLessOrEq(int(uint32(a)), int(uint32(b))), whose result for words of 231 or more depends on the Go release and the targetโ€™s int width:

  • Go 1.25 and earlier: le(a, b) is the sign bit of the wrapping 32-bit difference int32(a) - int32(b) - 1. This is not an order relation, and the result depends on the exact network above.
  • Go 1.26 and later, 64-bit targets: le(a, b) is uint32(a) <= uint32(b), so the network sorts the words into ascending unsigned order (any correct sort gives the same result).
  • Go 1.26 and later, 32-bit targets: int(uint32(a)) wraps, le(a, b) is int32(a) <= int32(b), and the words end up in ascending signed order.

The same seed therefore yields different sntrup4591761 public keys and ciphertexts in the three cases. This was observed with Go 1.24.13, 1.25.0 and 1.25.14 on amd64 (1.24.13 and 1.25.14 also on 386), Go 1.26.0, 1.26.11 and 1.27.4 on amd64, and Go 1.26.0, 1.26.11 and 1.27.4 on 386 (Sectionย 18.11); for 1000 random inputs the libraryโ€™s t-small output matched Algorithmย 18.1 with the comparison listed for each case every time. Normal mixing is unaffected, since any valid key pair works. In blame assignment, however, each peer recomputes the othersโ€™ public keys from their revealed seeds with its own build (Sectionย 18.8.4, step 1); when the two builds fall in different cases above, the recomputed key differs from the KEโ€™s and the verifier blames a peer that followed the protocol. A new implementation SHOULD use the unsigned comparison (ascending unsigned sort) of current 64-bit builds.

18.3 Identities, Hashes and Signatures

18.3.1 Ephemeral identities

Every mixing message carries the senderโ€™s identity: a 33-byte compressed secp256k1 public key generated freshly for each pair request and discarded after the mix. A peer MUST use a new identity for every pair request; the mixpool rejects a pair request from an identity that has already sent any message (Sectionย 18.9). All later messages of the peer in every session formed from that pair request are signed by the same identity.

18.3.2 Message hash

Each mixing message is identified by its message hash, the BLAKE-256 of its canonical serialization (the full payload of Sectionย 18.4, signature first). Message hashes are the inventory identifiers used for relay and the references in โ€œseenโ€ lists. They are always used in internal byte order, not reversed for display.

18.3.3 Signatures

Every message, including the pair request, is signed with EC-Schnorr-DCRv0 by the identity key. The signed digest binds the message contents, its type, its session and its run, using an ASCII domain-separation string.

Algorithm 18.2 ยท Mixing message signature digest

def signed_data_hash(msg) -> bytes:
    # varstring of the command with "-sig" appended (e.g. "mixkeyxchg-sig"),
    # then every field of the message except the leading 64-byte signature,
    # serialized exactly as on the wire
    label = (msg.command + "-sig").encode("ascii")
    return BLAKE256(varint(len(label)) + label + serialize_without_signature(msg))

def signature_digest(msg) -> bytes:
    sid, run = msg.session_id, msg.run
    if msg.command == "mixpairreq":          # has no session
        sid, run = bytes(32), 0
    s = (b"decred-mix-signature" + b"," + msg.command.encode("ascii") + b"," +
         hex_lower(sid) + b"," + str(run).encode("ascii") + b"," +
         hex_lower(signed_data_hash(msg)))
    return BLAKE256(s)

def sign(msg, priv):
    msg.signature = ec_schnorr_dcrv0_sign(priv, signature_digest(msg))   # 64 bytes

def verify(msg) -> bool:
    return (len(msg.identity) == 33 and parse_pubkey(msg.identity) is not None
            and parse_schnorr_sig(msg.signature) is not None
            and ec_schnorr_dcrv0_verify(msg.identity, signature_digest(msg),
                                        msg.signature))

dcrd: mixing/signatures.go ยท sign, verify, schnorrHash | wire/msgmix*.go ยท WriteSignedData

hex_lower is lowercase hexadecimal of the raw bytes (64 characters for 32 bytes), and the run is written in decimal without leading zeros. Because the session identifier and run are inside the digest, a signature cannot be replayed into another session even if the rest of a message were identical.

Note

dcrd signs with the deterministic nonce of its EC-Schnorr-DCRv0 implementation, which makes the signature vector of Sectionย 18.11 reproducible. Verifiers do not depend on how the nonce was chosen.

18.3.4 Transcript references

Every message after the pair request lists the hashes of the messages of the previous stage that the sender used: the KE lists the sessionโ€™s PRs (SeenPRs), the CT lists KEs, the SR lists CTs, the FP and DC list SRs, the CM lists DCs, and an RS lists RSs. Because the lists are inside the signed data, each message commits to the transcript its author saw. The reference implementation reads only two of them: the SeenPRs of a KE, which define the session (Algorithmย 18.4, Algorithmย 18.5), and the SeenSecrets of an RS, which are used for blame (Sectionย 18.8.4). For the CT, SR, FP, DC, CM and RS lists the mixpool checks only the number of entries (Tableย 18.16), and the client never inspects the hashes of the CT, SR, FP, DC and CM lists. The client fills these lists in unmixed order, except SeenSecrets, whose order is unspecified. An implementation SHOULD fill them exactly as described in Sectionย 18.7. mixing/mixpool/limits.go ยท checkCTLimits | mixing/mixclient/blame.go ยท blame

18.4 Wire Messages

The eight messages are valid only on connections that negotiated protocol version MixVersion =10 or later (Chapterย 15); decoding them at a lower version is an error. They are announced and requested with inventory vectors of type MSG_MIX =4 whose hash is the message hash. All integers are little-endian; โ€œhashโ€ fields are 32 raw bytes. Each table gives the payload of the message, which follows the common message header.

The messages share a prefix: the 64-byte Schnorr signature, the 33-byte identity, and (except in the PR) the 32-byte session ID and the 4-byte run number. Every message produced by the reference client carries run number 0, and the mixpool rejects any other value before all other checks (Sectionย 18.9.2). mixing/mixpool/mixpool.go ยท AcceptMessage

Table 18.3. mixpairreq (PR) payload
FieldTypeBytesDescription
Signature[64]byte64Signature (Algorithmย 18.2).
Identity[33]byte33Compressed public key of the ephemeral identity.
Expiryuint324Block height at which the PR expires (Sectionย 18.5.3).
MixAmountint648Value in atoms of each mixed output. Decoding fails if negative.
ScriptClassvarstring1+nScript class of mixed outputs; strict ASCII (bytes 0x20โ€“0x7e), ๐‘›โ‰ค32 (MaxMixPairReqScriptClassLen).
TxVersionuint162Version of the CoinJoin transaction.
LockTimeuint324Lock time of the CoinJoin transaction.
MessageCountuint324Number ๐‘š of mixed outputs requested.
InputValueint648Sum of the values of the contributed UTXOs. Decoding fails if negative.
UTXOCountvarint1โ€“3Number of contributed UTXOs, at most MaxMixPairReqUTXOs =512.
UTXOsMixPairReqUTXO[]varUTXOCount entries, Tableย 18.4.
HasChangeuint810: no change output; 1: a change output follows. Any other value fails decoding.
ChangeTxOutvarPresent only if HasChange is 1: value (int64, 8), script version (uint16, 2), public key script (varbytes), exactly as a transaction output (Chapterย 4).
Flagsbyte1Capability flags (Tableย 18.13).
PairingFlagsbyte1Pairing flags; part of the pairing description (Sectionย 18.5.2).
Table 18.4. MixPairReqUTXO (one contributed output)
FieldTypeBytesDescription
Hash[32]byte32Hash of the transaction containing the output.
Indexuint324Output index.
Treeint81Transaction tree (0 regular, 1 stake). Decoding fails if negative.
ScriptvarbytesvarRedeem script for P2SH outputs, at most 16384 bytes (MaxMixPairReqUTXOScriptLen). Relays reject a non-empty script (P2SH inputs are unsupported).
PubKeyvarbytesvarPublic key controlling the output, at most 33 bytes.
SignaturevarbytesvarUTXO ownership proof (Sectionย 18.5.4), at most 64 bytes.
Opcodebyte10 for a plain P2PKH output, or the stake opcode tagging the output script: OP_SSGEN (0xbb), OP_SSRTX (0xbc) or OP_TGEN (0xc3).
Table 18.5. mixkeyxchg (KE) payload
FieldTypeBytesDescription
Signature[64]byte64Signature.
Identity[33]byte33Sender identity.
SessionID[32]byte32Session identifier (Algorithmย 18.4).
Epochuint648Epoch of the session as Unix time in seconds.
Runuint324Run number; 0.
Posuint324Index of the senderโ€™s own PR in SeenPRs (its unmixed position).
ECDH[33]byte33Compressed secp256k1 public key for Diffie-Hellman.
PQPK[1218]byte1218sntrup4591761 public key.
Commitment[32]byte32Commitment to the senderโ€™s secrets (Sectionย 18.7.3).
SeenPRCountvarint1โ€“3Number of PR hashes, at most MaxMixPeers =512.
SeenPRs[32]byte[]32 eachHashes of the sessionโ€™s PRs in unmixed order (Sectionย 18.6.3).
Table 18.6. mixcphrtxt (CT) payload
FieldTypeBytesDescription
Signature[64]byte64Signature.
Identity[33]byte33Sender identity.
SessionID[32]byte32Session identifier.
Runuint324Run number; 0.
Countvarint1โ€“3Number ๐‘› of ciphertexts and of seen KE hashes (one count for both lists), at most 512. An encoder MUST NOT produce lists of different lengths.
Ciphertexts[1047]byte[]1047 each๐‘› sntrup4591761 ciphertexts; entry ๐‘˜ is encapsulated to the PQPK of the peer at unmixed position ๐‘˜.
SeenKeyExchanges[32]byte[]32 each๐‘› KE message hashes in unmixed order.
Table 18.7. mixslotres (SR) payload
FieldTypeBytesDescription
Signature[64]byte64Signature.
Identity[33]byte33Sender identity.
SessionID[32]byte32Session identifier.
Runuint324Run number; 0.
MCountvarint1โ€“3Outer dimension: the senderโ€™s message count ๐‘š; 1โ‰คMCountโ‰ค1024 (MaxMixMcount).
Widthvarint1โ€“3Inner dimension: the sessionโ€™s total message count ๐‘€; 1โ‰คWidthโ‰ค512 (MaxMixPeers, see the pitfall below).
DCMixvarbytes[][]varMCount rows of Width field elements (minimal big-endian, each at most 32 bytes), row-major. Row ๐‘— is the padded power-sum vector of the senderโ€™s ๐‘—-th message.
SeenCountvarint1โ€“3At most 512.
SeenCiphertexts[32]byte[]32 eachCT message hashes in unmixed order.

Implementation pitfall

The SR decoder bounds the inner dimension by MaxMixPeers =512, and the encoder refuses (with the error โ€œtoo many mixing peersโ€) to serialize an SR whose first row is longer than 512, although that dimension is the sessionโ€™s total message count ๐‘€, which the client allows up to MaxMtot =1024 (Sectionย 18.6.6) and the mixpool accepts up to 1024. In a session with ๐‘€>512, an SR is therefore accepted into the senderโ€™s own mixpool but cannot be written to any connection: a dcrd node that tries to send it closes that connection after the encoding error. An SR with such a width built by other software fails to decode at a dcrd receiver, which bans the sender for a malformed wire message. The reference client does not keep ๐‘€ at or below 512 when forming sessions. Clients SHOULD NOT form sessions with ๐‘€>512. wire/msgmixslotreserve.go ยท BtcDecode, writeMessageNoSignature | peer/peer.go ยท outHandler | server.go ยท OnRead
Table 18.8. mixfactpoly (FP) payload
FieldTypeBytesDescription
Signature[64]byte64Signature.
Identity[33]byte33Sender identity.
SessionID[32]byte32Session identifier.
Runuint324Run number; 0.
RootCountvarint1โ€“3At most 1024 (MaxMixMcount).
Rootsvarbytes[]varRoots of the slot-reservation polynomial in increasing numeric order, minimal big-endian, each at most 32 bytes.
SeenCountvarint1โ€“3At most 512.
SeenSlotReserves[32]byte[]32 eachSR message hashes in unmixed order.
Table 18.9. mixdcnet (DC) payload
FieldTypeBytesDescription
Signature[64]byte64Signature.
Identity[33]byte33Sender identity.
SessionID[32]byte32Session identifier.
Runuint324Run number; 0.
Xvarint1โ€“3Number of vectors (the senderโ€™s ๐‘š). If 0, the next two fields and the data are absent. Encoders MUST NOT send 0.
Yvarint1โ€“3Elements per vector (the sessionโ€™s ๐‘€). ๐‘‹โ‰ค1024 and ๐‘Œโ‰ค1024.
MsgSizevarint1Element size; MUST be 20 (MixMsgSize).
DCNet[20]byte[X][Y]20XYVector ๐‘—, element ๐‘˜, row-major.
SeenCountvarint1โ€“3At most 512.
SeenSlotReserves[32]byte[]32 eachSR message hashes in unmixed order.
Table 18.10. mixconfirm (CM) payload
FieldTypeBytesDescription
Signature[64]byte64Signature.
Identity[33]byte33Sender identity.
SessionID[32]byte32Session identifier.
Runuint324Run number; 0.
MixMsgTxvarThe CoinJoin transaction in full serialization (prefix and witness, Chapterย 4), with signature scripts present for the senderโ€™s own inputs.
SeenCountvarint1โ€“3At most 512.
SeenDCNets[32]byte[]32 eachDC message hashes in unmixed order.
Table 18.11. mixsecrets (RS) payload
FieldTypeBytesDescription
Signature[64]byte64Signature.
Identity[33]byte33Sender identity.
SessionID[32]byte32Session identifier.
Runuint324Run number; 0.
Seed[32]byte32The runโ€™s PRNG seed (Sectionย 18.7.2).
SRCountvarint1โ€“3At most 1024.
SlotReserveMsgsvarbytes[]varThe unpadded slot-reservation messages, minimal big-endian, each at most 32 bytes.
Nvarint1โ€“3Number of DC messages, at most 1024. If 0, MsgSize and data are absent.
MsgSizevarint1Present if ๐‘>0; MUST be 20.
DCNetMsgs[20]byte[N]20NThe unpadded DC-net messages (output key hashes).
SeenCountvarint1โ€“3At most 512.
SeenSecrets[32]byte[]32 eachHashes of RS messages of the session already seen (Sectionย 18.8.4).

All varints MUST be canonical (Chapterย 4). The decode-time bounds above come from wire; the mixpool applies tighter limits from the mixing package (Tableย 18.16), and the maximum payload lengths that the message framing enforces are listed in Tableย 18.12.

Table 18.12. Maximum payload lengths (protocol version 10 and later)
MessageMax payloadMessageMax payload
mixpairreq8476848mixfactpoly49291
mixkeyxchg17815mixdcnet20988047
mixcphrtxt552584mixconfirm1016520
mixslotres17318030mixsecrets70831
Table 18.13. Pair request capability flags
BitNameMeaning
0x01PRFlagCanSolveRootsThe peer can factor the slot-reservation polynomial and will publish FP messages (Sectionย 18.7.8).
othersReserved; ignored.

18.5 Pair Requests

A pair request announces a peerโ€™s wish to mix, binds its identity to the inputs it will spend and proves it can spend them. It is broadcast before the epoch in which the peer wants to mix and remains valid, possibly through several epochs, until it expires or its inputs are spent.

18.5.1 Field semantics

  • MixAmount is the value of every mixed output. MessageCount =๐‘š is the number of mixed outputs the peer receives.
  • ScriptClass MUST be P2PKH-secp256k1-v0 (ScriptClassP2PKHv0), the only class currently accepted: mixed outputs are version-0 P2PKH scripts 76 a9 14 <20-byte hash> 88 ac.
  • TxVersion and LockTime are copied into the CoinJoin. The reference client creates the CoinJoin with transaction version 1 and lock time 0.
  • InputValue is the total value of the UTXOs; Change is the optional change output, taken verbatim into the CoinJoin. The peerโ€™s fee contribution is InputValueโˆ’๐‘šโ‹…MixAmountโˆ’change value.
  • Expiry is a block height; see Sectionย 18.5.3.
  • Flags advertise capabilities (Tableย 18.13). A client sets PRFlagCanSolveRoots only if a root solver is available to it.
  • PairingFlags select the protocol variant: the reference client uses pairingVersion =3 on every network except the test network, where it uses pairingVersionTestnet =4. A client MUST use the same value to pair with reference peers.

18.5.2 Pairing description

Two pair requests are compatible, and can be mixed together, exactly when their pairing descriptions are byte-identical. The description is

pairing=le64(MixAmount)โ€–varstring(ScriptClass)โ€–le16(TxVersion)โ€–le32(LockTime)โ€–PairingFlags

(18.2)

(one byte for the flags). wire/msgmixpairreq.go ยท Pairing

18.5.3 Expiry

With โ„Ž the height of the current chain tip, a pair request is acceptable only if โ„Ž<Expiryโ‰คMaxExpiry(โ„Ž), where

MaxExpiry(โ„Ž)=โ„Ž+โŒŠ60minTargetTimePerBlockโŒ‹+1,

(18.3)

that is โ„Ž+13 on the main network (5-minute blocks), โ„Ž+31 on the test network and โ„Ž+3601 on the simulation and regression networks. mixing/expiry.go ยท MaxExpiry The reference client signs ownership proofs for, and sets, an expiry chosen by the wallet within this window; dcrwallet uses MaxExpiry(โ„Ž)โˆ’2. Every session formed from a PR inherits the earliest expiry of its known PRs (Sectionย 18.9.4).

18.5.4 UTXO ownership proofs

Each contributed UTXO carries a proof that the peer holds the private key controlling it. The proof is an EC-Schnorr-DCRv0 signature over a digest that commits to the PRโ€™s expiry and to the public key. The source states its purpose as preventing the proofโ€™s inclusion in other pair requests signed by an unrelated identity. Together with the mixpool rule that a PR may claim an outpoint already claimed by an accepted PR only with a strictly later expiry (Sectionย 18.9.2), a copied proof, valid only for the original expiry, cannot displace the ownerโ€™s PR at a node that already holds it.

Algorithm 18.3 ยท UTXO ownership proof

PREAMBLE = b"mixpr-utxoproof,P2PKH(EC-Schnorr-DCRv0),"   # tag "," scheme ","

def utxo_proof_digest(pubkey: bytes, expiry: uint32) -> bytes:
    return BLAKE256(PREAMBLE + be32(expiry) + pubkey)     # no separator after expiry

def sign_utxo_proof(priv, expiry):
    pub = compressed_pubkey(priv)                         # 33 bytes
    return pub, ec_schnorr_dcrv0_sign(priv, utxo_proof_digest(pub, expiry))

def check_utxo(utxo, prev_pk_script, expiry) -> bool:
    # prev_pk_script: the script of the referenced output, script version 0
    if utxo.opcode == 0:          h = extract_p2pkh_v0(prev_pk_script)
    elif utxo.opcode == OP_SSGEN: h = extract_stakegen_p2pkh_v0(prev_pk_script)
    elif utxo.opcode == OP_SSRTX: h = extract_stakerevoke_p2pkh_v0(prev_pk_script)
    elif utxo.opcode == OP_TGEN:  h = extract_treasurygen_p2pkh_v0(prev_pk_script)
    else: return False
    return (h is not None and HASH160(utxo.pubkey) == h
            and ec_schnorr_dcrv0_verify(utxo.pubkey,
                                        utxo_proof_digest(utxo.pubkey, expiry),
                                        utxo.signature))

dcrd: mixing/utxoproof/utxoproof.go ยท SignUtxoProof, ValidateSecp256k1P2PKH

The expiry is written big-endian, unlike the wire fields. The supported output types are version-0 P2PKH outputs and the version-0 P2PKH forms of vote, revocation and treasury-generation outputs tagged with OP_SSGEN, OP_SSRTX and OP_TGEN (Chapterย 6). P2SH outputs are not supported: the Script field MUST be empty. A client sets Opcode to the first byte of the previous output script when that byte is one of the three stake opcodes, and to 0 otherwise.

18.5.5 Fee and dust policy

Relays enforce a minimum and maximum fee contribution per PR so that the CoinJoin passes default mempool policy (Chapterย 17). The fee rate is feeRate =10000 atoms per kilobyte. The size of the peerโ€™s share of the transaction is estimated as if every input redeemed a P2PKH output with a 108-byte signature script and every output were a P2PKH output:

size(๐‘›in,๐‘›out,๐‘)=12+2โ‹…varintlen(๐‘›in)+varintlen(๐‘›out+๐‘)+166๐‘›in+36(๐‘›out+๐‘)

(18.4)

where ๐‘›in is the UTXO count, ๐‘›out=๐‘š, ๐‘โˆˆ{0,1} indicates a change output, and 166 and 36 are the estimated sizes of one input and one P2PKH output. With fee(๐‘ )=โŒŠ10000โ‹…๐‘ /1000โŒ‹ (but at least 10000 if that is 0, and clamped to 21ร—1014), the contributed fee must satisfy fee(size)โ‰คcontributedโ‰คfee(10000โ‹…size). mixing/mixpool/mixpool.go ยท checkFee, estimateP2PKHv0SerializeSize

An output is dust if โŒŠ๐‘ฃโ‹…1000/(3โ‹…201)โŒ‹<10000, where 201 is the estimated cost in bytes of creating and later spending a P2PKH output (8+2+1+25+165). The smallest non-dust value is therefore 6030 atoms. The mix amount and any change value are checked with this formula (the change with the P2PKH size, whatever its actual script). The product ๐‘ฃโ‹…1000 is computed in signed 64-bit arithmetic and wraps for ๐‘ฃ>9223372036854775, far above the money supply. mixing/mixpool/mixpool.go ยท isDustAmount

18.6 Epochs and Session Formation

18.6.1 Epochs

An epoch boundary is a Unix time that is a multiple of the epoch duration ๐ธ: 600 seconds on the main, simulation and regression networks, and 180 seconds on the test network (test network 3). The duration is hard-coded in the mixpool (10 minutes, replaced by 3 minutes when the network is test network 3), not a chain parameter; the client in turn selects the test-network stage timeout and pairing version by checking whether the mixpoolโ€™s epoch is 3 minutes. The value of an epoch is that boundary in seconds. mixing/mixpool/mixpool.go ยท NewPool | mixing/mixclient/client.go ยท NewClient

Clients SHOULD publish their pair request at a random time well away from the boundaries, so that publication time does not link a PR to its owner and so that all peers know all PRs before the tick. The reference client, with the next boundary at ๐‘‡, stage timeout ๐œ (Tableย 18.14) and maximum jitter ๐‘—max=๐œ/10, publishes at

๐‘ก=now+๐‘‘๐‘+๐‘ˆ[0,300ms)+๐‘ˆ[0,๐‘‡โˆ’๐œโˆ’๐‘—maxโˆ’now)

(18.5)

if now<๐‘‡โˆ’๐œโˆ’๐‘—max, and otherwise waits until ๐‘‡+๐œ and then adds ๐‘‘๐‘+๐‘ˆ[0,300ms)+๐‘ˆ[0,๐‘‡+๐ธโˆ’๐œโˆ’๐‘—maxโˆ’now). Here ๐‘‘๐‘ is a per-identity delay drawn once from ๐‘ˆ[0,๐‘—maxโˆ’300ms) and added to every message the peer sends. mixing/mixclient/client.go ยท prDelay, msgJitter

18.6.2 Choosing the participants

At each epoch boundary ๐‘‡, a client with waiting local pair requests, for each distinct pairing description, takes the set of PRs in its mixpool with that description, as follows.

  1. Before anything else, prune the mixpool: remove every session for which a CM from each of its PRs has been seen, together with those PRs, and remove every PR and every session whose expiry is at or below the height most recently reported to the client by its wallet when a block was attached to the main chain (0, so no height expiry, until the first such block after the client started). This is immediate, unlike the delayed expiry dcrd performs (Sectionย 18.9.4), and it runs at every epoch boundary after the first, whether or not local pair requests are waiting.
  2. Take all PRs with the pairing description.
  3. Sort them by decreasing expiry and drop any PR that spends an outpoint also spent by a PR with a strictly greater expiry (a peer replaces a PR by broadcasting one with a later expiry).
  4. Drop PRs that spend outputs with two or more misbehavior strikes (Sectionย 18.9.5).
  5. If more than 512 remain, keep the local peersโ€™ PRs and then the others in increasing hash order, up to 512.

mixing/mixclient/client.go ยท epochTicker, expireMessages | mixing/mixpool/mixpool.go ยท RemoveConfirmedSessions, ExpireMessages, CompatiblePRs, Observer.ExcludePRs

Different peers may see different PR sets; the session-agreement procedure of Sectionย 18.6.5 resolves that. A client that omits the pruning of step 1 keeps PRs that reference clients have already dropped, derives a different session ID from them in its first attempt, and reaches a common session only through that procedure. The reference peersโ€™ first attempt fails as well, because they wait for a KE carrying their own session ID from every PR, so one such client costs every peer of the pairing a KE timeout and an alternate-session round.

18.6.3 Session identifier and unmixed order

The session identifier commits to the exact set of PRs and to the epoch. The unmixed order of the peers, which fixes each peerโ€™s index in every vector of the run, is the order of the PR hashes after XOR with the session ID, which is pseudorandom and not under any peerโ€™s control.

Algorithm 18.4 ยท Session ID and unmixed order

def session_id(pr_hashes: list[bytes], epoch: uint64) -> bytes:
    h = sorted(pr_hashes)                      # bytewise lexicographic, ascending
    return BLAKE256(b"decred-mix-session" + be64(epoch) + b"".join(h))

def form_session(prs, epoch):
    sid = session_id([pr.hash for pr in prs], epoch)
    ordered = sorted(prs, key=lambda pr: xor(pr.hash, sid))   # ascending
    return sid, ordered       # ordered[k] is the peer at unmixed position k

def validate_session(ke) -> bool:                 # checked for every KE
    x = [xor(h, ke.session_id) for h in ke.seen_prs]
    if any(x[k] < x[k - 1] for k in range(1, len(x))):
        return False                              # not in unmixed order
    if ke.run == 0 and session_id(ke.seen_prs, ke.epoch) != ke.session_id:
        return False
    return True

dcrd: mixing/sid.go ยท deriveSessionID, SortPRsForSession, ValidateSession

The epoch is serialized big-endian in the session-ID preimage. For a peer, Pos is its index in the ordered list, ๐‘š๐‘˜ the message count of the peer at position ๐‘˜, ๐‘€=โˆ‘๐‘˜๐‘š๐‘˜ the sessionโ€™s total message count, and ๐‘ ๐‘˜=โˆ‘๐‘–<๐‘˜๐‘š๐‘– the global index of the first message of peer ๐‘˜. Messages are numbered 0..๐‘€โˆ’1 in this order everywhere below.

18.6.4 Minimum participation

A client always broadcasts its KE for the session it formed, even when the session cannot proceed, so that other peers can fetch PRs they are missing. It does not proceed past the KE unless the session has at least MinPeers =4 PRs and at least one PR has PRFlagCanSolveRoots set. mixing/mixclient/client.go ยท run

The KE also shows that the peer is still present. When its pairing attempt for the epoch ends, the reference client removes from its own mixpool the PR of every identity that an alternate-session computation of that epoch (Algorithmย 18.5) found unresponsive, that is, from which the mixpool holds no KE for that epoch. A computation contributes to this list only if it found an alternate session that differs from the one attempted, and the removal happens only if at least MinPeers identities of that pairing description have a most recent KE of that epoch. The client applies a similar test once, shortly after the KE deadline of the first epoch boundary following its start, to the PRs it held at start: every such PR with no KE of that epoch is a candidate, without the alternate-session condition, and the client stops at the first pairing description with fewer than MinPeers such KEs, in unspecified order, so silent PRs of other pairings may or may not be removed. A removed PR is not paired again unless it is received anew. A peer with a pending PR therefore SHOULD send a KE at every epoch boundary, and an implementation that never removes silent PRs keeps forming initial sessions that reference clients do not form. mixing/mixclient/client.go ยท removeUnresponsiveDuringEpoch, pairSession, epochTicker | mixing/mixpool/mixpool.go ยท RemoveUnresponsiveDuringEpoch

18.6.5 Session agreement

After sending its KE, a peer waits until the KE deadline (Tableย 18.14) for a KE from every PR of the session, where โ€œthe sessionโ€ is any of the session attempts made so far in this epoch since the last point of agreement; if one of them completes it is used. If none completes and the peers have not yet reached agreement in this epoch, the peer computes an alternate session from the KEs it has received, which are evidence of what PR sets the other peers saw. If none completes after agreement was reached, the pairing is abandoned for the epoch.

Algorithm 18.5 ยท Alternate session

def alternate_session(prs, latest_ke, epoch):
    # prs: PRs of the failed attempt; latest_ke[id]: the KE most recently
    # accepted from identity id, present only if that KE has this epoch
    # (an older KE of the epoch is not used)
    by_hash = {pr.hash: pr for pr in prs}
    resp = {pr.identity: (pr, latest_ke[pr.identity])
            for pr in prs if pr.identity in latest_ke}
    silent = {pr.hash for pr in prs if pr.identity not in latest_ke}
    count = {}
    for pr, ke in resp.values():
        for h in ke.seen_prs:
            if h != pr.hash and h not in silent:        # self-references excluded
                count[h] = count.get(h, 0) + 1
    need = len(count) // 2
    rem = [h for h in count if count[h] >= need]
    while True:
        if len(rem) < MIN_PEERS:
            fail("too few peers")
        rem.sort(key=lambda h: (count[h], h))          # fewest sightings first
        if count[rem[0]] == len(rem) - 1:              # everyone saw everyone
            if any(h not in by_hash for h in rem):
                fail("agreement reached on PRs unknown locally")
            return form_session([by_hash[h] for h in rem], epoch)
        rem = rem[1:]                                   # drop least-seen PR
        count = {h: 0 for h in rem}
        for h in rem:
            if h in by_hash and by_hash[h].identity in resp:
                for s in resp[by_hash[h].identity][1].seen_prs:
                    if s != h and s in count:
                        count[s] += 1

dcrd: mixing/mixclient/client.go ยท alternateSession

If the alternate session differs from the current attempt, the peer starts a new attempt with it (fresh KE, same keys and secrets), restarting the stage deadlines from the current time; if it is identical, agreement is assumed to have been reached and the attempt is waited for again with restarted deadlines. If the computation fails (too few peers, or agreement on PRs unknown locally), the peer restarts the deadlines and keeps waiting for KEs of the attempts made so far. Each outcome is counted per resulting session identifier, all failures counting as one outcome; the third occurrence of the same outcome in an epoch abandons the pairing for that epoch. All of this happens within the epoch: the client abandons the pairing attempt when the next epoch begins. mixing/mixclient/client.go ยท pairSession

Figureย 18.1 summarizes the procedure.

Figure 18.1. Session agreement within one epoch. Every outcome of the alternate session restarts the stage deadlines and returns to the wait; the third occurrence of the same outcome in an epoch abandons the pairing, as does the start of the next epoch.

18.6.6 Size limits

When all KEs of a session have arrived and agreement has not yet been recorded in the epoch (agreement recorded because an alternate session reproduced the current attempt, Sectionย 18.6.5, skips this check), each peer checks the session against the mixing limits of Tableย 18.16, walking the PRs in unmixed order and excluding a PR if adding it would exceed 64 peers, a total of 1024 messages, or an estimated CoinJoin size of 100000 bytes. The size estimate is 12+2โ‹…varintlen(๐‘›in)+varintlen(๐‘›out)+166๐‘›in+โˆ‘outputs(10+varintlen(โ„“)+โ„“) over all inputs and outputs so far, with โ„“=25 for each mixed output and the actual script length for each change output; a PR is excluded when the estimate is โ‰ฅ100000. If any PR is excluded, the remaining PRs form a new session (Algorithmย 18.4) and the run restarts with it, provided at least four remain. mixing/mixclient/client.go ยท run, coinjoinSize.join

18.6.7 Runs and reruns

CoinShuffle++ numbers successive runs of a session. In dcrd every run is instead a fresh session: whenever peers are excluded (blame, timeout, size limits, disagreement), the remaining PRs are re-sorted with Algorithmย 18.4 using the same epoch value, giving a new session ID, and every message of the new attempt carries run number 0. Relays reject any message whose run number is not 0. The Epoch field of every KE in the epoch is the original epoch value, and relays accept KEs only up to 20 minutes after it (Sectionย 18.9.2), which bounds the time available for reruns.

18.7 The Protocol Run

This section describes one run of a session with peers 0..๐‘›โˆ’1 in unmixed order. โ€œPeer ๐‘˜โ€ refers to unmixed positions, โ€œmessage ๐‘”โ€ to global message indices.

18.7.1 Deadlines

Each run has a start time ๐‘‡0: the epoch boundary for the first attempt of an epoch, and the current time when a rerun is started. All deadlines are relative to it:

Table 18.14. Stage deadlines of a run (๐œ = 30 s on the main, simulation and regression networks, 10 s on the test network)
DeadlineTimeBy then
KE๐‘‡0+๐œAll KEs of the session received.
CT๐‘‡0+2๐œAll CTs received.
SR๐‘‡0+3๐œAll SRs received. (A peer that cannot solve roots starts waiting for a valid FP as soon as it has all SRs; Sectionย 18.7.8.)
DC๐‘‡0+4๐œAll DCs (and FPs, sent together with them) received.
DC-RS๐‘‡0+5๐œWait for secrets revealed after the DC stage; CMs are not sent before this time.
CM๐‘‡0+6๐œAll CMs received.

mixing/mixclient/client.go ยท deadlines.start, timeoutDuration

Figure 18.2. Stages of one run. Each band names the messages that are due by the deadline at its right edge (Tableย 18.14).

Each message is sent after the senderโ€™s per-identity delay ๐‘‘๐‘ plus a fresh ๐‘ˆ[0,300ms), and is due by the deadline of its stage. A peer that has not received a message of the current stage from some peer by the deadline treats that peer as having timed out (Sectionย 18.8.2).

18.7.2 Key generation and commitment

For every run in which it must generate fresh secrets (the first run of a PR, and every run after secrets were revealed), a peer:

  1. Draws a uniformly random 32-byte seed and sets ๐‘ƒ=PRNG(seed,0).
  2. Derives its secp256k1 Diffie-Hellman key pair from ๐‘ƒ: read 32 bytes, interpret them as a big-endian integer, and repeat until the value is in [1,๐‘โˆ’1] (๐‘ the group order).
  3. Derives its sntrup4591761 key pair from the continuation of ๐‘ƒ, consuming randomness as specified in Sectionย 18.2.1.
  4. Draws ๐‘š slot-reservation messages ๐‘Ÿ0..๐‘Ÿ๐‘šโˆ’1 uniformly from [0,๐น) with a system random source (not from ๐‘ƒ).
  5. Generates ๐‘š fresh secp256k1 keys in its wallet and takes their HASH160s ๐‘‘0..๐‘‘๐‘šโˆ’1 as its DC-net messages; these are the 20-byte hashes of the mixed outputs it will receive.

The state of ๐‘ƒ after step 3 is kept: the encapsulations of the CT stage continue reading from it. mixing/mixclient/client.go ยท genDicemixKeys | mixing/keyagreement.go ยท NewKX

Implementation pitfall

Blame verification (Sectionย 18.8.4, step 2) recomputes a peerโ€™s CT ciphertexts by encapsulating from the state of ๐‘ƒ immediately after key generation. The reference client keeps a single ๐‘ƒ per secret generation and continues it, without rewinding, whenever it reuses secrets: in a rerun after a timeout or an observable-misbehavior exclusion, and in a session of a later epoch for a pair request whose earlier session ended without a reveal (the peer state is cloned with the same PRNG object). A peer that already encapsulated in an earlier run therefore encapsulates the new CT from an advanced state, and if secrets are revealed in that run it fails step 2 and is blamed although it followed the protocol. Driving dcrdโ€™s client with six local peers, one withholding its CT (CT timeout, rerun of five peers reusing secrets) and then one flipping a bit of its SR in the rerun, blame assignment blamed all five peers for ciphertexts that differ from the recomputation, and the session was abandoned. A new implementation SHOULD generate fresh secrets for every run, which protects its own messages; it cannot prevent dcrd peers of the same run from being blamed this way. mixing/mixclient/client.go ยท cloneLocalPeer, excludeBlamed, epochTicker

18.7.3 The commitment

The KEโ€™s Commitment is the message hash of the RS message the peer would publish for this session, computed with the signature set to 64 zero bytes and an empty SeenSecrets list:

Commitment=๐ป(064โ€–Identityโ€–SessionIDโ€–le32(0)โ€–Seedโ€–SR-listโ€–DC-listโ€–varint(0))

(18.6)

where the SR list and DC list are serialized as in Tableย 18.11 (the SR messages minimal big-endian). wire/msgmixsecrets.go ยท Commitment

18.7.4 Key exchange (KE)

The peer sends a KE with the session ID, the epoch, run 0, Pos set to its unmixed position, its ECDH public key (compressed), its sntrup4591761 public key, the commitment, and SeenPRs set to all PR hashes of the session in unmixed order. The session ID, epoch and SeenPRs must satisfy Algorithmย 18.4. When all ๐‘› KEs have arrived (Sectionย 18.6.5), every peer parses every ECDH key; a KE whose key does not parse is observable misbehavior (Tableย 18.15).

18.7.5 Ciphertexts (CT)

Peer ๐‘ encapsulates once to the sntrup4591761 public key of every peer ๐‘˜=0..๐‘›โˆ’1 including itself, in increasing ๐‘˜, using the continuation of its PRNG ๐‘ƒ as the randomness source, obtaining ciphertext ๐‘๐‘,๐‘˜ and cleartext key ๐‘’๐‘,๐‘˜. It sends a CT whose Ciphertexts list is ๐‘๐‘,0..๐‘๐‘,๐‘›โˆ’1 and whose SeenKeyExchanges lists the KE hashes in unmixed order. mixing/keyagreement.go ยท KX.Encapsulate

18.7.6 Shared keys

On receiving all CTs, peer ๐‘ checks that each lists exactly ๐‘› ciphertexts (otherwise the sender is excluded, Tableย 18.15) and decapsulates the ciphertext ๐‘๐‘˜,๐‘ addressed to it by each peer ๐‘˜. A pairwise 32-byte key between peers ๐‘ and ๐‘˜ is

๐พ๐‘,๐‘˜=๐ป(ECDH๐‘ฅ(๐‘,๐‘˜))โŠ•๐‘’๐‘˜,๐‘โŠ•๐‘’๐‘,๐‘˜(๐‘˜โ‰ ๐‘),๐พ๐‘,๐‘=๐ป(ECDH๐‘ฅ(๐‘,๐‘))โŠ•๐‘’๐‘,๐‘

(18.7)

where ECDH๐‘ฅ(๐‘,๐‘˜) is the 32-byte big-endian ๐‘ฅ coordinate of ๐‘Ž๐‘โ‹…๐ด๐‘˜ for ๐‘โ€™s ECDH private key ๐‘Ž๐‘ and ๐‘˜โ€™s ECDH public key ๐ด๐‘˜. ๐พ๐‘,๐‘˜=๐พ๐‘˜,๐‘. From the pairwise keys, a separate PRNG is derived for every pair of messages, giving a 32-byte slot-reservation secret and an ๐‘€-element XOR pad.

Algorithm 18.6 ยท Pairwise message secrets

def shared_secrets(p, mcounts, sid, kx, ecdh_pub, ct_to_me):
    # p: own unmixed position; ct_to_me[k]: CT_k.ciphertexts[p]
    M = sum(mcounts)
    sr = [[None] * M for _ in range(mcounts[p])]   # sr[i][g]: 32 bytes
    dc = [[None] * M for _ in range(mcounts[p])]   # dc[i][g]: M x 20 bytes
    for i in range(mcounts[p]):                     # own message index
        g = 0                                       # global index of the other message
        for k in range(len(mcounts)):
            if k == p and mcounts[p] == 1:
                g += 1
                continue
            key = BLAKE256(ecdh_x(kx.ecdh_priv, ecdh_pub[k]))
            e_in = sntrup_decapsulate(ct_to_me[k], kx.pq_priv)
            if e_in is None:
                raise DecapsulateError(k)           # triggers blame
            key = xor(key, e_in)
            if k != p:
                key = xor(key, kx.cleartext[k])     # the key p encapsulated to k
            for j in range(mcounts[k]):
                if k == p and j == i:
                    g += 1
                    continue
                if p < k or (p == k and j < i):
                    counter, nonce = i, j           # lower peer's index is the counter
                else:
                    counter, nonce = j, i
                seed = BLAKE256(sid + key + le32(counter))
                rng = PRNG(seed, nonce)
                sr[i][g] = rng.read(32)
                dc[i][g] = [rng.read(20) for _ in range(M)]
                g += 1
    return sr, dc

dcrd: mixing/keyagreement.go ยท KX.SharedSecrets

For own message ๐‘– (global index ๐‘ ๐‘+๐‘–), entry ๐‘” is the secret shared with message ๐‘”; the entry for the messageโ€™s own index is unused. The two holders of a message pair derive the same seed and nonce: the counter is always the message index of the lower-positioned peer (for two messages of the same peer, the larger index), and the nonce the other index.

18.7.7 Slot reservation (SR)

Slot reservation lets the peers agree on a random permutation of the ๐‘€ messages without revealing who owns which position. Each message ๐‘” is represented by its random field element ๐‘Ÿ, and the peers jointly compute, with a DC-net [54] over ๐”ฝ๐น, the power sums ๐‘†๐‘ก=โˆ‘๐‘”๐‘Ÿ๐‘”๐‘กmod๐น for ๐‘ก=1..๐‘€, from which the set {๐‘Ÿ๐‘”} (but not the owners) can be recovered.

Algorithm 18.7 ยท Slot-reservation pads and mix

def sr_pads(kp: list[bytes], my: int, M: int) -> list[int]:
    # kp[g]: 32-byte SR secret shared with message g; my: own global index
    pads = []
    for t in range(M):
        acc = 0
        for g in range(M):
            if g == my:
                continue
            d = int.from_bytes(BLAKE256(kp[g] + le64(t + 1)), "big")   # 256-bit
            acc = acc + d if my > g else acc - d
        pads.append(acc % F)          # non-negative residue
    return pads

def sr_mix(r: int, pads: list[int]) -> list[int]:
    return [(pow(r, t + 1) + pads[t]) % F for t in range(len(pads))]

dcrd: mixing/dcnet.go ยท SRMixPads, SRMix

For its ๐‘–-th message, peer ๐‘ computes sr_mix(r_i, sr_pads(sr[i], s_p + i, M)) and sends the ๐‘š resulting rows as the SRโ€™s DCMix matrix (๐‘š rows of width ๐‘€), with SeenCiphertexts listing the CT hashes in unmixed order. Every pad term appears once with each sign across the session, so pads cancel in the sum.

On receiving all SRs, each peer checks that the SR of peer ๐‘˜ has exactly ๐‘š๐‘˜ rows of width ๐‘€ (otherwise the sender is excluded), concatenates all rows in unmixed order and adds them element-wise modulo ๐น, giving ๐‘†1..๐‘†๐‘€. The polynomial whose roots are the messages is built with Newtonโ€™s identities:

Algorithm 18.8 ยท Slot-reservation polynomial coefficients

def coefficients(S: list[int]) -> list[int]:
    # S[t] = sum of r^(t+1); returns a[0..M] of phi(x) = sum a[i] x^i (mod F)
    M = len(S)
    a = [0] * (M + 1)
    a[M] = F - 1                                   # -1
    for i in range(M):
        acc = sum(a[M - i + j] * S[j] for j in range(i + 1))
        a[M - 1 - i] = (acc * (F - pow(i + 1, -1, F))) % F
    return a

def is_root(x: int, a: list[int]) -> bool:
    return sum(a[i] * pow(x, i, F) for i in range(len(a))) % F == 0

dcrd: mixing/dcnet.go ยท Coefficients, IsRoot

๐œ‘(๐‘ฅ)=โˆ’โˆ๐‘”(๐‘ฅโˆ’๐‘Ÿ๐‘”); its ๐‘€ roots are exactly the messages.

18.7.8 Root finding and the FP message

Factoring a degree-๐‘€ polynomial over a 127-bit prime field needs a dedicated solver; dcrd delegates it to an external program (csppsolver from the decred.org/cspp/v2 module) and sets PRFlagCanSolveRoots only if that program starts. Any correct root-finding algorithm is acceptable.

  • A peer that can solve computes the roots. If the solver returns an error, a number of roots other than ๐‘€, or reports a repeated root (two peers chose the same ๐‘Ÿ), the peer triggers blame (Sectionย 18.8). Otherwise it sorts the roots in increasing numeric order and sends an FP carrying them (minimal big-endian) and SeenSlotReserves listing the SR hashes in unmixed order; the FP is sent together with its DC message. If the solver process has exited, the peer instead clears PRFlagCanSolveRoots for its future PRs and waits for an FP as below.
  • A peer that cannot solve waits for any FP of the session that is valid: exactly ๐‘€ roots, each in [0,๐น) and a root of ๐œ‘ by Algorithmย 18.8, pairwise distinct, and in strictly increasing order. It uses the first valid FP it finds (each senderโ€™s FP is examined once) and ignores invalid ones. The SR deadline ends only the first blocking wait: the reference client keeps checking for a valid FP after it, and uses one that arrives later, until an RS of the session appears or the session leaves its mixpool. mixing/mixclient/client.go ยท roots

The slot of message ๐‘Ÿ๐‘– is its index in the sorted root list. A peer that does not find one of its own ๐‘Ÿ๐‘– among the roots triggers blame. The search SHOULD be constant-time.

18.7.9 XOR DC-net (DC)

The second DC-net transmits the 20-byte output hashes in the reserved slots. For its ๐‘–-th message, with slot ๐œŽ๐‘– and the pad vectors dc[๐‘–][๐‘”] of Algorithmย 18.6, peer ๐‘ computes

๐‘‰๐‘–=(โจ๐‘”โ‰ ๐‘ ๐‘+๐‘–dc[๐‘–][๐‘”])โŠ•(๐‘‘๐‘–placed at element๐œŽ๐‘–),

(18.8)

a vector of ๐‘€ 20-byte elements (mixing/dcnet.go ยท DCMixPads, DCMix), and sends the ๐‘š vectors ๐‘‰0..๐‘‰๐‘šโˆ’1 in a DC, with SeenSlotReserves listing the SR hashes in unmixed order. On receiving all DCs, each peer checks that peer ๐‘˜โ€™s DC has ๐‘š๐‘˜ vectors of ๐‘€ elements (otherwise the sender is excluded) and XORs all ๐‘€ vectors element-wise; element ๐œŽ of the result is the message in slot ๐œŽ.

18.7.10 Building the CoinJoin

Every peer builds the same unsigned transaction:

  1. Version TxVersion and lock time LockTime (common to all PRs by compatibility), expiry 0, full serialization type.
  2. For each PR in unmixed order, one input per UTXO in PR order, with the given outpoint, sequence 0xffffffff, empty signature script and the null witness values (ValueIn =โˆ’1, BlockHeight =0, BlockIndex = 0xffffffff); and the PRโ€™s change output, if any, verbatim.
  3. For each slot ๐œŽ=0..๐‘€โˆ’1, an output of value MixAmount, script version 0 and script 76 a9 14 || D[ฯƒ] || 88 ac, where ๐ท is the XOR DC-net result.
  4. Sort the transaction in place: inputs by previous-outpoint tree (ascending), then by previous transaction hash compared bytewise in display (byte-reversed) order, then by output index; outputs by value, then script version, then script bytes (lexicographic, a proper prefix first).

mixing/mixclient/coinjoin.go ยท resetUnmixed, addMixedMessage, sort | dcrutil/txsort/txsort.go ยท InPlaceSort

The witness values of the inputs are not covered by the transaction hash, which is computed over the prefix only (Chapterย 4); dcrdโ€™s mempool fills in the fraud-proof witness from the UTXO set when the transaction is accepted.

18.7.11 Confirmation and publication (CM)

Each peer checks that for each of its own messages ๐‘‘๐‘– the sorted transaction has an output with value MixAmount, script version 0 and the P2PKH script paying to ๐‘‘๐‘– (the reference implementation scans in constant time over outputs of equal value, version and script length). If any is missing, the peer triggers blame. Otherwise it signs each of its own inputs and waits until the DC-RS deadline; if any RS of the session has appeared by then, it joins blame assignment instead of confirming. Otherwise it sends a CM containing the transaction with its own signature scripts and SeenDCNets listing the DC hashes in unmixed order.

On receiving all CMs, a peer checks that each CMโ€™s transaction has the same transaction hash as its own; a CM that differs is observable misbehavior. It copies, from each CM, the signature scripts of exactly the inputs that the CMโ€™s sender contributed, then executes every input script against the previous output script reconstructed from the UTXOโ€™s public key and opcode (P2PKH, or the stake-tagged P2PKH form) with script version 0 and the flags DiscourageUpgradableNops, VerifyCleanStack, VerifyCheckLockTimeVerify, VerifyCheckSequenceVerify and VerifyTreasury (Chapterย 6). The owners of any failing input are excluded. If all succeed, every peer publishes the transaction, after a random delay, as an ordinary transaction. The session is then complete. mixing/mixclient/client.go ยท run, validateMergedCoinjoin

18.8 Blame and Failure Handling

18.8.1 Observable misbehavior

Some failures are visible to every peer from the published messages alone. The offending peers are excluded immediately and the rest rerun (Sectionย 18.6.7) without revealing secrets and reusing their existing keys and messages:

Table 18.15. Misbehavior that leads to immediate exclusion
StageCondition (the sender is excluded)
KEECDH public key does not parse.
CTNumber of ciphertexts โ‰ ๐‘›.
SRDCMix not exactly ๐‘š๐‘˜ร—๐‘€.
DCDCNet not exactly ๐‘š๐‘˜ vectors of ๐‘€ elements.
CMTransaction hash differs from the locally built CoinJoin; or an input contributed by the sender fails script execution.

18.8.2 Timeouts

If, at the CT, SR, DC or CM deadline, messages of that stage are missing, the peers whose message is missing are excluded and the rest rerun, reusing their secrets. (Missing KEs are handled by session agreement, Sectionย 18.6.5.) If fewer than MinPeers =4 peers would remain after any exclusion, the session is abandoned. mixing/mixclient/client.go ยท blameTimedOut, excludeBlamed

18.8.3 Revealing secrets

A peer triggers blame when it detects a failure that cannot be attributed from public data: a ciphertext addressed to it fails to decapsulate, the solver fails or finds a repeated root, one of its own slot messages is not among the roots, or one of its own outputs is missing from the CoinJoin. It publishes its RS (the secrets it committed to in its KE) with an empty SeenSecrets list, alongside or instead of its next protocol message.

A peer that finds any RS of its session at the end of a wait for CT, SR, FP or DC messages (such a wait ends early once every peer has sent either the awaited message or an RS), or at the DC-RS deadline before confirming, abandons the run and joins blame assignment (an RS arriving only while CMs are being collected is ignored): it publishes its own RS with SeenSecrets listing the hashes of the RS messages already received for the session. Its RS MUST reference at least one other peerโ€™s RS; otherwise it is indistinguishable from an initiator. Each peer then waits one stage timeout after publishing its own RS for the RS messages of all peers; peers that do not send one are excluded. mixing/mixpool/mixpool.go ยท Receive | mixing/mixclient/blame.go ยท blame

18.8.4 Blame procedure

With all ๐‘› RS messages, each peer replays every other peerโ€™s computation. The checks are applied in the following order, and each group returns as soon as it has blamed anyone; the next run excludes the blamed peers and every peer generates fresh secrets. mixing/mixclient/blame.go ยท blame

  1. For each peer: it sent a KE; the RS commitment (Sectionย 18.7.3) equals the KEโ€™s Commitment; every revealed SR message is in [0,๐น); recomputing ๐‘ƒ=PRNG(Seed,0) and the key pairs (Sectionย 18.7.2) reproduces the KEโ€™s ECDH and sntrup4591761 public keys; and the RS has exactly ๐‘š๐‘˜ SR messages and ๐‘š๐‘˜ DC messages.
  2. For each peer: re-encapsulating to all peers from the continuation of its ๐‘ƒ reproduces exactly the ciphertexts of its CT (which must exist).
  3. Any SR message revealed by more than one peer: all those peers are blamed.
  4. For each peer: it sent an SR of the right dimensions; with the recomputed ciphertexts addressed to it and its recomputed private key, its shared secrets can be derived (if a decapsulation fails, the reference client blames this peer, the recipient, not the peer whose ciphertext failed); and recomputing its DCMix from the revealed SR messages reproduces the published one.
  5. If no roots were obtained in the run, step 6 is skipped.
  6. For each peer: it sent a DC with ๐‘š๐‘˜ vectors; and recomputing each vector from its revealed DC messages, the slots of its revealed SR messages among the roots, and its pads reproduces the published vector.
  7. If nobody has been blamed, every peer whose RS references no RS of the session other than itself, or references a hash that is not an RS of the session, is blamed (a false accusation of failure).

If blame identifies nobody, or fewer than four peers would remain, the session is abandoned.

18.9 The Mixpool: Relay Policy

Full nodes and wallets keep received mixing messages in a mixpool. A full node relays a message only after accepting it into its mixpool; a wallet reads session messages from its own. Everything in this section is policy: it is what dcrd enforces, and a node that wants its messages relayed by dcrd MUST satisfy it.

18.9.1 Relay

Messages are announced with inv vectors of type MSG_MIX (4) and fetched with getdata (Chapterย 15). A dcrd node:

  • requests an announced mixing message only when its chain is current and the message is neither in its pool, nor in a cache of recently removed messages (8500 entries, one-minute lifetime), nor in its filter of recently rejected message hashes (an age-partitioned Bloom filter of 62500 items, false-positive rate 10โˆ’7);
  • serves getdata for mixing messages from its pool or the recently removed cache;
  • does not announce mixing messages to peers with protocol version below 10 or that asked not to receive transaction relay;
  • in blocks-only mode, ignores mixing messages and disconnects peers that announce them;
  • when a KE is held as an orphan because its own PR is unknown, requests that PR from the peer that sent the KE;
  • bans a peer that sends a message whose decoding fails with a wire-protocol error (any decode bound of Sectionย 18.4), or one rejected with a bannable error (Tableย 18.17).

server.go ยท onMixMessage, handleServeGetData, OnInv | internal/netsync/manager.go ยท OnMixMsg, needMixMsg

18.9.2 Acceptance of every message

A message is accepted only if: its run number is 0; it has not already been accepted (a duplicate is silently ignored); and its signature is valid (Algorithmย 18.2). Then, by type:

Pair request. In order: MixAmount โ‰ค MaxMixAmount =525000000000000 and MessageCount โ‰ค16; if there is change, its value is non-negative and not dust, does not exceed InputValue, its script version is 0 and its script is P2PKH or P2SH version 0; at least one UTXO; MessageCount >0; MixAmount not dust; InputValueโˆ’changeโ‰ฅMessageCountโ‹…MixAmount; the expiry window of Sectionย 18.5.3; script class P2PKH-secp256k1-v0; the fee bounds of Sectionย 18.5.5; no outpoint listed twice; every Script empty. A node with a UTXO set (dcrd) additionally requires, for every UTXO, that the output exists, is unspent both in the chain and in the mempool, has at least one confirmation, has script version 0, and passes Algorithmย 18.3 against its script, and that the sum of the UTXO values equals InputValue (this comparison is skipped when the sum is 0). Finally the identity must not have sent any earlier message, and for every outpoint already claimed by an accepted PR, the new PRโ€™s expiry must be strictly greater than that PRโ€™s. mixing/mixpool/mixpool.go ยท checkAcceptPR, acceptPR

Key exchange. Algorithmย 18.4 holds; Pos<|SeenPRs|; the epoch is a multiple of 60 seconds, not more than 5 seconds in the future and not more than 20 minutes in the past relative to the nodeโ€™s clock; no other KE by the same identity exists in the session; and among the referenced PRs that the node knows, the PR at Pos has the KEโ€™s identity and all have the same pairing description. If the PR at Pos is unknown, the KE is stored as an orphan. The first accepted KE of a session creates the session, whose PR list is the KEโ€™s SeenPRs and whose expiry is the minimum expiry of the referenced PRs known at that time. mixing/mixpool/mixpool.go ยท checkAcceptKE, acceptKE

Other messages. The limits of Tableย 18.16; a 32-byte session ID; no other message of the same type by the same identity in the same session. If the identity has no KE in the session, the message is stored as an orphan.

For every identity, at most maxMessagesPerIdentity =7ร—2ร—64=896 messages are accepted, counting the PR itself, so 895 session messages. Orphans are not counted until they are promoted.

Table 18.16. Mixpool limits on message dimensions (mixing package)
MessageLimit
PRMixAmount โ‰ค525000000000000; MessageCount โ‰ค16 (MaxMcount).
CTAt most 64 ciphertexts and 64 seen KEs (MaxPeers).
SRAt most 16 rows, each at most 1024 elements (MaxMtot); at most 64 seen CTs.
DCAt most 16 vectors, each at most 1024 elements; at most 64 seen SRs.
FPAt most 1024 roots; at most 64 seen SRs.
CMTransaction serialize size โ‰ค100000 (MaxMixTxSerializeSize); at most 64 seen DCs.
RSAt most 16 SR messages and 16 DC messages; at most 64 seen RSs.
Table 18.17. Bannable mixpool errors
ErrorCondition
ErrInvalidSignatureInvalid message signature.
ErrChangeDustChange value negative or dust.
ErrMixDustMix amount is dust.
ErrLowInputChange exceeds input value, or fee below the minimum.
ErrHighFeeFee above the maximum.
ErrInvalidMessageCountMessage count 0.
ErrInvalidScriptChange script neither P2PKH nor P2SH.
ErrInvalidTotalMixAmountInputs less change below ๐‘šโ‹…MixAmount.
ErrMissingUTXOsNo UTXOs.
ErrPeerPositionOutOfBoundsKE Pos outside SeenPRs.
ErrInvalidSessionIDNon-PR message without a 32-byte session ID.
ErrInvalidUTXOProofDuplicate outpoint, failed ownership proof, or UTXO sum differs from InputValue. Bannable only if the sending peer advertises the full-node service flag (it could have checked the UTXOs).

Other rejections (wrong run number, expiry out of range, unknown script class, an unconfirmed or spent UTXO, conflicting messages, invalid session order, and so on) are not bannable. The source notes for several of them that a peer may relay such a message in good faith, for example a KE whose PRs it does not know.

18.9.3 Orphans

The orphan pool holds at most 250 messages. When adding an orphan would exceed that, the node counts orphans per source peer and removes orphans of the source with the most orphans, then of the next, and so on (from each source as many as are needed, up to all of them), until 187 remain; the new orphan is then added. When a PR is accepted, orphan KEs of that identity that reference it are reconsidered; when a KE is accepted, the identityโ€™s orphans in that session are accepted. Orphans are removed 20 minutes after they were stored, orphan KEs also when their epoch is more than 20 minutes old, and all orphans of an identity when its PR is removed. mixing/mixpool/mixpool.go ยท addOrphan, limitNumOrphans, reconsiderOrphans

18.9.4 Expiry and removal

When a block extends the main chain, dcrd removes from the mixpool the session of any transaction in the block that is a known completed mix, and every PR with an outpoint spent by any other transaction in the block, together with all messages of that identity and the sessions they took part in. It also schedules expiry: after waiting until the second epoch boundary from now, it removes every session whose expiry is at or below the height recorded when the wait began, and every PR whose Expiry is at or below it. mixing/mixpool/mixpool.go ยท RemoveSpentPRs, ExpireMessagesInBackground, expireMessagesNow

18.9.5 Interaction with the mempool and voting

Two further policies protect mixes from disruption (they belong to Chapterย 17 but are driven by the mixpool):

  • The mempool rejects a transaction that spends an outpoint of a current pair request unless it is the completed mix of a known session.
  • The mixpool observer examines, at each epoch boundary, the previous epoch. Among sessions of at least four KEs that reached the CT stage and revealed no secrets, a session is complete if every peer sent a CM. An identity that sent a KE and a CT in some session of a pairing but was not in a completed mix receives a strike if a mix of that pairing completed; if none completed, it receives a strike only if it was one of the peers whose message was missing at the first incomplete stage of a session in which all KEs were present. Strikes are recorded against the identityโ€™s PR outpoints (merged with any strike set sharing an outpoint), removed for the PR outpoints of the peers of a session found complete and for the inputs of a known mix transaction contained in a block, and forgotten once the latest strike is at least 24 hours older than the epoch being examined. Outputs with two or more strikes (strikeLimit) cause the client to exclude PRs spending them, the mempool to reject non-mix transactions spending them, and dcrd not to announce the winning tickets of a block containing such a spend, so that its voting wallets do not vote on that block.

mixing/mixpool/observer.go ยท checkPrevEpoch, updateStrikes, MisbehavingBlock | internal/mempool/mempool.go ยท maybeAcceptTransaction

18.10 Constants

Table 18.18. Mixing constants
NameValueMeaning
F2127โˆ’1Field prime of the slot-reservation DC-net.
MixMsgSize / Msize20Size of an XOR DC-net message (a HASH160).
MixVersion10First protocol version with mixing messages.
MSG_MIX4Inventory type of mixing messages.
MinPeers4Minimum peers to proceed past KE or rerun.
MaxPeers64Maximum peers in a mixed session (mixpool and client).
MaxMcount16Maximum message count per peer.
MaxMtot1024Maximum total messages per session.
MaxMixTxSerializeSize100000Maximum CoinJoin size in bytes.
MaxMixAmount525000000000000Maximum mix amount (21ร—1014/4 atoms).
MaxMixPeers (wire)512Wire bound on peer counts and seen lists.
MaxMixMcount (wire)1024Wire bound on message counts and roots.
MaxMixFieldValLen32Maximum bytes of a field element.
MaxMixPairReqUTXOs512Maximum UTXOs per PR.
MaxMixPairReqScriptClassLen32Maximum script class length.
MaxMixPairReqUTXOScriptLen16384Maximum UTXO redeem script length.
MaxMixPairReqUTXOPubKeyLen33Maximum UTXO public key length.
MaxMixPairReqUTXOSignatureLen64Maximum UTXO proof length.
ScriptClassP2PKHv0P2PKH-secp256k1-v0Only accepted script class.
PRFlagCanSolveRoots0x01PR flag: peer can solve roots.
pairingVersion3 (4 on testnet)PR PairingFlags used by the reference client.
epoch600 s (180 s on testnet)Epoch duration.
timeoutDuration30 s (10 s on testnet)Stage timeout ๐œ.
maxJitter๐œ/10Bound on per-identity plus per-message delay.
msgJitter300 msPer-message random delay bound.
earlyKEDuration5 sKE accepted at most this early before its epoch.
lateKEDuration20 minKE accepted at most this late after its epoch.
minconf1Confirmations required of PR UTXOs.
feeRate10000 atoms/kBFee rate for PR fee and dust checks.
maxRelayFeeMultiplier10000Upper fee bound factor.
maxOrphans250Orphan pool capacity (187 after eviction).
maxMessagesPerIdentity896Messages accepted per identity.
strikeLimit2Strikes that flag outputs as misbehaving.
maxRecentlyRemovedMixMsgs8500Recently removed message cache size (TTL 1 min).

18.11 Test Vectors

The vectors below were produced by running the mixing package of dcrd at the reference commit (with its wire, chaincfg and secp256k1 dependencies taken from the same tree). Hashes are raw bytes in hexadecimal, not display order.

Test vector: Session ID and unmixed order

Six PR hashes โ„Ž๐‘˜ (๐‘˜=0..5), each 32 bytes with first byte ๐‘˜ and the rest zero.

epoch 0
  preimage prefix  6465637265642d6d69782d73657373696f6e || 0000000000000000
  sid              695794d3492979b67b51cd79fa330eaae643955ecea866b3e35d7abed2ec621e
  unmixed order    h1 h0 h3 h2 h5 h4
epoch 1763251200 (2025-11-16T00:00:00Z)
  preimage prefix  6465637265642d6d69782d73657373696f6e || 0000000069191400
  sid              0a2ebbf690ff74794c4fe8cd626187ee6464739fb0bb92e86d547841ce70a615
  unmixed order    h2 h3 h0 h1 h4 h5
Test vector: Signed pair request

The PR of dcrdโ€™s own signature test: identity key with private scalar 1, Expiry=15, MixAmount=16, ScriptClass=โ€œscript classโ€, TxVersion=17, LockTime=18, MessageCount=19, InputValue=20, one UTXO (hash of 31 zero bytes then 01, index 2, tree 3, script 040506, PubKey and Signature each 31 zero bytes followed by 07 and 08, opcode 9), change (value 10, version 11, script 0c0d0e), Flags=21, PairingFlags=22. This message is well-formed on the wire but not acceptable to a mixpool.

payload (266 bytes)
  1ffdddfb26b2955b3cf46c9e98671d11d1fd91619da4e85edb840786f661b6ab
  6824c83923f596a990613fce97d995d9d50a89ecb23841c9c10a80a47f18b50a
  0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
  0f000000 1000000000000000 0c73637269707420636c617373 1100 12000000
  13000000 1400000000000000 01
  0000000000000000000000000000000000000000000000000000000000000001
  02000000 03 03040506
  200000000000000000000000000000000000000000000000000000000000000007
  200000000000000000000000000000000000000000000000000000000000000008
  09 01 0a00000000000000 0b00 030c0d0e 15 16
signed-data hash   dc059c0a267ffe3519b6fd44200a62230af86646df1990cf0316e492de3235f5
digest preimage    decred-mix-signature,mixpairreq,<64 zeros>,0,dc059c0a...de3235f5
signature digest   bd117cb3e25960bfe803274052411ce01ed3dcf5cf1f0dfe61f5d8f8515f4b24
signature          1ffdddfb26b2955b3cf46c9e98671d11d1fd91619da4e85edb840786f661b6ab
                   6824c83923f596a990613fce97d995d9d50a89ecb23841c9c10a80a47f18b50a
message hash       78cbe3e350243d0d220e92aa188a7c9c419321fd9d8233e7a0730d16bce47f63
pairing            1000000000000000 0c73637269707420636c617373 1100 12000000 16
Test vector: UTXO ownership proof

Private key scalar 1, expiry 15.

preimage   6d697870722d7574786f70726f6f662c5032504b482845432d5363686e6f72722d
           4443527630292c 0000000f
           0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
digest     992e8aa407418e1b8c80e8b09a5fc974e809bd4a91dfdcb1aade88cf1a2cdd1e
signature  8e04cc6dba1be56419f3373755cb40ea4584c5fbdfa7e9dd4061aff1cda38189
           6ec744946fc45fe70f954c1fb5919e2d4cffbe7dd27797cf03b26c2f7e1a01be
Test vector: ECDH component of a pairwise key

Private scalars 2 and 3.

x(6G)        fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556
H(x(6G))     cedb592ff1f23633afcdb634a11364e81b9efdfbdf2feeedc3b62969f2988a4b
Test vector: Message-pair PRNG (Algorithmย 18.6)

sid = 32 bytes 11, combined key = 32 bytes 22, counter 1, nonce 2, ๐‘€=3.

seed preimage  11..11 (32) || 22..22 (32) || 01000000
seed           57fe2217c2c6b52edbd184ad99b76396bb57b71fd0ca1931ab9ed2abdf2487e9
SR secret      b312257a35d4a80604045b2e26c257799c118c562ce57da8a0bfd879549cfcc7
DC pad         77ba2e62c31f8cd28bcf08238c20fe7a9d6ddaae
               877e64054adc223569c8684d00a5e0bc4ea0c2e9
               d2a6ab5fd54d37e54ac00225e412fc80e4ce12aa
PRNG(key 000102..1f, n=0), first 64 bytes
  39fd2b7dd9c5196a8dbd0377b8dc4a498a35d86fbcde6accb2cc7d4cd8ea2492
  2b23cce7a26023ab3f0eef693ac87f64258235eab1f7a32dc22762a0485b410c
PRNG(key 000102..1f, n=1), first 32 bytes
  d838fb09536e2e3a10e8f23f486273a69f42d8e640d781ede384793c34c32564
Test vector: Slot-reservation DC-net with three messages

Three peers with one message each (๐‘€=3), ๐‘Ÿ0=3, ๐‘Ÿ1=5, ๐‘Ÿ2=7, and SR secrets ๐พ0,1 = 32 bytes 01, ๐พ0,2 = 32 bytes 02, ๐พ1,2 = 32 bytes 03 (tiny values for illustration; real messages are uniform in [0,๐น)). Field elements in minimal big-endian hex.

H(K01 || le64(1))  8d0647c6c0a02d2043415ed185424366a964699e1388b4813588ef8b1f1f09a5
peer 0 pads   5cb3d0e7d64cf4d5783290eb9d1eee93 49e72f508b78bf99eabaac0ba4ade141
              17996cc15b8e659faae5a1e77ea8ecc5
peer 0 mix    5cb3d0e7d64cf4d5783290eb9d1eee96 49e72f508b78bf99eabaac0ba4ade14a
              17996cc15b8e659faae5a1e77ea8ece0
peer 1 mix    14421511451bf2841894680d1661e9b2 54b3ef8a640d1127a38dc5d8780f9cea
              6c7e965d9e0f0f9957befc2137d1dc65
peer 2 mix    0f0a1a06e49718a66f3907074c7f27c6 6164e125107a2f3e71b78e1be342821d
              7be7fce106628ac6fd5b61f7498538a8
sum           S1 = 15, S2 = 83, S3 = 495
coefficients  a0 = 105, a1 = F - 71, a2 = 15, a3 = F - 1
              (phi(x) = -(x - 3)(x - 5)(x - 7))
is_root(3), is_root(5), is_root(7) = true; is_root(4) = false
Test vector: Secrets commitment

Identity of private scalar 1, sid = 32 bytes 11, run 0, seed = 32 bytes 33, SR messages [3], DC messages [20 bytes 44].

hashed bytes  00 x 64 || 0279be66..16f81798 || 11 x 32 || 00000000 || 33 x 32
              || 01 01 03 || 01 14 44 x 20 || 00
commitment    1255ff216f8ea06b900073f40cc5c747727f00eb8c5f1a66554838be61c86cf8
Test vector: Key derivation from a seed (Sectionย 18.7.2)

Seed = 32 bytes 55. Then one encapsulation, from the continuing PRNG, to the peerโ€™s own sntrup4591761 public key. The sntrup4591761 values depend on the comparison used by the sorting network (see the pitfall in Sectionย 18.2.1).

ECDH private   b02358b37e4f6868fb48af8ab2750b062aa95a831bc21978a98e944264fa0e75
ECDH public    02c6febf4681819e413f0ace75200a67d0fe3d0c98a15856b3a56342573c52d11e
unsigned comparison (Go 1.26.0, 1.26.11, 1.27.4 on amd64):
  H(PQ public key)   7f9f922f9089ae5b09e67cb92da4586bfc40b272f45e8ee3426db0a0dd46f272
  PQ public [0:16]   3190d480e196ca264dffac85c074c554
  H(ciphertext)      c408d531daed383c66dd6394f171bf21bbe044d6414e940060efe62096664443
  shared key         23364e2d3cd93f7527e9e77bd7d18e8c3a94ca6063f8c466030c699d41b52970
Go 1.25 comparison (Go 1.24.13, 1.25.0, 1.25.14 on amd64; 1.25.14 on 386):
  H(PQ public key)   fd71ff70b51595ea21392e96c9b610d81b9469444668e385e9bba1f9d2cd8921
  PQ public [0:16]   2f1d55f11730c71c872cd85f55fafb34
  H(ciphertext)      0bf356f86e997d15c238b665f9844be366150a47b3bd8f7ed0f22829c02d53be
  shared key         3328923bfcceee6b4728e91ec67e72f17575ce64a9fbaa77eba2e9d4e416cd5e
signed comparison (Go 1.26.11, 1.27.4 on 386):
  H(PQ public key)   ddd0c09f8460c9c66d437692c4c0f60dc0c26ad6b8a0cabe55dab7551153ccc7
  PQ public [0:16]   eae67aa5191d2a37a72e01d63a4af017
  H(ciphertext)      0ae73fd9549edeae907b807a5992e4b4627fdce0b870c226559fe507a1dc9416
  shared key         f56dff234601d5ad1fe447faa04f4795569ee81e0a003f26f02aba4ed8f0f592
Test vector: Policy arithmetic
MaxExpiry(1000): mainnet 1013, testnet3 1031, simnet 4601
smallest non-dust P2PKH value: 6030 atoms
size(1 in, 1 out, no change) = 217   min fee 2170   max fee 21700000
size(2 in, 4 out, change)    = 527   min fee 5270   max fee 52700000
size(5 in, 16 out, change)   = 1457  min fee 14570  max fee 145700000