mintCallbackToken function

Future<String> mintCallbackToken({
  1. required BroadcastCallbackConfig config,
  2. required CallbackTokenSigner signer,
  3. required String? txid,
  4. DateTime? now,
  5. Uint8List? random,
})

A callback token for one submission: bb1. and the unpadded base64url of 01 ‖ ephemeral X25519 key ‖ nonce ‖ ciphertext. The plaintext is the CBOR list [body, signature]: the Ed25519 signature is over broadcast-bridge/token/v1 ‖ body. The key is HKDF-SHA256 of the X25519 shared secret, salted with ephemeral key ‖ bridge key and with the same domain string as info; the cipher is ChaCha20-Poly1305 with associated data 01.

txid binds the token to one transaction; null for a batch. now and random are for tests: random is 44 bytes, the ephemeral X25519 seed then the nonce. A fresh token per submission is what keeps tokens unlinkable to each other.

Implementation

Future<String> mintCallbackToken({
  required BroadcastCallbackConfig config,
  required CallbackTokenSigner signer,
  required String? txid,
  DateTime? now,
  Uint8List? random,
}) async {
  final exp = (now ?? DateTime.now()).add(config.tokenTtl).millisecondsSinceEpoch ~/ 1000;
  final body = callbackTokenBody(
    peerIdBytes: signer.peerIdBytes,
    folder: config.folder,
    txid: txid,
    exp: exp,
    bridgePeerIdBytes: decodePeerId(config.bridgePeerId),
    net: config.net,
  );
  final sig = await signer.sign(Uint8List.fromList([..._domain, ...body]));
  if (sig.length != 64) throw StateError('the signer returned ${sig.length} bytes, not an Ed25519 signature');
  final plain = cbor.encode(CborList([CborBytes(body), CborBytes(sig)]));

  final rand = random ?? _secureRandom(44);
  if (rand.length != 44) throw ArgumentError.value(random, 'random', 'must be 44 bytes');
  final bridgePub = _hexDecode(config.bridgeX25519PubHex);
  final x25519 = X25519();
  final eph = await x25519.newKeyPairFromSeed(rand.sublist(0, 32));
  final ephPub = (await eph.extractPublicKey()).bytes;
  final shared = await x25519.sharedSecretKey(
    keyPair: eph,
    remotePublicKey: SimplePublicKey(bridgePub, type: KeyPairType.x25519),
  );
  final key = await Hkdf(hmac: Hmac.sha256(), outputLength: 32).deriveKey(
    secretKey: shared,
    nonce: [...ephPub, ...bridgePub],
    info: _domain,
  );
  final nonce = rand.sublist(32, 44);
  final box = await Chacha20.poly1305Aead().encrypt(plain, secretKey: key, nonce: nonce, aad: const [0x01]);

  final raw = <int>[0x01, ...ephPub, ...nonce, ...box.cipherText, ...box.mac.bytes];
  return 'bb1.${base64Url.encode(raw).replaceAll('=', '')}';
}