did-btcr2-js

ADR 152: The Aggregation Checks Bind to the Beacon Type, the Membership, and the Beacon Output of the Cohort, and the Service Checks Only the Update Sender

Context

In an aggregate beacon round, the service makes the cohort, the beacon address, the aggregated data, and the transaction. Each member checks this work and then signs. Before this change, the checks had five defects. The runners also had old defects in the same code.

The member validated with the beacon type that the message named

#handleDistributeAggregatedData selected the strategy with message.body.beaconType. It did not use the beacon type of the cohort. The advert guard isCohortAdvertMessage accepted each beaconType string.

Example: a member joins a CASBeacon cohort, and its DID document gets a CASBeacon service at the beacon address. The service then sends DISTRIBUTE_AGGREGATED_DATA with the type SMTBeacon, a valid SMT proof, and the SMT root. The member validated the data as SMT data (matches true) and signed a transaction that anchors the SMT root. A resolver processes this signal as a CAS signal. It finds no CAS Announcement for the root and raises MISSING_UPDATE_DATA, so the DID does not resolve.

A member also joined a cohort of the type FooBeacon. The round of that cohort then stopped at the distribution.

The service accepted a member after it fixed the beacon address

acceptParticipant had no phase check. pendingOptIns() still listed each open opt-in after finalizeKeygen.

Example: a cohort has minParticipants 1. The opt-ins of b and c arrive together, and the operator decision for c takes 50 ms. The runner accepts b, and finalizeKeygen computes the beacon address from the key of b. Then the approval of c returns, and acceptParticipant adds c. The cohort keys are now the keys of b and c, but b got an address for the key of b alone. Thus the address does not come from the cohort keys, and c gets no COHORT_READY.

A second path needed no slow decision. A DID with an open opt-in sent COHORT_OPT_IN again after finalizeKeygen. The state machine dropped this message. The runner then read the old record from pendingOptIns() and called the operator again, and the approval added the DID.

A fallback signature did not bind to the beacon output of the member

approveFallback computed the script-path sighash over the prevout script of the request (prevOutScriptHex). It did not compare this script with the cohort. The fallback leaf comes only from the sorted cohort keys and k (ADR 043, decision 2).

Example: cohorts A and B have the same two keys and k = 1, but other recovery keys. Their fallback leaves are equal, and their beacon addresses are different. The service of A asks a member to sign a fallback transaction. The transaction spends the UTXO of B, sends its value to the service, and anchors the signal of A. The member signed, and its signature completed a valid spend of the UTXO of B. ADR 089, decision 4, records this residual.

On the key path, approveNonce also used the script of the request with no comparison. The partial signature uses the tweak of the cohort of the member, so it cannot spend an output with another key. startSigning accepted each prevout script. It threw MISSING_PREV_OUT_SCRIPT only after it set the phase SigningStarted.

The service refused a conformant update

#verifySubmittedUpdate verified the proof of an update with the opt-in key (participantPk) of the sender.

Example: did:btcr2:k1abc joins a CASBeacon cohort with the key of #initialKey. Update 2 adds #key-2 and makes it the only capabilityInvocation entry. The controller signs update 3 with #key-2. The service dropped update 3 with the rejection code UPDATE_VERIFICATION_FAILED, but a resolver accepts update 3. Thus no later update of the DID got through this beacon.

The opt-in key is also self-declared (ADR 090, the residual “participantPk is self-declared and not tied to the sender’s DID”). Thus the old check bound the update to no key of the DID document.

Two beacon types can get one beacon address

The beacon address comes from the cohort keys, k, the recovery key, the recovery sequence, the funding model (ADR 042), and the network. It does not come from the beacon type or from the DID. A member uses the same key in each cohort.

Example: a service advertises a CASBeacon cohort and an SMTBeacon cohort with minParticipants 1 and the same recovery terms. A member joins both cohorts, and both cohorts get the address X. The application adds a CASBeacon service at X to the DID document. The SMT round then anchors an SMT root from X. A resolver processes this signal as a CAS signal and raises MISSING_UPDATE_DATA.

The type check of decision 1 does not find this case, because the member validates each cohort with the type of that cohort. Also, joinedCohorts listed a cohort after its COHORT_READY failed with the error type BEACON_ADDRESS_MISMATCH. The cause: validateMembership sets cohort.beaconAddress before it compares the address.

The runners had old defects in the same code

  1. joinFirst and joinMatching rejected on an error event, but they did not stop the runner. The caller had no runner handle, and the runner continued to sign and to join new adverts.
  2. stop() removed only the transport handlers. A callback that waited at stop() still signed and sent a message after it returned.
  3. The service runner awaited onProvideTxData with no latch. A VALIDATION_ACK during the await called onProvideTxData again, for example a repeated ack or an ack of a stranger. The second startSigning call threw INVALID_PHASE, and the runner failed the cohort.
  4. Two opt-ins of one DID can wait on the operator at the same time. Then the second approval threw ALREADY_ACCEPTED and failed the cohort. Or the first approval added the key of the second opt-in to the cohort, even if the operator declined that key.

The service runner also dropped an approval past maxParticipants with no event. The four demos in packages/aggregation/lib/operations/aggregation/ built a beacon transaction with no OP_RETURN signal. Their prevout script was a key-path-only P2TR script, not the beacon script.

Examples

Case Before After
A CAS cohort gets valid SMT data under the type SMTBeacon The member signs the SMT root. matches is false. The default runner sends a rejection ack, and approveNonce throws UNVALIDATED_DATA.
An advert has the beaconType FooBeacon The member joins, and the round stops at the distribution. The participant drops the advert.
The approval of c returns after finalizeKeygen acceptParticipant adds c. The address does not come from the cohort keys. The runner emits message-rejected with the rejection code MEMBERSHIP_FINAL.
A fallback request of cohort A spends the UTXO of cohort B The member of A signs. The spend of B is valid. approveFallback throws PREVOUT_SCRIPT_MISMATCH.
The member submits update 3, signed with #key-2 The service drops it (UPDATE_VERIFICATION_FAILED). The service accepts it.
An SMT cohort gets the accepted address of a CAS cohort of the member The member signs the SMT root. receive() throws BEACON_TYPE_CONFLICT. The phase becomes Failed, and the runner emits cohort-failed.

The normative specification texts

The specification does not mark the appendix as non-normative. Conformance: “Everything else in this specification is normative.” Thus the SHOULD texts of the security considerations are normative.

The texts with no requirement

The illustrative example

Thus the section “Example Using Musig2, secp256k1, and Schnorr Signatures” is illustrative, and its lowercase “must” is not a BCP 14 keyword. Three of its texts match this change:

This change follows the example, but no check depends on the example. Each check depends on the normative texts above.

BIP 341

Common signature message: “sha_scriptpubkeys (32): the SHA256 of all spent outputs’ scriptPubKeys, serialized as script inside CTxOut.” Thus a Taproot signature commits to the script of the output that the transaction spends.

Decision

1. The member validates with the beacon type of its cohort

2. The membership is final at finalizeKeygen

finalizeKeygen computes the beacon address from the cohort keys. Thus the service accepts no member after it:

After the operator decision, the service runner applies these checks in this order:

  1. If the runner stopped, or the cohort completed or failed, the runner drops the approval with no event.
  2. If the DID is already a member, the runner drops the approval with no event (decision 7).
  3. If the phase is not Advertised, the runner emits message-rejected with the rejection code MEMBERSHIP_FINAL.
  4. If a newer opt-in of the DID replaced the record, the runner drops the approval with no event (decision 7).
  5. If the cohort has maxParticipants members, the runner emits message-rejected with the rejection code COHORT_FULL. Before, it dropped the approval with no event.

The runner emits MEMBERSHIP_FINAL and COHORT_FULL, not the state machine. The participant of a late approval gets no message and stays in the phase OptedIn. AggregationParticipantRunner has no timeout, so the application of the participant must set its own deadline.

3. Each signature spends the beacon output of the cohort

The check is the first defense. A beacon signal spends from the beacon address (Terminology), so a member signs only a spend of its own beacon output. The sighash over its own beacon script is a second defense. By BIP 341, a signature over its own beacon script cannot spend an output with another script.

Only the check on the fallback path closes an attack: the spend of another cohort with the same keys and k. On the key path, the partial signature already uses the tweak of the cohort. The key-path check and the startSigning check fail fast: they refuse a round that cannot complete, before any signature.

Two cohorts with the same keys, k, recovery key, recovery sequence, and funding model have the same beacon script. For these cohorts the check passes. Decision 5 covers the beacon type of such cohorts.

4. The service checks only the structure of the proof and the sender DID

#submittedUpdateProblem replaces #verifySubmittedUpdate. It reads the proof through unknown, so a wrong type gives a rejection and not a raw TypeError out of receive(). It applies these checks in this order:

  1. The proof is an object, not null and not an array. Else: UPDATE_MALFORMED, “SUBMIT_UPDATE signedUpdate has no proof object”.
  2. verificationMethod is a string, and proofValue is a string that is not empty. Else: UPDATE_MALFORMED, “Update proof has no verificationMethod or proofValue string”.
  3. verificationMethod is the sender DID, then #, ?, or /, then at least one more character. Else: UPDATE_SENDER_MISMATCH, “Update proof verificationMethod is not a DID URL of the sender DID”.

Check 3 refuses a relative id (#initialKey), the bare DID, and a longer DID that starts with the sender DID. The rule is the rule of Updater.sign on the write path (ADR 147, decision 6).

The service does not verify the signature. It does not hold the current DID document of the sender, so it cannot know which methods can sign an update. A resolver verifies the proof. An update with a bad proof harms only the DID of the sender. The CAS map key is that DID, and the SMT leaf index is the SHA-256 hash of that DID.

The order of #handleSubmitUpdate does not change: the body, NOT_A_MEMBER, the size cap, the new checks, then DUPLICATE_RESPONSE. service.ts no longer imports BIP340Cryptosuite and SchnorrMultikey. The package source now imports only types from @did-btcr2/cryptosuite.

RejectionReason changes:

5. One beacon address of a participant has one beacon type

In #handleCohortReady, after validateMembership, the participant compares this cohort with each other cohort of the participant object. If another cohort has the same accepted beacon address and another beacon type:

The membership is final at finalizeKeygen (decision 2), so a cohort in conflict cannot get another address. Thus a cohort in conflict fails. If no other cohort conflicts, the participant records the accepted address and sets the phase CohortReady.

The scope of the check:

Thus joinedCohorts lists only the cohorts whose COHORT_READY the participant accepted. Two cohorts of one beacon type at one address stay allowed. The JSDoc of JoinedCohortInfo.beaconType tells the application to compare the beacon address with the beacon services of its DID documents.

The check compares address strings. Testnet3, testnet4, signet, and mutinynet give one address string for the same terms. Thus the check can also refuse a cohort on another of these networks. This refusal is not necessary, but it makes no DID invalid.

6. The participant runner reports the refusal as a cohort failure and stops before a rejection

Thus joinFirst with two cohorts in conflict resolves with the first cohort and its sidecar data. Before this change, the member refused no cohort, so it signed each cohort that got to the signing before joinFirst stopped the runner. This is a reason for cohort-failed: an error event makes joinFirst reject, and the caller does not get the sidecar data (see Alternatives).

7. The service runner applies an approval only to the opt-in that the operator saw, and it requests the transaction data one time

The identity check has two limits:

  1. Under an approve-all policy, the newest opt-in wins. The decision for the newest opt-in approves it, and the service adds its key to the cohort. The default onOptInReceived approves each opt-in.
  2. On a transport with no sender authentication, a stranger can send an opt-in with the DID of another party. The check does not bind the opt-in to a key of that DID. A later change of the transports binds the opt-in to the sender key.

The JSDoc of onOptInReceived says: “only the decision for the new opt-in applies.”

8. The demos send a signal and spend the beacon output

The four demos in packages/aggregation/lib/operations/aggregation/ get the prevout script from the beacon address. Each demo sends the change to the beacon address and puts OP_RETURN <signalBytes> in the last output. e2e-verify-signing.ts reads the tweaked key from the beacon output, and it computes the sighash over the beacon script. The JSDoc examples of startSigning and AggregationServiceRunner name buildAggregationBeaconTx of @did-btcr2/method with its options object.

9. Each judgment call conforms to the specification texts

Judgment call Text Result
The member validates the aggregated data with the beacon type of the advert. It vetoes data under another type or under no type. Beacons: “The Beacon Type in the service defines how Beacon Signals MUST be processed.” Security Considerations: “The DID controller SHOULD verify that the Beacon Signal announces the BTCR2 Update they expect (or no BTCR2 Update)”. Conforms. The beacon service of the member has the type of the cohort. A signal of another type announces no update that a resolver can find for the DID.
The participant drops an advert of a type other than CASBeacon and SMTBeacon. The check runs on the receive path, not in joinCohort. Aggregate Beacons: “DID controllers can use a CAS Beacon, an SMT Beacon, or both to participate in BTCR2 Update Aggregation.” Conforms. Only these two types aggregate updates. The specification is silent on the place of the check. On the receive path, one advert of another type cannot reject joinFirst or joinMatching.
acceptParticipant throws INVALID_PHASE outside the phase Advertised. pendingOptIns() is empty outside that phase. Aggregate Beacons, example: “The Aggregation Service decides when to finalize the membership of the Aggregation Cohort. After it does, it computes an n-of-n Pay-to-Taproot (P2TR) address from the public keys the Aggregation Participants provided.” Security Considerations: “DID controllers participating in an Aggregation Cohort SHOULD verify the Beacon Address is an n-of-n and that one of the n keys is the key that they provided to the Aggregation Service.” Conforms. A key that the service adds after finalizeKeygen is not in the address that each member computed.
A late approval gives message-rejected with MEMBERSHIP_FINAL or COHORT_FULL. A late opt-in and an approval after a stop give no event. The specification defines no event of a service. The specification is silent. One rule covers both late approvals, so an operator that approved an opt-in gets an answer. A late opt-in reaches no operator callback, so it needs no answer.
The service runner applies an approval only to the opt-in that the operator saw. It drops an approval for a member DID. A latch requests the transaction data one time. The specification defines no operator decision and no runner. The specification is silent. The checks keep the rule of ADR 089, decision 5: one inbound message cannot fail a cohort. A repeated opt-in or a repeated ack no longer fails the cohort.
The member and startSigning refuse a prevout script that is not the beacon script, on the key path and on the fallback path. Terminology: “Beacon Signals are Bitcoin transactions that spend from a Beacon Address and include a transaction output of the format defined in Signal Bytes.” Beacons: “so that only approved Beacon Signals can be posted to Bitcoin.” Conforms. A transaction that spends another output is not a beacon signal of the cohort. Both paths give the same guarantee, as ADR 043, decision 5, does for the signal check.
The member signs over its own beacon script. beaconScript is a private field with a copy getter. BIP 341: “sha_scriptpubkeys (32): the SHA256 of all spent outputs’ scriptPubKeys, serialized as script inside CTxOut.” Conforms. The signature commits to the beacon script of the member, so it cannot spend an output with another script. The specification is silent on the API. With a copy, a caller cannot change the bytes that the check reads.
The JSDoc examples and the demos build a transaction that spends the beacon output and puts the signal in the last output. Resolve, Find Beacon Signals: “The transaction spends from the Beacon Address.” Also: “The last output script of the transaction contains Signal Bytes.” Conforms. The examples also give the recovery terms that ADR 042 requires.
The service checks only the structure of the proof and the sender DID. It does not verify the signature. Update: “An INVALID_DID_UPDATE error MUST be raised if no entry of the sourceDidDocument.capabilityInvocation Set identifies verificationMethodId.” Resolve: “The resolver MUST find the entry of current_document.capabilityInvocation that identifies update.proof.verificationMethod.” Privacy Considerations: “aggregators are able to coordinate Beacon Signals without needing to view or validate DID documents or the updates.” Conforms. Each capabilityInvocation method that can sign can sign an update. The service does not hold the current DID document, so a key check refuses conformant updates. The specification gives the service no check of an update.
The proof id must be the sender DID, then #, ?, or /, then at least one more character. The specification names no proof id rule for a service. The specification is silent. The rule is the rule of Updater.sign (ADR 147, decision 6). The old service check also refused a relative id, at the signature verification.
Each check has its own rejection code. UPDATE_VERIFICATION_FAILED is removed with no alias. The specification defines no rejection code of a service. The specification is silent. Each name identifies its check: a structure check validates, and a signature check verifies. At 0.x, the package changes the name with no alias.
The participant refuses a COHORT_READY at the accepted address of another of its cohorts with another beacon type. Two cohorts of one type at one address stay allowed. Resolve, Find Beacon Signals: “For each Beacon Address that is not in scanned_beacons:” and “Derive update_hash from the transaction’s Signal Bytes based on the Beacon Type:”. Beacons: “Any on-chain Beacon Signal that cannot be processed renders the related DID invalid.” Conforms. A resolver scans each beacon address one time and processes each signal with one beacon type. A signal of the other type cannot be processed.
The check runs after validateMembership, reads only the accepted address, and counts each other cohort in any phase. Security Considerations: “This can be achieved only by constructing the Beacon Address for themselves using the set of keys from the Aggregation Cohort that SHOULD be provided by the Aggregation Service.” Conforms. The check uses an address that the member computed. A Complete or Failed cohort can keep a beacon service in a DID document.
On a conflict, the phase becomes Failed. The participant runner emits cohort-failed and no error event. The specification defines no participant event. The specification is silent. The membership is final, so the cohort cannot get another address. The refusal ends one cohort, as a validation rejection does.
The check is only on the participant side and knows one participant object. The library has no service check and no seed option for known beacons. Security Considerations: “The DID controller SHOULD verify that the Beacon Signal announces the BTCR2 Update they expect (or no BTCR2 Update) for all Beacon Signals broadcast by Aggregation Services before final authorization.” Conforms. The SHOULD applies to the DID controller. By the guard criterion of ADR 135, the library refuses only a permanent failure with data that it holds. The DID documents are data of the application.
joinFirst and joinMatching stop the runner before they reject. The runner checks the stop after each awaited callback. joinMatching does not count a failed cohort. The specification defines no library API. The specification is silent. After a rejection, the caller has no runner handle, so only the helper can stop the runner. joinMatching keeps its contract: “resolve once count cohorts have completed”.

Alternatives

Consequences

The behavior changes:

The public API breaks:

  1. isCohortAdvertMessage returns false for a beaconType other than CASBeacon and SMTBeacon. The participant drops such an advert. The runner emits no cohort-discovered event, and joinCohort throws INVALID_PHASE for its id.
  2. PendingValidation.beaconType is the type of the cohort. PendingValidation.matches is false if the message names another type or no type. A message with no type now gives a stored validation.
  3. approveNonce and approveFallback throw PREVOUT_SCRIPT_MISMATCH.
  4. acceptParticipant throws INVALID_PHASE outside the phase Advertised. pendingOptIns() returns an empty map outside that phase.
  5. startSigning throws PREVOUT_SCRIPT_MISMATCH. It throws MISSING_PREV_OUT_SCRIPT before it changes the phase.
  6. RejectionReason removes UPDATE_VERIFICATION_FAILED. It adds UPDATE_SENDER_MISMATCH, INVALID_FALLBACK_SIG, MEMBERSHIP_FINAL, and COHORT_FULL. A fallback signerPk that is not the cohort key gives INVALID_FALLBACK_SIG (before: UPDATE_MALFORMED). A proof that is not an object, a verificationMethod that is not a string, or a proofValue that is empty or not a string gives UPDATE_MALFORMED (before: UPDATE_VERIFICATION_FAILED).
  7. The service runner emits message-rejected with MEMBERSHIP_FINAL or COHORT_FULL. Before, it dropped these approvals with no event.
  8. JoinedCohortInfo.beaconType is a new required member. Code that builds a JoinedCohortInfo must set it. Code that calls an OnProvideUpdate function must pass beaconType.
  9. CohortCompleteInfo.beaconType is the type of the cohort. Before, it came from the validation, or it was an empty string.
  10. AggregationParticipant.receive() throws AggregationParticipantError of the type BEACON_TYPE_CONFLICT, and the phase becomes Failed. The data is { cohortId, beaconType, beaconAddress, otherCohortId, otherBeaconType }.
  11. joinedCohorts lists only the cohorts whose COHORT_READY the participant accepted. Before, it also listed a cohort after BEACON_ADDRESS_MISMATCH. Each key in JoinedCohortInfo.cohortKeys is now a copy, so a change to a key does not change the cohort.
  12. The participant runner emits cohort-failed with { cohortId, reason } for BEACON_TYPE_CONFLICT, and no error event. joinFirst and joinMatching do not settle on it.
  13. joinFirst and joinMatching stop the runner before they reject on an error event.
  14. After stop(), a callback that returns late has no effect: the runner sends no message for it.
  15. The additions: the getter AggregationCohort.beaconScript and the member beaconType of the OnProvideUpdate info.

The residuals:

The test evidence:

Superseded.

Unchanged.

Implementation

References