use nostr_sdk::prelude::nip44::v2::ConversationKey;
use nostr_sdk::prelude::{Keys, PublicKey, SecretKey};
use sha2::{Digest, Sha256};
use super::super::{ChannelId, CommunityId, Epoch};
const LABEL_CHANNEL: &str = "concord/channel";
const LABEL_CONTROL: &str = "concord/control";
const LABEL_CONTROL_SIGNER: &str = "concord/control-signer";
const LABEL_REKEY_PSEUDONYM: &str = "concord/rekey-pseudonym";
const LABEL_BASE_REKEY_PSEUDONYM: &str = "concord/base-rekey-pseudonym";
const LABEL_RECIPIENT_PSEUDONYM: &str = "concord/recipient-pseudonym";
const LABEL_GUESTBOOK: &str = "concord/guestbook";
const LABEL_CHANNEL_ACCESS: &str = "concord/channel-access";
const LABEL_CHANNEL_WRITER: &str = "concord/channel-writer";
const LABEL_VOICE_SIGNER: &str = "concord/voice-signer";
const LABEL_VOICE_MEDIA: &str = "concord/voice-media";
const LABEL_VOICE_SENDER: &str = "concord/voice-sender";
const LABEL_DISSOLVED: &str = "concord/dissolved";
const LABEL_GRANT: &str = "concord/grant";
const LABEL_BANLIST: &str = "concord/banlist";
const LABEL_PINS: &str = "concord/pins";
const LABEL_INVITE_LINKS: &str = "concord/invite-links";
const LABEL_EVERYONE: &str = "concord/everyone";
const LABEL_TENURE: &str = "concord/tenure";
const LABEL_ACL: &str = "concord/acl";
const LABEL_SYNC: &str = "concord/sync";
const LABEL_WRITERS: &str = "concord/writers";
const LABEL_WRITER_SCOPE: &[u8] = b"concord/writer-scope";
const LABEL_CERTIFIER_SCOPE: &[u8] = b"concord/certifier-scope";
const LABEL_EDITION_BINDING: &str = "concord/edition-binding";
const LABEL_INVITE_KEY: &str = "concord/invite-key";
const LABEL_WRAP_OWNER: &str = "concord/wrap-owner";
const LABEL_COMMUNITY: &str = "concord/community";
const LABEL_EPOCH_COMMITMENT: &str = "concord/epoch-key-commitment";
const ZERO32: [u8; 32] = [0u8; 32];
pub const TOKEN_LEN: usize = 16;
fn build_info(label: &str, id32: &[u8; 32], epoch: Option<u64>) -> Vec<u8> {
let mut info = Vec::with_capacity(label.len() + 1 + 32 + 8);
info.extend_from_slice(label.as_bytes());
info.push(0x00);
info.extend_from_slice(id32);
if let Some(e) = epoch {
info.extend_from_slice(&e.to_be_bytes());
}
info
}
fn hkdf32(ikm: &[u8], info: &[u8]) -> [u8; 32] {
let mut prk = crate::crypto::sha256::hmac(&[0u8; 32], &[ikm]);
let okm = crate::crypto::sha256::hmac(&prk, &[info, &[1]]);
zeroize::Zeroize::zeroize(&mut prk);
okm
}
fn hkdf_to_secret_key(ikm: &[u8], base_info: &[u8]) -> SecretKey {
if let Ok(sk) = SecretKey::from_slice(&hkdf32(ikm, base_info)) {
return sk;
}
for counter in 0u8..=255 {
let mut info = base_info.to_vec();
info.push(counter);
if let Ok(sk) = SecretKey::from_slice(&hkdf32(ikm, &info)) {
return sk;
}
}
unreachable!("secp256k1 scalar rejection 257 times running is impossible")
}
#[derive(Clone)]
pub struct GroupKey {
keys: Keys,
conv_key: ConversationKey,
}
const GROUP_KEY_MEMO_CAP: usize = 4096;
#[derive(Default)]
struct GroupKeyMemo {
cur: std::collections::HashMap<[u8; 32], GroupKey>,
prev: std::collections::HashMap<[u8; 32], GroupKey>,
}
impl GroupKeyMemo {
fn get(&mut self, key: &[u8; 32]) -> Option<GroupKey> {
if let Some(hit) = self.cur.get(key) {
return Some(hit.clone());
}
let hit = self.prev.remove(key)?;
self.insert(*key, hit.clone());
Some(hit)
}
fn insert(&mut self, key: [u8; 32], value: GroupKey) {
if self.cur.len() >= GROUP_KEY_MEMO_CAP {
self.prev = std::mem::take(&mut self.cur);
}
self.cur.insert(key, value);
}
}
impl GroupKey {
pub(crate) fn from_parts(keys: Keys, conv_key: ConversationKey) -> Self {
GroupKey { keys, conv_key }
}
fn derive(label: &str, secret: &[u8], id32: &[u8; 32], epoch: Option<u64>) -> Self {
let memo_key: [u8; 32] = {
let mut h = crate::crypto::sha256::Sha256::new();
h.update(label.as_bytes());
h.update([0u8]);
h.update(secret);
h.update(id32);
h.update(epoch.unwrap_or(u64::MAX).to_be_bytes());
h.update([epoch.is_some() as u8]);
h.finalize()
};
struct MemoKey;
type MemoMap = std::sync::Mutex<GroupKeyMemo>;
let memo: std::sync::Arc<MemoMap> = crate::db::current_session().scoped::<MemoKey, MemoMap>();
if let Some(hit) = memo.lock().unwrap_or_else(|e| e.into_inner()).get(&memo_key) {
return hit;
}
let info = build_info(label, id32, epoch);
let sk = hkdf_to_secret_key(secret, &info);
let keys = Keys::new(sk);
let conv_key = ConversationKey::derive(keys.secret_key(), &keys.public_key())
.expect("self-ECDH of a valid keypair cannot fail");
let out = GroupKey { keys, conv_key };
memo.lock().unwrap_or_else(|e| e.into_inner()).insert(memo_key, out.clone());
out
}
pub(crate) fn from_secret(secret: &[u8; 32]) -> Option<Self> {
let keys = Keys::new(nostr_sdk::prelude::SecretKey::from_slice(secret).ok()?);
let conv_key = ConversationKey::derive(keys.secret_key(), &keys.public_key()).ok()?;
Some(GroupKey { keys, conv_key })
}
pub(crate) fn secret(&self) -> [u8; 32] {
self.keys.secret_key().to_secret_bytes()
}
pub fn pk(&self) -> PublicKey {
self.keys.public_key()
}
pub fn pk_hex(&self) -> String {
self.keys.public_key().to_hex()
}
pub fn keys(&self) -> &Keys {
&self.keys
}
pub fn conv_key(&self) -> &ConversationKey {
&self.conv_key
}
}
impl std::fmt::Debug for GroupKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GroupKey").field("pk", &self.pk_hex()).finish()
}
}
pub fn channel_group_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> GroupKey {
GroupKey::derive(LABEL_CHANNEL, secret, &channel_id.0, Some(epoch.0))
}
pub fn control_group_key(community_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
GroupKey::derive(LABEL_CONTROL, community_root, &community_id.0, Some(epoch.0))
}
pub fn control_signer_group_key(control_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
GroupKey::derive(LABEL_CONTROL_SIGNER, control_root, &community_id.0, Some(epoch.0))
}
pub fn guestbook_group_key(community_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
GroupKey::derive(LABEL_GUESTBOOK, community_root, &community_id.0, Some(epoch.0))
}
pub fn channel_writer_group_key(writer_secret: &[u8; 32], channel_id: &ChannelId, writer_epoch: Epoch) -> GroupKey {
GroupKey::derive(LABEL_CHANNEL_WRITER, writer_secret, &channel_id.0, Some(writer_epoch.0))
}
pub fn channel_access_group_key(community_root: &[u8; 32], channel_id: &ChannelId, root_epoch: Epoch) -> GroupKey {
GroupKey::derive(LABEL_CHANNEL_ACCESS, community_root, &channel_id.0, Some(root_epoch.0))
}
pub fn channel_rekey_group_key(root: &[u8; 32], channel_id: &ChannelId, new_epoch: Epoch) -> GroupKey {
GroupKey::derive(LABEL_REKEY_PSEUDONYM, root, &channel_id.0, Some(new_epoch.0))
}
pub fn base_rekey_group_key(prior_root: &[u8; 32], community_id: &CommunityId, new_epoch: Epoch) -> GroupKey {
GroupKey::derive(LABEL_BASE_REKEY_PSEUDONYM, prior_root, &community_id.0, Some(new_epoch.0))
}
pub fn dissolved_group_key(community_id: &CommunityId) -> GroupKey {
GroupKey::derive(LABEL_DISSOLVED, &community_id.0, &ZERO32, None)
}
pub fn voice_group_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> GroupKey {
GroupKey::derive(LABEL_VOICE_SIGNER, secret, &channel_id.0, Some(epoch.0))
}
pub fn voice_media_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> [u8; 32] {
hkdf32(secret, &build_info(LABEL_VOICE_MEDIA, &channel_id.0, Some(epoch.0)))
}
pub fn voice_sender_key(media_key: &[u8; 32], identity: &str) -> [u8; 32] {
let id: [u8; 32] = Sha256::digest(identity.as_bytes()).into();
hkdf32(media_key, &build_info(LABEL_VOICE_SENDER, &id, None))
}
pub fn grant_locator(community_id: &CommunityId, member_xonly: &[u8; 32]) -> [u8; 32] {
#[derive(Default)]
struct Locators {
cur: std::collections::HashMap<[u8; 64], [u8; 32]>,
prev: std::collections::HashMap<[u8; 64], [u8; 32]>,
}
const GEN: usize = 8192;
let mut key = [0u8; 64];
key[..32].copy_from_slice(&community_id.0);
key[32..].copy_from_slice(member_xonly);
let memo = crate::db::current_session().scoped::<Locators, std::sync::Mutex<Locators>>();
let mut held = memo.lock().unwrap_or_else(|e| e.into_inner());
if let Some(hit) = held.cur.get(&key) {
return *hit;
}
let locator = match held.prev.remove(&key) {
Some(hit) => hit,
None => hkdf32(&community_id.0, &build_info(LABEL_GRANT, member_xonly, None)),
};
if held.cur.len() >= GEN {
held.prev = std::mem::take(&mut held.cur);
}
held.cur.insert(key, locator);
locator
}
pub fn banlist_locator(community_id: &CommunityId) -> [u8; 32] {
hkdf32(&community_id.0, &build_info(LABEL_BANLIST, &ZERO32, None))
}
pub fn everyone_locator(community_id: &CommunityId) -> [u8; 32] {
hkdf32(&community_id.0, &build_info(LABEL_EVERYONE, &ZERO32, None))
}
pub fn edition_binding(community_id: &CommunityId) -> [u8; 32] {
hkdf32(&community_id.0, &build_info(LABEL_EDITION_BINDING, &ZERO32, None))
}
pub fn tenure_locator(community_id: &CommunityId, member_xonly: &[u8; 32], sealer_xonly: &[u8; 32]) -> [u8; 32] {
let pair: [u8; 32] = Sha256::new().chain_update(member_xonly).chain_update(sealer_xonly).finalize().into();
hkdf32(&community_id.0, &build_info(LABEL_TENURE, &pair, None))
}
pub fn acl_locator(community_id: &CommunityId, scope: &[u8; 32], target: &[u8; 32]) -> [u8; 32] {
let pair: [u8; 32] = Sha256::new().chain_update(scope).chain_update(target).finalize().into();
hkdf32(&community_id.0, &build_info(LABEL_ACL, &pair, None))
}
pub fn sync_locator(community_id: &CommunityId, channel_id: &ChannelId) -> [u8; 32] {
hkdf32(&community_id.0, &build_info(LABEL_SYNC, &channel_id.0, None))
}
pub fn writers_locator(community_id: &CommunityId, channel_id: &ChannelId) -> [u8; 32] {
hkdf32(&community_id.0, &build_info(LABEL_WRITERS, &channel_id.0, None))
}
pub fn writer_scope(channel_id: &ChannelId) -> [u8; 32] {
Sha256::new().chain_update(LABEL_WRITER_SCOPE).chain_update(channel_id.0).finalize().into()
}
pub fn certifier_scope(channel_id: &ChannelId) -> [u8; 32] {
Sha256::new().chain_update(LABEL_CERTIFIER_SCOPE).chain_update(channel_id.0).finalize().into()
}
pub fn pins_locator(community_id: &CommunityId, channel_id: &ChannelId) -> [u8; 32] {
hkdf32(&community_id.0, &build_info(LABEL_PINS, &channel_id.0, None))
}
pub fn invite_links_locator(community_id: &CommunityId, creator_xonly: &[u8; 32]) -> [u8; 32] {
hkdf32(&community_id.0, &build_info(LABEL_INVITE_LINKS, creator_xonly, None))
}
pub fn recipient_locator(
rotator_xonly: &[u8; 32],
recipient_xonly: &[u8; 32],
scope_id: &[u8; 32],
new_epoch: Epoch,
) -> [u8; 32] {
let mut ikm = [0u8; 64];
ikm[..32].copy_from_slice(rotator_xonly);
ikm[32..].copy_from_slice(recipient_xonly);
hkdf32(&ikm, &build_info(LABEL_RECIPIENT_PSEUDONYM, scope_id, Some(new_epoch.0)))
}
pub fn invite_bundle_key(token: &[u8; TOKEN_LEN]) -> [u8; 32] {
hkdf32(token, &build_info(LABEL_INVITE_KEY, &ZERO32, None))
}
pub fn wrap_owner_key(author_secret: &[u8; 32], address: &PublicKey, rumor_id: &[u8; 32]) -> Keys {
let mut h = Sha256::new();
h.update(address.to_bytes());
h.update(rumor_id);
let id: [u8; 32] = h.finalize().into();
Keys::new(hkdf_to_secret_key(author_secret, &build_info(LABEL_WRAP_OWNER, &id, None)))
}
pub fn community_id_of(owner_xonly: &[u8; 32], owner_salt: &[u8; 32]) -> CommunityId {
let mut h = Sha256::new();
h.update(LABEL_COMMUNITY.as_bytes());
h.update(owner_xonly);
h.update(owner_salt);
CommunityId(h.finalize().into())
}
pub fn verify_community_id(community_id: &CommunityId, owner_xonly: &[u8; 32], owner_salt: &[u8; 32]) -> bool {
community_id_of(owner_xonly, owner_salt) == *community_id
}
pub fn epoch_key_commitment(prev_epoch: Epoch, prev_key: &[u8; 32]) -> [u8; 32] {
let mut h = Sha256::new();
h.update(LABEL_EPOCH_COMMITMENT.as_bytes());
h.update(prev_epoch.0.to_be_bytes());
h.update(prev_key);
h.finalize().into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn coordinates_match_the_spec_vectors() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::roles::overwrite_target_bytes;
let h = |b: [u8; 32]| crate::simd::hex::bytes_to_hex_32(&b);
let (cid, ch, member, sealer, role) = (CommunityId([1; 32]), ChannelId([2; 32]), [3u8; 32], [4u8; 32], [5u8; 32]);
assert_eq!(h(grant_locator(&cid, &member)), "087cc31d524f398b0810e36aa18b9d135427514c3788382c39c50c0bc50381f3");
assert_eq!(h(banlist_locator(&cid)), "cf2767777adcceb8a2ce51d5c3d3c20de9c74bf4867bc2373e5b12eacb5c73d8");
assert_eq!(h(everyone_locator(&cid)), "3fbe677b7b2bbddc50d08a428d4e61c8e4c7fdba586d13f1b0f421ab906eeebd");
assert_eq!(h(edition_binding(&cid)), "d09129fb5961dc61a181cdfaa2c6588396465ebbdb2c45d79b3fae0b9ad71955");
assert_eq!(h(tenure_locator(&cid, &member, &sealer)), "e252eea5e2d7172d166c2dc9c6902df736180fb2105bfaf859f990f509be57d1");
assert_eq!(h(sync_locator(&cid, &ch)), "6b08541be1e17ef80f2552273d2534d5b6eac9ab244c4044d2cf150cecfab49f");
assert_eq!(h(writers_locator(&cid, &ch)), "f79c6f82f7076ca71112846c985a42acee711f95e2b37aaf05ed4777b0779324");
assert_eq!(h(pins_locator(&cid, &ch)), "6e1aa2cb6c78baed7d417d2f6432b1b651b8b605db58515d0749f400b0593a00");
for (target, acl) in [
(OverwriteTarget::Everyone, "5b337620f7f8d929a0434be597e20ce5c4440bce8c377eb41e0b3b250b6a0ffe"),
(OverwriteTarget::Role(h(role)), "cf60d1469c48371fe46a8a2643b4dc0e9da025ba3ac1b08c07acc63ca27d1393"),
(OverwriteTarget::Member(h(member)), "1ac57124b4398297a2ac7c96099cef0f21b206e3602921f740c89408c3e69ed1"),
] {
assert_eq!(h(acl_locator(&cid, &ch.0, &overwrite_target_bytes(&cid, &target).unwrap())), acl);
}
}
#[test]
fn a_wrap_owner_key_is_the_authors_alone_and_one_per_wrap() {
let address = Keys::new(SecretKey::from_slice(&[9; 32]).unwrap()).public_key();
let other_address = Keys::new(SecretKey::from_slice(&[10; 32]).unwrap()).public_key();
let owner = wrap_owner_key(&[7; 32], &address, &[8; 32]);
assert_eq!(owner.public_key().to_hex(), "decf171297dc66aa114a80471fb2a4b43c54f66ccd0f089545f68fe2ec08a2fd");
assert_eq!(wrap_owner_key(&[7; 32], &address, &[8; 32]).public_key(), owner.public_key(), "every client of the author derives the same key");
assert_ne!(wrap_owner_key(&[7; 32], &address, &[11; 32]).public_key(), owner.public_key(), "each message has its own");
assert_ne!(wrap_owner_key(&[7; 32], &other_address, &[8; 32]).public_key(), owner.public_key(), "each plane has its own");
assert_ne!(wrap_owner_key(&[12; 32], &address, &[8; 32]).public_key(), owner.public_key(), "another author derives another key");
let secret: [u8; 32] = std::array::from_fn(|i| i as u8);
let id: [u8; 32] = std::array::from_fn(|i| 0xff - i as u8);
let channel = channel_group_key(&secret, &ChannelId(id), Epoch(0)).pk();
assert_eq!(wrap_owner_key(&secret, &channel, &[0x11; 32]).public_key().to_hex(), "5beb1665f03b5bdbd02dcb3e644a9c7ebca0e0c86b26767c7588470e4603f5dc");
}
#[test]
fn hkdf32_matches_the_hkdf_crate_for_every_input_shape() {
for ikm_len in [0usize, 16, 32, 64, 65, 200] {
let ikm: Vec<u8> = (0..ikm_len).map(|i| (i * 7 + 3) as u8).collect();
for info_len in [0usize, 1, 33, 41, 63, 64, 120] {
let info: Vec<u8> = (0..info_len).map(|i| (i * 13 + 5) as u8).collect();
let mut want = [0u8; 32];
hkdf::Hkdf::<Sha256>::new(None, &ikm).expand(&info, &mut want).unwrap();
assert_eq!(hkdf32(&ikm, &info), want, "ikm {ikm_len} info {info_len}");
}
}
}
#[test]
fn a_full_group_key_memo_ages_a_generation_and_keeps_what_is_used() {
let value = guestbook_group_key(&[7; 32], &CommunityId([8; 32]), Epoch(0));
let key = |i: u32| {
let mut k = [0u8; 32];
k[..4].copy_from_slice(&i.to_le_bytes());
k
};
let mut memo = GroupKeyMemo::default();
let cap = GROUP_KEY_MEMO_CAP as u32;
for i in 0..cap {
memo.insert(key(i), value.clone());
}
memo.insert(key(cap), value.clone());
assert_eq!((memo.cur.len(), memo.prev.len()), (1, GROUP_KEY_MEMO_CAP), "a full generation ages whole");
for round in 0..3 {
for i in 0..cap {
assert!(memo.get(&key(i)).is_some(), "round {round}: key {i} went cold");
}
}
for i in cap..cap * 3 {
memo.insert(key(i + 1), value.clone());
}
assert!(memo.get(&key(0)).is_none());
assert!(memo.cur.len() <= GROUP_KEY_MEMO_CAP && memo.prev.len() <= GROUP_KEY_MEMO_CAP);
}
fn secret() -> [u8; 32] {
let mut k = [0u8; 32];
for (i, b) in k.iter_mut().enumerate() {
*b = i as u8;
}
k
}
fn id32() -> [u8; 32] {
let mut id = [0u8; 32];
for (i, b) in id.iter_mut().enumerate() {
*b = (255 - i) as u8;
}
id
}
fn alt() -> [u8; 32] {
[0x11u8; 32]
}
fn cid() -> CommunityId {
CommunityId(id32())
}
fn chan() -> ChannelId {
ChannelId(id32())
}
const EPOCH_MULTI: u64 = 0x0102030405060708;
const GOLDEN_CHANNEL_E0_SEED: &str = "1a99a5958bf9fcc5336e6e19db42aabf36ffbfa12f38a1d5fbde2ae383ed751b";
const GOLDEN_CHANNEL_E0_PK: &str = "7a5c5dff759a63f1fc2779864487432bae3d1ea72c4ffabd39f4c1fdaf62097a";
const GOLDEN_CHANNEL_EMULTI_PK: &str = "f20c7d192cc87615d7341e86f38f85303f4708b40232d4fea521ab8217767391";
const GOLDEN_CONTROL_E0_PK: &str = "c43df20bf4d6eeaea5149619662ffe9b211f31e11bb4a59f56b6e906f702d46f";
const GOLDEN_CONTROL_SIGNER_E0_SEED: &str = "c4a3e8354d95137132087356412b67b53e025d127d45de45cff9ecf45b0c24f6";
const GOLDEN_CONTROL_SIGNER_E0_PK: &str = "718aef388257f3fd9f1bfae5cf2cbd0594a2ffc31adb5c1fe22c502c046acaee";
const GOLDEN_CONTROL_SIGNER_EMULTI_PK: &str = "e27235cc13be2f9ad65648e01ff2b63402846469c8638b5386c625688194ec7d";
const GOLDEN_GUESTBOOK_E0_PK: &str = "ad09de582026fa7a052db18bb5827fa24c15e929d59aadcc91efb8508f5368ad";
const GOLDEN_CHANNEL_ACCESS_E0_PK: &str = "901126284c4d1dfd5e753aa866e28b498825c3382611d1f5d5e929de0bcae15e";
const GOLDEN_CHANNEL_WRITER_E1_PK: &str = "7a5b45238020c162ffb7237c680934cf088ddfa47e1d5e2d630450672bc32555";
const GOLDEN_WRITER_SCOPE: &str = "211ceda4b4148fa644628adcc2fe6fd8db10878bcdf1cefe02e59ad5d85741a5";
const GOLDEN_WRITERS_LOCATOR: &str = "18b69b68718ea12d42ddc77692f72660c2320e7b5fadc0b671f9dfe265099a91";
const GOLDEN_SYNC_LOCATOR: &str = "c5ec430fce319555a3c7c0fad4800b8a245c644fc4ab17b8db3aa4e42605e882";
const GOLDEN_CHANNEL_REKEY_E1_PK: &str = "7c55cdb957e9db2b4800d687b2a07d3f7066b1a35824a1e86ba871f55e87e8b5";
const GOLDEN_BASE_REKEY_E1_PK: &str = "fb2fa44fba66ba15595f784255a1cb569531db8784432ac0e4fe838498dd9dea";
const GOLDEN_DISSOLVED_PK: &str = "4d3d55d88fdf9d9c2089651e5cbb0dfa93b6b9b10cdcb2319b0dce1a1398096a";
const GOLDEN_GRANT_LOCATOR: &str = "fd2f88cc7f1eb8d7d862c91dc22afe700c358d1845158b3f353b769ce4898e35";
const GOLDEN_BANLIST_LOCATOR: &str = "88089214afae6d3c412fd817ada44d6df4d485a53565646471e74476397693c9";
const GOLDEN_INVITE_LINKS_LOCATOR: &str = "f4ae29994165767bac23e8dce630f81b926d2c8aa150e5cbf0bdf75865e8379a";
const GOLDEN_RECIPIENT_LOCATOR: &str = "342deb400e191f0f52c81f27600934552550beb85aa9bf169f02d0e7f826cf74";
const GOLDEN_INVITE_KEY: &str = "94bf8b0d89e579ddaeccf8d9db3f5de5c86a1259c597f2560ff0120173bc5e1f";
const GOLDEN_VOICE_MEDIA_E0: &str = "8ab5b935c5e17f156563860ae6263f3700bfd836c326f8b3d7082be2fbaef6a0";
const GOLDEN_VOICE_SIGNER_E0_PK: &str = "7591f1306c265ee1dce6a07b72c76fadb3af13bf9ccce0d284cb3af6134211a1";
const GOLDEN_VOICE_SENDER: &str = "9ce1c11a39ce16a84b72c2697724a39e5c41ec07f4d703dcb01241271837599e";
const GOLDEN_COMMUNITY_ID: &str = "2b790bd59df98bdc52092b74ebd6933a89ef8eaeecc9030861cbdeae7c814c46";
const GOLDEN_EPOCH_COMMITMENT: &str = "3e6d6a3c9973c16d1ca7c5602d36979927c55c21a7e2c840f883af3f047e80a4";
fn hex(bytes: &[u8]) -> String {
crate::simd::hex::bytes_to_hex_32(bytes.try_into().expect("32 bytes"))
}
#[test]
fn channel_group_key_golden_vector() {
let gk = channel_group_key(&secret(), &chan(), Epoch(0));
assert_eq!(hex(gk.keys().secret_key().as_secret_bytes()), GOLDEN_CHANNEL_E0_SEED);
assert_eq!(gk.pk_hex(), GOLDEN_CHANNEL_E0_PK);
}
#[test]
fn channel_group_key_golden_multibyte_epoch_is_big_endian() {
let gk = channel_group_key(&secret(), &chan(), Epoch(EPOCH_MULTI));
assert_eq!(gk.pk_hex(), GOLDEN_CHANNEL_EMULTI_PK);
}
#[test]
fn control_group_key_golden_vector() {
assert_eq!(control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(), GOLDEN_CONTROL_E0_PK);
}
#[test]
fn control_signer_group_key_golden_vectors() {
let gk = control_signer_group_key(&secret(), &cid(), Epoch(0));
assert_eq!(hex(gk.keys().secret_key().as_secret_bytes()), GOLDEN_CONTROL_SIGNER_E0_SEED);
assert_eq!(gk.pk_hex(), GOLDEN_CONTROL_SIGNER_E0_PK);
assert_ne!(gk.pk_hex(), GOLDEN_CONTROL_E0_PK);
assert_eq!(
control_signer_group_key(&secret(), &cid(), Epoch(EPOCH_MULTI)).pk_hex(),
GOLDEN_CONTROL_SIGNER_EMULTI_PK
);
}
#[test]
fn guestbook_group_key_golden_vector() {
assert_eq!(guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(), GOLDEN_GUESTBOOK_E0_PK);
}
#[test]
fn channel_access_group_key_golden_vector() {
assert_eq!(channel_access_group_key(&secret(), &chan(), Epoch(0)).pk_hex(), GOLDEN_CHANNEL_ACCESS_E0_PK);
}
#[test]
fn writer_golden_vectors() {
assert_eq!(channel_writer_group_key(&secret(), &chan(), Epoch(1)).pk_hex(), GOLDEN_CHANNEL_WRITER_E1_PK);
assert_eq!(hex(&writer_scope(&chan())), GOLDEN_WRITER_SCOPE);
assert_eq!(hex(&writers_locator(&cid(), &chan())), GOLDEN_WRITERS_LOCATOR);
assert_eq!(hex(&sync_locator(&cid(), &chan())), GOLDEN_SYNC_LOCATOR);
}
#[test]
fn rekey_group_keys_golden_vectors() {
assert_eq!(
channel_rekey_group_key(&secret(), &chan(), Epoch(1)).pk_hex(),
GOLDEN_CHANNEL_REKEY_E1_PK
);
assert_eq!(
base_rekey_group_key(&secret(), &cid(), Epoch(1)).pk_hex(),
GOLDEN_BASE_REKEY_E1_PK
);
}
#[test]
fn dissolved_group_key_golden_and_is_epoch_free() {
assert_eq!(dissolved_group_key(&cid()).pk_hex(), GOLDEN_DISSOLVED_PK);
let with_epoch = GroupKey::derive(LABEL_DISSOLVED, &cid().0, &ZERO32, Some(0));
assert_ne!(with_epoch.pk_hex(), GOLDEN_DISSOLVED_PK);
}
#[test]
fn locator_golden_vectors() {
assert_eq!(hex(&grant_locator(&cid(), &alt())), GOLDEN_GRANT_LOCATOR);
assert_eq!(hex(&banlist_locator(&cid())), GOLDEN_BANLIST_LOCATOR);
assert_eq!(hex(&invite_links_locator(&cid(), &alt())), GOLDEN_INVITE_LINKS_LOCATOR);
assert_eq!(
hex(&recipient_locator(&secret(), &alt(), &id32(), Epoch(3))),
GOLDEN_RECIPIENT_LOCATOR
);
assert_eq!(hex(&invite_bundle_key(&[0x07u8; TOKEN_LEN])), GOLDEN_INVITE_KEY);
}
#[test]
fn voice_golden_vectors() {
let media = voice_media_key(&secret(), &chan(), Epoch(0));
assert_eq!(hex(&media), GOLDEN_VOICE_MEDIA_E0);
assert_eq!(voice_group_key(&secret(), &chan(), Epoch(0)).pk_hex(), GOLDEN_VOICE_SIGNER_E0_PK);
assert_eq!(
hex(&voice_sender_key(&media, "00112233445566778899aabbccddeeff")),
GOLDEN_VOICE_SENDER
);
}
#[test]
fn community_id_golden_and_verifies() {
let id = community_id_of(&secret(), &alt());
assert_eq!(hex(&id.0), GOLDEN_COMMUNITY_ID);
assert!(verify_community_id(&id, &secret(), &alt()));
assert!(!verify_community_id(&id, &alt(), &alt()));
assert!(!verify_community_id(&id, &secret(), &id32()));
}
#[test]
fn epoch_key_commitment_golden_and_binds_both_inputs() {
assert_eq!(hex(&epoch_key_commitment(Epoch(2), &secret())), GOLDEN_EPOCH_COMMITMENT);
assert_ne!(hex(&epoch_key_commitment(Epoch(3), &secret())), GOLDEN_EPOCH_COMMITMENT);
assert_ne!(hex(&epoch_key_commitment(Epoch(2), &alt())), GOLDEN_EPOCH_COMMITMENT);
}
#[test]
fn labels_domain_separate_every_plane() {
let pks = [
channel_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
control_signer_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
channel_rekey_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
base_rekey_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
voice_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
];
let unique: std::collections::HashSet<_> = pks.iter().collect();
assert_eq!(unique.len(), pks.len(), "two labels collided on one address");
}
#[test]
fn epoch_rotates_every_keyed_address() {
assert_ne!(
channel_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
channel_group_key(&secret(), &chan(), Epoch(1)).pk_hex()
);
assert_ne!(
control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
control_group_key(&secret(), &cid(), Epoch(1)).pk_hex()
);
assert_ne!(
guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
guestbook_group_key(&secret(), &cid(), Epoch(1)).pk_hex()
);
}
#[test]
fn recipient_locator_binds_direction_scope_and_epoch() {
let base = recipient_locator(&secret(), &alt(), &id32(), Epoch(1));
assert_ne!(recipient_locator(&alt(), &secret(), &id32(), Epoch(1)), base);
assert_ne!(recipient_locator(&secret(), &alt(), &id32(), Epoch(2)), base);
assert_ne!(recipient_locator(&secret(), &alt(), &ZERO32, Epoch(1)), base);
}
#[test]
fn conv_key_is_deterministic_self_ecdh() {
let a = channel_group_key(&secret(), &chan(), Epoch(0));
let b = channel_group_key(&secret(), &chan(), Epoch(0));
assert_eq!(a.conv_key().as_bytes(), b.conv_key().as_bytes());
}
}