From cdf09d3edf9c7a56bd34460fd4f128bfadc4f647 Mon Sep 17 00:00:00 2001 From: evgeny Date: Tue, 27 Oct 2026 04:25:08 +0100 Subject: [PATCH] Commit new channel identity and signed root membership before runtime publication --- src/chat/chat_channel.c | 149 +++++++++++++++++++++++++--------------- src/chat/chat_core.h | 8 ++- 2 files changed, 98 insertions(+), 59 deletions(-) diff --git a/src/chat/chat_channel.c b/src/chat/chat_channel.c index 4aece5b38..4d55a6560 100644 --- a/src/chat/chat_channel.c +++ b/src/chat/chat_channel.c @@ -88,67 +88,102 @@ int chat_core_ensure_channel_ready(struct UTUN_INSTANCE* inst, const char* ch_id /* ─── создание канала ─── */ -void chat_core_create_channel(struct UTUN_INSTANCE* inst, struct chat_channel_create* req) { - struct chat_core_ctx* cc = CC(inst); - if (!cc || !cc->initialized) { - DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: create_channel NOT INITIALIZED ch=%s", - CC_ID, req ? req->channel_id : "(null)"); - return; +int chat_core_create_channel(struct UTUN_INSTANCE* inst, const struct chat_channel_create* req) { + struct chat_core_ctx* cc = inst ? CC(inst) : NULL; + if (!cc || !cc->initialized || !cc->db || !inst->topo_groups || !req || req->owner_node_id != inst->node_id || + strnlen(req->name, sizeof(req->name)) == sizeof(req->name)) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: invalid context/owner/name"); return -1; } - if (!req) { DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: create_channel req=NULL", CC_ID); return; } + if (!sqlite3_get_autocommit(cc->db)) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: external transaction rejected"); return -1; + } + uint8_t description[CHAT_CHANNEL_DESCRIPTION_MAX], public_key[32]; + int bytes = chat_channel_description_data(req->channel_id, req->name, req->owner_node_id, + req->x25519_pubkey, req->ed25519_pubkey, description, sizeof(description)); + if (bytes < 0 || sc_compute_public_key_from_private(req->x25519_privkey, public_key) != SC_OK || + memcmp(public_key, req->x25519_pubkey, 32)) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: invalid description or X25519 key pair"); return -1; + } + EVP_PKEY* ed = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, NULL, req->ed25519_privkey, 32); + size_t public_size = 32; + int valid_pair = ed && EVP_PKEY_get_raw_public_key(ed, public_key, &public_size) == 1 && public_size == 32; + EVP_PKEY_free(ed); + if (!valid_pair || memcmp(public_key, req->ed25519_pubkey, 32) || + sc_ed25519_verify(req->ed25519_pubkey, description, (size_t)bytes, req->signature) != SC_OK) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: invalid Ed25519 key pair/description signature ch=%s", req->channel_id); return -1; + } + uint64_t group_id = strtoull(req->channel_id, NULL, 10); + if (topo_groups_find(inst->topo_groups, group_id)) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: group ID already in use ch=%s", req->channel_id); return -1; + } + time_t now = ntp_time_get_seconds(inst); + if (now <= 0) { DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: invalid join time ch=%s", req->channel_id); return -1; } + uint64_t timestamp = (uint64_t)now; + uint8_t join[64], root[64], update[64], body[MS_USERINFO_MAX + 73]; char profile[MS_USERINFO_MAX + 1]; + bytes = member_sync_build_join_msg(req->x25519_pubkey, req->ed25519_pubkey, inst->node_id, + inst->my_keys.public_key, timestamp, body, sizeof(body)); + if (bytes < 0 || sc_ed25519_sign(inst->my_ed25519_privkey, body, (size_t)bytes, join) != SC_OK || + member_sync_sign_pubkey(req->ed25519_privkey, inst->my_keys.public_key, root) < 0) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: root JOIN/invitation signing failed ch=%s", req->channel_id); return -1; + } + if (chat_core_name_userinfo(inst->name, profile, sizeof(profile))) return -1; + bytes = member_sync_build_update_msg(join, timestamp, profile, body, sizeof(body)); + if (bytes < 0 || sc_ed25519_sign(inst->my_ed25519_privkey, body, (size_t)bytes, update) != SC_OK) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: root profile signing failed ch=%s", req->channel_id); return -1; + } + sqlite3_stmt* st = NULL; const char* stage = "begin"; + int rc = sqlite3_exec(cc->db, "BEGIN IMMEDIATE /* channel creation */", NULL, NULL, NULL); + if (rc != SQLITE_OK) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: begin ch=%s rc=%d: %s", req->channel_id, rc, sqlite3_errmsg(cc->db)); return -1; + } + stage = "lookup channel"; + rc = sqlite3_prepare_v2(cc->db, "SELECT 1 FROM channels WHERE channel_id=?", -1, &st, NULL); + if (rc == SQLITE_OK) rc = sqlite3_bind_text(st, 1, req->channel_id, -1, SQLITE_STATIC); + if (rc == SQLITE_OK) rc = sqlite3_step(st); + if (rc == SQLITE_ROW) { stage = "channel already exists"; rc = SQLITE_CONSTRAINT; goto error; } + if (rc != SQLITE_DONE) goto error; + stage = "lookup finalize"; rc = sqlite3_finalize(st); st = NULL; + if (rc != SQLITE_OK) goto error; + stage = "store description"; + if (topo_node_sqlite_channel_put(cc->db, req->channel_id, req->name, req->owner_node_id, + req->x25519_pubkey, req->x25519_privkey, req->ed25519_pubkey, req->ed25519_privkey, req->signature)) { + rc = SQLITE_ERROR; goto error; + } + stage = "feedback schema"; + if (chat_feedback_ensure_channel(inst, req->channel_id)) { rc = SQLITE_ERROR; goto error; } + stage = "store root member"; + int changes = member_sync_put(inst, req->channel_id, inst->node_id, inst->my_keys.public_key, inst->my_ed25519_pubkey, + join, timestamp, update, timestamp, profile, NULL, NULL, 0, 0, root); + if (changes < 0 || !(changes & MS_APPLY_CHANGED)) { rc = SQLITE_ERROR; goto error; } + stage = "verify stored root"; + if (member_sync_author_key(inst, req->channel_id, inst->node_id, public_key) != MS_AUTHOR_ACTIVE || + memcmp(public_key, inst->my_ed25519_pubkey, 32)) { rc = SQLITE_CONSTRAINT; goto error; } + stage = "commit"; rc = sqlite3_exec(cc->db, "COMMIT /* channel creation */", NULL, NULL, NULL); + if (rc != SQLITE_OK) goto error; - DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "%s: create_channel BEGIN ch=%s name=%s", - CC_ID, req->channel_id, req->name); - - int rc = topo_node_sqlite_channel_put(cc->db, - req->channel_id, req->name, req->owner_node_id, - req->x25519_pubkey, req->x25519_privkey, - req->ed25519_pubkey, req->ed25519_privkey, - req->signature); - - if (rc != 0) { - DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: channel_put FAILED ch=%s rc=%d", - CC_ID, req->channel_id, rc); - } else { - DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "%s: channel_put OK ch=%s name=%s owner=0x%016llx", - CC_ID, req->channel_id, req->name, (unsigned long long)req->owner_node_id); - - chat_core_ensure_channel_ready(inst, req->channel_id); - - uint8_t ch_id_len = (uint8_t)strlen(req->channel_id); - uint8_t data[65]; - data[0] = ch_id_len; - memcpy(data + 1, req->channel_id, ch_id_len); - - { - uint64_t myid = inst->node_id; - uint64_t join_ts = (uint64_t)ntp_time_get_seconds(inst); - uint8_t join_sig[64]; - if (channel_sign_join(req->x25519_pubkey, req->ed25519_pubkey, myid, inst->my_keys.public_key, - join_ts, inst->my_ed25519_privkey, join_sig) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: root join signing failed ch=%s", CC_ID, req->channel_id); return; - } - - /* корень дерева приглашений: подписан ключом группы (канальный ed25519) */ - uint8_t root_sig[64]; - struct ms_member_rec root = { .node_id = myid, .x25519 = inst->my_keys.public_key, .signature = root_sig }; - if (member_sync_sign_pubkey(req->ed25519_privkey, inst->my_keys.public_key, root_sig) < 0 - || member_sync_verify_signature(cc->db, req->channel_id, &root) != 1) { - DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: root invitation signing failed ch=%s", CC_ID, req->channel_id); return; - } - int mrc = member_sync_put(inst, req->channel_id, myid, - inst->my_keys.public_key, inst->my_ed25519_pubkey, - join_sig, join_ts, NULL, 0, "{}", NULL, NULL, 0, 0, root_sig); - if (mrc < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: member_sync_put(self) FAILED ch=%s rc=%d", - CC_ID, req->channel_id, mrc); - } - /* адреса + update_ts + подпись + синк — единой функцией */ - chat_core_update_my_member(inst); + int ready = !chat_core_ensure_channel_ready(inst, req->channel_id); + if (!ready) DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "channel create: committed ch=%s, runtime activation deferred; retry preparation", req->channel_id); + member_sync_record_committed(inst, req->channel_id, inst->node_id, (unsigned)changes); + DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "channel created: ch=%s name=%s root=%016llx committed=1 runtime_ready=%d", + req->channel_id, req->name, (unsigned long long)inst->node_id, ready); + uint8_t event[21]; size_t length = strlen(req->channel_id); event[0] = (uint8_t)length; + memcpy(event + 1, req->channel_id, length); chat_event_post(inst, CHAT_EVT_CHANNEL_UPDATED, event, (int)length + 1); + return 0; +error: + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: ch=%s stage=%s rc=%d (%s) db=%s", + req->channel_id, stage, rc, sqlite3_errstr(rc), sqlite3_errmsg(cc->db)); + rc = sqlite3_finalize(st); + if (rc != SQLITE_OK) DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: cleanup finalize ch=%s rc=%d", req->channel_id, rc); + if (!sqlite3_get_autocommit(cc->db)) { + rc = sqlite3_exec(cc->db, "ROLLBACK", NULL, NULL, NULL); + if (rc != SQLITE_OK) DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: rollback ch=%s rc=%d: %s", + req->channel_id, rc, sqlite3_errmsg(cc->db)); + if (!sqlite3_get_autocommit(cc->db)) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "channel create: transaction remains open ch=%s; requesting owner stop/DB close", req->channel_id); + utun_instance_stop(inst); } - - chat_event_post(inst, CHAT_EVT_CHANNEL_UPDATED, data, 1 + ch_id_len); } + return -1; } void chat_core_create_channel_trampoline(void* arg) { diff --git a/src/chat/chat_core.h b/src/chat/chat_core.h index e5e90ed17..8326044e1 100644 --- a/src/chat/chat_core.h +++ b/src/chat/chat_core.h @@ -134,8 +134,12 @@ struct chat_create_auto_arg { struct UTUN_INSTANCE* inst; char name[128]; }; * проверенные данные БД сохраняются. Членства на других узлах не даёт. */ int chat_core_ensure_channel_ready(struct UTUN_INSTANCE* inst, const char* ch_id); -// Создать канал по готовым ключам и метаданным req; req остаётся у вызывающего. -void chat_core_create_channel(struct UTUN_INSTANCE* inst, struct chat_channel_create* req); +/* Создать новый канал:проверить пары ключей/подпись,одним commit сохранить описание,root JOIN/профиль/приглашение и Merkle. + * 0 — сохранено,-1 — отказ без публикации;req заимствован и не меняется. Владелец — этот instance. + * Внешняя транзакция и занятый ID запрещены. CHANNEL_UPDATED — после commit и попытки runtime-подготовки. + * Отказ подготовки не отменяет созданный канал:можно повторить ensure_channel_ready. Неудачный rollback + * с открытой транзакцией запрашивает stop/закрытие БД владельцем вне callback. */ +int chat_core_create_channel(struct UTUN_INSTANCE* inst, const struct chat_channel_create* req); void chat_core_create_channel_trampoline(void* arg);