navid/veins / commit

0f2b7d81e2f0

Navid M <navidmomtahen@gmail.com> · 2026-11-27

parents: 65edf85423c0

Browse files at this commit · Download source

all: full parity for C++ baseline
--- a/veins-cpprewrite/CMakeLists.txt+++ b/veins-cpprewrite/CMakeLists.txt@@ -23,6 +23,30 @@ set(BUILD_SHARED_LIBS OFF)  find_package(Threads REQUIRED)++# ---------------------------------------------------------------------------+# OpenSSL: TLS 1.3, Ed25519, and cryptographic randomness for the native+# protocol. Homebrew keeps OpenSSL keg-only on macOS, so try `brew` before the+# default search when the caller did not provide an explicit root.+# ---------------------------------------------------------------------------+if(APPLE AND NOT OPENSSL_ROOT_DIR AND NOT DEFINED ENV{OPENSSL_ROOT_DIR})+    find_program(VN_BREW_EXECUTABLE brew)+    if(VN_BREW_EXECUTABLE)+        foreach(_formula openssl@3 openssl)+            execute_process(+                COMMAND "${VN_BREW_EXECUTABLE}" --prefix "${_formula}"+                OUTPUT_VARIABLE _prefix+                OUTPUT_STRIP_TRAILING_WHITESPACE+                ERROR_QUIET+            )+            if(_prefix AND EXISTS "${_prefix}/include/openssl")+                set(OPENSSL_ROOT_DIR "${_prefix}")+                break()+            endif()+        endforeach()+    endif()+endif()+find_package(OpenSSL REQUIRED)  # --------------------------------------------------------------------------- # zstd: prefer an installed package, otherwise a system library, otherwise@@ -111,12 +135,26 @@     src/oplog.cpp     src/merge.cpp     src/cli.cpp+    src/crypto.cpp+    src/net.cpp+    src/wire.cpp+    src/protocol.cpp+    src/auth.cpp+    src/server.cpp+    src/promisor.cpp+    src/net_commands.cpp )  target_include_directories(vn PRIVATE src)-target_link_libraries(vn PRIVATE BLAKE3::blake3 ${VN_ZSTD_TARGET} Threads::Threads)+target_link_libraries(vn PRIVATE+    BLAKE3::blake3+    ${VN_ZSTD_TARGET}+    OpenSSL::SSL+    OpenSSL::Crypto+    Threads::Threads+) if(WIN32)-    target_link_libraries(vn PRIVATE bcrypt)+    target_link_libraries(vn PRIVATE bcrypt ws2_32 crypt32) endif() target_compile_definitions(vn PRIVATE VN_VERSION="0.0.1") --- /dev/null+++ b/veins-cpprewrite/src/auth.cpp@@ -0,0 +1,521 @@+#include "auth.h"++#include "store.h"++#include <algorithm>+#include <cstdlib>+#include <cstring>++#if defined(_WIN32)+#include <io.h>+#else+#include <sys/stat.h>+#include <unistd.h>+#endif++namespace vn::auth {++namespace {++std::optional<std::string> env_value(const char *name) {+  const char *value = std::getenv(name);+  if (!value || !*value)+    return std::nullopt;+  return std::string(value);+}++std::string lower_ascii(std::string_view text) {+  std::string out(text);+  for (char &c : out) {+    if (c >= 'A' && c <= 'Z')+      c = static_cast<char>(c + 32);+  }+  return out;+}++std::string_view trim_view(std::string_view text) {+  std::size_t start = 0;+  std::size_t end = text.size();+  auto blank = [](char c) {+    return c == ' ' || c == '\t' || c == '\r' || c == '\n';+  };+  while (start < end && blank(text[start]))+    ++start;+  while (end > start && blank(text[end - 1]))+    --end;+  return text.substr(start, end - start);+}++int file_mode(const fs::path &path) {+#if defined(_WIN32)+  (void)path;+  return 0600;+#else+  struct stat info {};+  if (::stat(path.c_str(), &info) != 0)+    return -1;+  return static_cast<int>(info.st_mode & 07777);+#endif+}++bool set_mode(const fs::path &path, int mode) {+#if defined(_WIN32)+  (void)path;+  (void)mode;+  return true;+#else+  return ::chmod(path.c_str(), static_cast<mode_t>(mode)) == 0;+#endif+}++bool valid_key_name(std::string_view name) {+  if (name.empty() || name.size() > 128)+    return false;+  for (char c : name) {+    if (c == '/' || c == '\\' || c == '\0')+      return false;+  }+  return true;+}++std::string hex_encode(std::string_view data) {+  static constexpr char digits[] = "0123456789abcdef";+  std::string out;+  out.reserve(data.size() * 2);+  for (char raw : data) {+    const auto c = static_cast<unsigned char>(raw);+    out.push_back(digits[c >> 4]);+    out.push_back(digits[c & 15]);+  }+  return out;+}++std::optional<std::string> hex_decode(std::string_view text) {+  if (text.empty() || text.size() % 2 != 0)+    return std::nullopt;+  auto value = [](char c) -> int {+    if (c >= '0' && c <= '9')+      return c - '0';+    if (c >= 'a' && c <= 'f')+      return c - 'a' + 10;+    return -1;+  };+  std::string out;+  out.reserve(text.size() / 2);+  for (std::size_t i = 0; i < text.size(); i += 2) {+    const int high = value(text[i]);+    const int low = value(text[i + 1]);+    if (high < 0 || low < 0)+      return std::nullopt;+    out.push_back(static_cast<char>((high << 4) | low));+  }+  return out;+}++std::string_view strip_user(std::string_view authority) {+  const auto at = authority.rfind('@');+  if (at != std::string_view::npos)+    return authority.substr(at + 1);+  return authority;+}++std::optional<std::string> authority_of(std::string_view input) {+  std::size_t start = 0;+  const auto scheme = input.find("://");+  if (scheme != std::string_view::npos)+    start = scheme + 3;+  if (start >= input.size())+    return std::nullopt;+  const auto slash = input.find('/', start);+  const std::size_t end = slash == std::string_view::npos ? input.size() : slash;+  if (end <= start)+    return std::nullopt;+  const std::string_view raw = input.substr(start, end - start);+  const std::string_view host = strip_user(raw);+  if (host.empty())+    return std::nullopt;+  return lower_ascii(host);+}++std::optional<std::string> host_without_port(std::string_view host) {+  if (host.empty() || host.front() == '[')+    return std::nullopt;+  const auto colon = host.rfind(':');+  if (colon == std::string_view::npos || colon == 0)+    return std::nullopt;+  return std::string(host.substr(0, colon));+}++fs::path target_path(const fs::path &dir, std::string_view target) {+  return dir / hex_encode(target);+}++std::optional<std::string> read_credential(const fs::path &path) {+  auto data = read_file_opt(path);+  if (!data)+    return std::nullopt;+  const std::string_view text(reinterpret_cast<const char *>(data->data()),+                              data->size());+  const std::string_view value = trim_view(text);+  if (value.empty())+    return std::nullopt;+  return std::string(value);+}++std::optional<std::string> lookup_credential(const fs::path &dir,+                                             std::string_view target) {+  return read_credential(target_path(dir, target));+}++std::vector<std::string_view> tokenize(std::string_view line) {+  std::vector<std::string_view> out;+  std::size_t start = 0;+  for (std::size_t i = 0; i <= line.size(); ++i) {+    const bool at_end = i == line.size();+    if (at_end || line[i] == ' ' || line[i] == '\t') {+      if (i > start)+        out.push_back(line.substr(start, i - start));+      start = i + 1;+    }+  }+  return out;+}++Access invalid_access(std::int64_t line) {+  Access out;+  out.valid = false;+  out.error_line = line;+  return out;+}++} // namespace++// ---------------------------------------------------------------------------+// Client keys+// ---------------------------------------------------------------------------++fs::path key_dir() {+  if (auto xdg = env_value("XDG_CONFIG_HOME"))+    return path_from_bytes(*xdg) / "veins" / "keys";+  if (auto home = env_value("HOME"))+    return path_from_bytes(*home) / ".config" / "veins" / "keys";+#if defined(_WIN32)+  if (auto appdata = env_value("APPDATA"))+    return path_from_bytes(*appdata) / "veins" / "keys";+#endif+  return fs::path(".veins-keys");+}++fs::path key_path(std::string_view name) {+  return key_dir() / (std::string(name) + ".key");+}++std::optional<Key> load_key(std::string_view name) {+  if (!valid_key_name(name))+    return std::nullopt;+  const fs::path path = key_path(name);+  const int mode = file_mode(path);+  if (mode < 0 || (mode & 63) != 0)+    return std::nullopt;+  auto data = read_file_opt(path);+  if (!data || data->size() != 33 || (*data)[0] != 1)+    return std::nullopt;+  std::vector<std::uint8_t> seed(data->begin() + 1, data->end());+  auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));+  if (!public_key)+    return std::nullopt;+  Key key;+  key.name = std::string(name);+  key.seed = std::move(seed);+  key.public_key = *public_key;+  key.fingerprint = key_fingerprint(*public_key);+  return key;+}++std::optional<Key> generate_key(std::string_view name) {+  if (!valid_key_name(name))+    return std::nullopt;+  const fs::path dir = key_dir();+  if (!ensure_directory(dir))+    return std::nullopt;+  (void)set_mode(dir, 0700);+  const auto seed = secure_random(32);+  if (seed.size() != 32)+    return std::nullopt;+  auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));+  if (!public_key)+    return std::nullopt;+  std::vector<std::uint8_t> body;+  body.reserve(33);+  body.push_back(1);+  body.insert(body.end(), seed.begin(), seed.end());+  const fs::path path = key_path(name);+  if (!write_file(path, Bytes(body.data(), body.size())))+    return std::nullopt;+  (void)set_mode(path, 0600);+  Key key;+  key.name = std::string(name);+  key.seed = seed;+  key.public_key = *public_key;+  key.fingerprint = key_fingerprint(*public_key);+  return key;+}++std::vector<std::string> list_key_names() {+  std::vector<std::string> out;+  const fs::path dir = key_dir();+  if (!path_is_dir(dir))+    return out;+  for (const auto &name : list_directory(dir)) {+    if (name.size() > 4 && name.compare(name.size() - 4, 4, ".key") == 0)+      out.push_back(name.substr(0, name.size() - 4));+  }+  return out;+}++// ---------------------------------------------------------------------------+// Per-user key selection+// ---------------------------------------------------------------------------++fs::path auth_dir() {+  const fs::path dir = key_dir();+  const fs::path parent = dir.parent_path();+  if (parent.empty())+    return fs::path(".veins-auth");+  return parent / "auth";+}++std::string normalize_target(std::string_view input) {+  const std::string_view trimmed = trim_view(input);+  if (trimmed.empty() || trimmed == "default")+    return "default";+  if (auto authority = authority_of(trimmed))+    return *authority;+  const auto slash = trimmed.find('/');+  const std::string_view raw =+      slash == std::string_view::npos ? trimmed : trimmed.substr(0, slash);+  const std::string_view host = strip_user(raw);+  if (host.empty())+    return "default";+  return lower_ascii(host);+}++bool set_key(std::string_view target, std::string_view key_name) {+  if (target.empty() || key_name.empty())+    return false;+  const fs::path dir = auth_dir();+  if (!ensure_directory(dir))+    return false;+  return write_file(target_path(dir, target), bytes_of(key_name));+}++bool remove_key(std::string_view target) {+  return remove_file(target_path(auth_dir(), target));+}++std::vector<std::string> list_credential_lines() {+  std::vector<std::string> out;+  const fs::path dir = auth_dir();+  if (!path_is_dir(dir))+    return out;+  for (const auto &name : list_directory(dir)) {+    auto decoded = hex_decode(name);+    if (!decoded)+      continue;+    auto key = read_credential(target_path(dir, *decoded));+    if (!key)+      continue;+    out.push_back(*decoded + ": " + *key + "\n");+  }+  return out;+}++bool local_key_exists(std::string_view name) {+  if (name.empty() || name.starts_with("ed25519:"))+    return false;+  return load_key(name).has_value();+}++std::optional<std::string> key_for_url(std::string_view url) {+  const fs::path dir = auth_dir();+  if (auto host = authority_of(url)) {+    if (auto exact = lookup_credential(dir, *host))+      return exact;+    if (auto base = host_without_port(*host)) {+      if (auto without_port = lookup_credential(dir, *base))+        return without_port;+    }+  }+  return lookup_credential(dir, "default");+}++// ---------------------------------------------------------------------------+// Server access policy+// ---------------------------------------------------------------------------++Access empty_access() { return Access{}; }++fs::path access_path(const fs::path &repo_root) {+  return veins_dir(repo_root) / "access";+}++Access load_access(const fs::path &repo_root) {+  const fs::path path = access_path(repo_root);+  const int mode = file_mode(path);+  if (mode >= 0 && (mode & 18) != 0)+    return invalid_access(0);+  auto data = read_file_opt(path);+  if (!data)+    return empty_access();+  const std::string_view text(reinterpret_cast<const char *>(data->data()),+                              data->size());+  Access access;+  std::size_t start = 0;+  std::int64_t line_no = 0;+  std::size_t i = 0;+  for (;;) {+    const bool at_end = i >= text.size();+    if (at_end || text[i] == '\n') {+      ++line_no;+      const std::string_view line = trim_view(text.substr(start, i - start));+      if (!line.empty() && line.front() != '#') {+        const auto tokens = tokenize(line);+        bool bad = false;+        if (tokens.size() == 2 && tokens[0] == "anonymous") {+          if (tokens[1] == "read")+            access.anonymous_read = true;+          else+            bad = true;+        } else if (tokens.size() >= 3 && tokens[0] == "allow") {+          std::uint8_t role = 0;+          if (tokens[1] == "read")+            role = ROLE_READ;+          else if (tokens[1] == "write")+            role = ROLE_WRITE;+          else+            bad = true;+          auto public_key = parse_public_key(tokens[2]);+          if (!public_key)+            bad = true;+          if (!bad) {+            const bool duplicate =+                std::any_of(access.entries.begin(), access.entries.end(),+                            [&](const AccessEntry &entry) {+                              return std::memcmp(entry.public_key.data(),+                                                 public_key->data(),+                                                 public_key->size()) == 0;+                            });+            if (duplicate) {+              bad = true;+            } else {+              AccessEntry entry;+              entry.public_key = *public_key;+              entry.role = role;+              if (tokens.size() >= 4)+                entry.name = std::string(tokens[3]);+              access.entries.push_back(std::move(entry));+            }+          }+        } else {+          bad = true;+        }+        if (bad)+          return invalid_access(line_no);+      }+      start = i + 1;+    }+    if (at_end)+      break;+    ++i;+  }+  return access;+}++bool write_access(const fs::path &repo_root, const Access &access) {+  std::string body = "# veins access policy\n";+  if (access.anonymous_read)+    body += "anonymous read\n";+  for (const auto &entry : access.entries) {+    if (entry.name.size() > 64)+      return false;+    body += "allow ";+    body += entry.role == ROLE_WRITE ? "write" : "read";+    body += " ";+    body += format_public_key(entry.public_key);+    if (!entry.name.empty()) {+      body += " ";+      body += entry.name;+    }+    body += "\n";+  }+  const fs::path path = access_path(repo_root);+  if (!write_file(path, bytes_of(body)))+    return false;+  (void)set_mode(path, 0600);+  return true;+}++std::uint8_t role_for(const Access &access, const PublicKey *public_key) {+  if (!public_key) {+    if (access.anonymous_read)+      return ROLE_READ;+    return ROLE_ANONYMOUS;+  }+  for (const auto &entry : access.entries) {+    if (std::memcmp(entry.public_key.data(), public_key->data(),+                    public_key->size()) == 0) {+      return entry.role;+    }+  }+  return ROLE_UNKNOWN;+}++bool add_access(const fs::path &repo_root, std::uint8_t role,+                const PublicKey &public_key, std::string_view name) {+  Access access = load_access(repo_root);+  if (!access.valid)+    return false;+  for (const auto &entry : access.entries) {+    if (std::memcmp(entry.public_key.data(), public_key.data(),+                    public_key.size()) == 0)+      return false;+  }+  AccessEntry entry;+  entry.public_key = public_key;+  entry.role = role;+  entry.name = std::string(name);+  access.entries.push_back(std::move(entry));+  return write_access(repo_root, access);+}++bool remove_access(const fs::path &repo_root, std::string_view fingerprint,+                   std::string_view name) {+  Access access = load_access(repo_root);+  if (!access.valid)+    return false;+  bool removed = false;+  std::vector<AccessEntry> kept;+  kept.reserve(access.entries.size());+  for (const auto &entry : access.entries) {+    const bool match_fingerprint =+        !fingerprint.empty() && key_fingerprint(entry.public_key) == fingerprint;+    const bool match_name = !name.empty() && entry.name == name;+    if (match_fingerprint || match_name) {+      removed = true;+    } else {+      kept.push_back(entry);+    }+  }+  access.entries = std::move(kept);+  return removed && write_access(repo_root, access);+}++bool set_anonymous(const fs::path &repo_root, bool enabled) {+  Access access = load_access(repo_root);+  if (!access.valid)+    return false;+  access.anonymous_read = enabled;+  return write_access(repo_root, access);+}++} // namespace vn::auth--- /dev/null+++ b/veins-cpprewrite/src/auth.h@@ -0,0 +1,75 @@+#pragma once++#include "crypto.h"++#include <cstdint>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++namespace vn::auth {++constexpr std::uint8_t ROLE_ANONYMOUS = 0;+constexpr std::uint8_t ROLE_READ = 1;+constexpr std::uint8_t ROLE_WRITE = 2;+constexpr std::uint8_t ROLE_UNKNOWN = 255;++// ---------------------------------------------------------------------------+// Client keys+// ---------------------------------------------------------------------------++struct Key {+  std::string name;+  std::vector<std::uint8_t> seed;+  PublicKey public_key{};+  std::string fingerprint;+};++fs::path key_dir();+fs::path key_path(std::string_view name);+std::optional<Key> load_key(std::string_view name);+std::optional<Key> generate_key(std::string_view name);+std::vector<std::string> list_key_names();++// ---------------------------------------------------------------------------+// Per-user key selection+// ---------------------------------------------------------------------------++fs::path auth_dir();+std::string normalize_target(std::string_view target);+bool set_key(std::string_view target, std::string_view key_name);+bool remove_key(std::string_view target);+std::vector<std::string> list_credential_lines();+bool local_key_exists(std::string_view name);+std::optional<std::string> key_for_url(std::string_view url);++// ---------------------------------------------------------------------------+// Server access policy+// ---------------------------------------------------------------------------++struct AccessEntry {+  PublicKey public_key{};+  std::string name;+  std::uint8_t role = ROLE_READ;+};++struct Access {+  bool valid = true;+  std::int64_t error_line = 0;+  bool anonymous_read = false;+  std::vector<AccessEntry> entries;+};++Access empty_access();+fs::path access_path(const fs::path &repo_root);+Access load_access(const fs::path &repo_root);+bool write_access(const fs::path &repo_root, const Access &access);+bool add_access(const fs::path &repo_root, std::uint8_t role,+                const PublicKey &public_key, std::string_view name);+bool remove_access(const fs::path &repo_root, std::string_view fingerprint,+                   std::string_view name);+bool set_anonymous(const fs::path &repo_root, bool enabled);+std::uint8_t role_for(const Access &access, const PublicKey *public_key);++} // namespace vn::auth--- a/veins-cpprewrite/src/cli.cpp+++ b/veins-cpprewrite/src/cli.cpp@@ -2,6 +2,8 @@  #include "local_commands.h" #include "merge.h"+#include "net_commands.h"+#include "promisor.h" #include "store.h" #include "worktree.h" @@ -2210,10 +2212,8 @@     show_version();   else if (cmd == "help")     show_help();-  else if (cmd == "git" || cmd == "remote" || cmd == "clone" ||-           cmd == "fetch" || cmd == "push" || cmd == "serve" || cmd == "key" ||-           cmd == "auth" || cmd == "access" || cmd == "whoami" ||-           cmd == "bench-import")+  else if (net_help(cmd)) {+  } else if (cmd == "git" || cmd == "bench-import")     show_unimplemented(cmd);   else {     usage();@@ -2227,6 +2227,7 @@ } // namespace  int cli_run(const std::vector<std::string> &args) {+  install_promisor_fetcher();   if (args.size() < 2) {     usage();     return 1;@@ -2289,9 +2290,26 @@   if (cmd == "help" || cmd == "-help" || cmd == "-h")     return run_help(args); -  if (cmd == "git" || cmd == "remote" || cmd == "clone" || cmd == "fetch" ||-      cmd == "push" || cmd == "serve" || cmd == "key" || cmd == "auth" ||-      cmd == "access" || cmd == "whoami" || cmd == "bench-import") {+  if (cmd == "remote")+    return remote_run(args);+  if (cmd == "clone")+    return clone_run(args);+  if (cmd == "fetch")+    return fetch_run(args);+  if (cmd == "push")+    return push_run(args);+  if (cmd == "serve")+    return serve_run(args);+  if (cmd == "key")+    return key_run(args);+  if (cmd == "auth")+    return auth_run(args);+  if (cmd == "access")+    return access_run(args);+  if (cmd == "whoami")+    return whoami_run(args);++  if (cmd == "git" || cmd == "bench-import") {     error_prefix();     std::cout << "command '" << cmd << "' is not available in this stage\n";     return 1;--- /dev/null+++ b/veins-cpprewrite/src/crypto.cpp@@ -0,0 +1,209 @@+#include "crypto.h"++#include <blake3.h>++#include <openssl/evp.h>+#include <openssl/rand.h>++#include <cstring>++namespace vn {++namespace {++// The reference implementation hashes the NUL terminator as well, so the+// domain is 12 bytes rather than the 11 characters in the specification.+constexpr char FINGERPRINT_DOMAIN[] = "veins/key/1";++PublicKey key_from_span(Bytes seed) {+  PublicKey out{};+  std::memcpy(out.data(), seed.data(), out.size());+  return out;+}++} // namespace++std::optional<PublicKey> ed25519_public_from_seed(Bytes seed) {+  if (seed.size() != 32)+    return std::nullopt;+  EVP_PKEY *pkey =+      EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);+  if (!pkey)+    return std::nullopt;+  PublicKey out{};+  std::size_t len = out.size();+  const int ok = EVP_PKEY_get_raw_public_key(pkey, out.data(), &len);+  EVP_PKEY_free(pkey);+  if (ok != 1 || len != out.size())+    return std::nullopt;+  return out;+}++std::optional<Signature> ed25519_sign(Bytes seed, Bytes message) {+  if (seed.size() != 32)+    return std::nullopt;+  EVP_PKEY *pkey =+      EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);+  if (!pkey)+    return std::nullopt;+  EVP_MD_CTX *ctx = EVP_MD_CTX_new();+  if (!ctx) {+    EVP_PKEY_free(pkey);+    return std::nullopt;+  }+  Signature out{};+  std::size_t sig_len = out.size();+  bool ok = false;+  if (EVP_DigestSignInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&+      EVP_DigestSign(ctx, out.data(), &sig_len, message.data(),+                     message.size()) == 1 &&+      sig_len == out.size()) {+    ok = true;+  }+  EVP_MD_CTX_free(ctx);+  EVP_PKEY_free(pkey);+  if (!ok)+    return std::nullopt;+  return out;+}++bool ed25519_verify(const PublicKey &public_key, Bytes message,+                    Bytes signature) {+  if (signature.size() != 64)+    return false;+  EVP_PKEY *pkey =+      EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr,+                                  public_key.data(), public_key.size());+  if (!pkey)+    return false;+  EVP_MD_CTX *ctx = EVP_MD_CTX_new();+  if (!ctx) {+    EVP_PKEY_free(pkey);+    return false;+  }+  bool ok = false;+  if (EVP_DigestVerifyInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&+      EVP_DigestVerify(ctx, signature.data(), signature.size(),+                       message.data(), message.size()) == 1) {+    ok = true;+  }+  EVP_MD_CTX_free(ctx);+  EVP_PKEY_free(pkey);+  return ok;+}++FingerprintBytes key_fingerprint_bytes(const PublicKey &public_key) {+  blake3_hasher hasher;+  blake3_hasher_init(&hasher);+  blake3_hasher_update(&hasher, FINGERPRINT_DOMAIN,+                       sizeof(FINGERPRINT_DOMAIN));+  blake3_hasher_update(&hasher, public_key.data(), public_key.size());+  std::array<std::uint8_t, 32> digest{};+  blake3_hasher_finalize(&hasher, digest.data(), digest.size());+  FingerprintBytes out{};+  std::memcpy(out.data(), digest.data(), out.size());+  return out;+}++std::string key_fingerprint(const PublicKey &public_key) {+  const auto raw = key_fingerprint_bytes(public_key);+  return base32_text(Bytes(raw.data(), raw.size()));+}++std::string base32_text(Bytes raw) {+  static constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";+  std::string out;+  out.reserve((raw.size() * 8) / 5 + 2);+  std::uint64_t bits = 0;+  std::size_t nbits = 0;+  for (std::uint8_t byte : raw) {+    bits = (bits << 8) | byte;+    nbits += 8;+    while (nbits >= 5) {+      nbits -= 5;+      out.push_back(alphabet[(bits >> nbits) & 31u]);+    }+  }+  if (nbits > 0)+    out.push_back(alphabet[(bits << (5 - nbits)) & 31u]);+  return out;+}++std::string base64url_encode(Bytes raw) {+  static constexpr char alphabet[] =+      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";+  std::string out;+  out.reserve((raw.size() * 4) / 3 + 4);+  std::uint32_t acc = 0;+  std::size_t bits = 0;+  for (std::uint8_t byte : raw) {+    acc = (acc << 8) | byte;+    bits += 8;+    while (bits >= 6) {+      bits -= 6;+      out.push_back(alphabet[(acc >> bits) & 63u]);+    }+  }+  if (bits > 0)+    out.push_back(alphabet[(acc << (6 - bits)) & 63u]);+  return out;+}++std::optional<std::vector<std::uint8_t>>+base64url_decode(std::string_view text) {+  if (text.empty())+    return std::nullopt;+  static const auto value_of = [](char c) -> int {+    if (c >= 'A' && c <= 'Z')+      return c - 'A';+    if (c >= 'a' && c <= 'z')+      return c - 'a' + 26;+    if (c >= '0' && c <= '9')+      return c - '0' + 52;+    if (c == '-')+      return 62;+    if (c == '_')+      return 63;+    return -1;+  };+  std::vector<std::uint8_t> out;+  out.reserve((text.size() * 6) / 8);+  std::uint32_t acc = 0;+  std::size_t bits = 0;+  for (char c : text) {+    const int value = value_of(c);+    if (value < 0)+      return std::nullopt;+    acc = (acc << 6) | static_cast<std::uint32_t>(value);+    bits += 6;+    if (bits >= 8) {+      bits -= 8;+      out.push_back(static_cast<std::uint8_t>((acc >> bits) & 255u));+    }+  }+  return out;+}++std::string format_public_key(const PublicKey &public_key) {+  return "ed25519:" ++         base64url_encode(Bytes(public_key.data(), public_key.size()));+}++std::optional<PublicKey> parse_public_key(std::string_view text) {+  constexpr std::string_view prefix = "ed25519:";+  if (!text.starts_with(prefix))+    return std::nullopt;+  auto decoded = base64url_decode(text.substr(prefix.size()));+  if (!decoded || decoded->size() != 32)+    return std::nullopt;+  return key_from_span(Bytes(decoded->data(), decoded->size()));+}++std::vector<std::uint8_t> secure_random(std::size_t count) {+  std::vector<std::uint8_t> out(count);+  if (count != 0 && RAND_bytes(out.data(), static_cast<int>(count)) != 1)+    out.clear();+  return out;+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/crypto.h@@ -0,0 +1,37 @@+#pragma once++#include "common.h"++#include <array>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++namespace vn {++using PublicKey = std::array<std::uint8_t, 32>;+using Signature = std::array<std::uint8_t, 64>;+using FingerprintBytes = std::array<std::uint8_t, 16>;++std::optional<PublicKey> ed25519_public_from_seed(Bytes seed);+std::optional<Signature> ed25519_sign(Bytes seed, Bytes message);+bool ed25519_verify(const PublicKey &public_key, Bytes message,+                    Bytes signature);++FingerprintBytes key_fingerprint_bytes(const PublicKey &public_key);+std::string key_fingerprint(const PublicKey &public_key);++// RFC 4648 base32 with no padding. The reference implementation emits+// fingerprints in uppercase, so this matches it.+std::string base32_text(Bytes raw);+// Unpadded base64url.+std::string base64url_encode(Bytes raw);+std::optional<std::vector<std::uint8_t>> base64url_decode(std::string_view text);++std::string format_public_key(const PublicKey &public_key);+std::optional<PublicKey> parse_public_key(std::string_view text);++std::vector<std::uint8_t> secure_random(std::size_t count);++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/net.cpp@@ -0,0 +1,753 @@+#include "net.h"++#include <algorithm>+#include <cerrno>+#include <climits>+#include <cstring>++#if defined(_WIN32)+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <winsock2.h>+#include <ws2tcpip.h>+#include <windows.h>+#include <io.h>+#endif++#include <openssl/err.h>+#include <openssl/ssl.h>+#include <openssl/x509.h>+#include <openssl/x509_vfy.h>++#if !defined(_WIN32)+#include <arpa/inet.h>+#include <fcntl.h>+#include <limits.h>+#include <netdb.h>+#include <netinet/in.h>+#include <signal.h>+#include <sys/socket.h>+#include <sys/types.h>+#include <sys/wait.h>+#include <unistd.h>+#if defined(__APPLE__)+#include <mach-o/dyld.h>+#endif+#endif++namespace vn::net {++namespace {++#if defined(_WIN32)+void ensure_winsock() {+  static const bool initialized = [] {+    WSADATA data{};+    return WSAStartup(MAKEWORD(2, 2), &data) == 0;+  }();+  (void)initialized;+}++std::wstring widen_utf8(std::string_view text) {+  if (text.empty())+    return {};+  const int len = MultiByteToWideChar(CP_UTF8, 0, text.data(),+                                      static_cast<int>(text.size()), nullptr, 0);+  std::wstring out(static_cast<std::size_t>(len), L'\0');+  MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()),+                      out.data(), len);+  return out;+}++// Quote one argument for CreateProcessW's command line.+std::wstring quote_windows_arg(std::wstring_view arg) {+  if (!arg.empty() &&+      arg.find_first_of(L" \t\n\v\"") == std::wstring_view::npos)+    return std::wstring(arg);+  std::wstring out = L"\"";+  for (std::size_t i = 0; i < arg.size(); ++i) {+    std::size_t backslashes = 0;+    while (i < arg.size() && arg[i] == L'\\') {+      ++backslashes;+      ++i;+    }+    if (i == arg.size()) {+      out.append(backslashes * 2, L'\\');+      break;+    }+    if (arg[i] == L'"') {+      out.append(backslashes * 2 + 1, L'\\');+      out.push_back(L'"');+    } else {+      out.append(backslashes, L'\\');+      out.push_back(arg[i]);+    }+  }+  out.push_back(L'"');+  return out;+}++std::wstring build_windows_command_line(+    const std::vector<std::string> &argv) {+  std::wstring out;+  for (std::size_t i = 0; i < argv.size(); ++i) {+    if (i != 0)+      out.push_back(L' ');+    out += quote_windows_arg(widen_utf8(argv[i]));+  }+  return out;+}+#endif++std::string ssl_error_string() {+  unsigned long code = ERR_get_error();+  if (code == 0)+    return {};+  char buffer[256];+  ERR_error_string_n(code, buffer, sizeof(buffer));+  return std::string(buffer);+}++} // namespace++// ---------------------------------------------------------------------------+// Stream+// ---------------------------------------------------------------------------++Stream::Stream(Stream &&other) noexcept { *this = std::move(other); }++Stream &Stream::operator=(Stream &&other) noexcept {+  if (this == &other)+    return *this;+  close();+  kind_ = other.kind_;+  fd_in_ = other.fd_in_;+  fd_out_ = other.fd_out_;+  ssl_ = other.ssl_;+#if defined(_WIN32)+  process_ = other.process_;+  process_id_ = other.process_id_;+#else+  pid_ = other.pid_;+#endif+  open_ = other.open_;+  other.open_ = false;+  other.ssl_ = nullptr;+  other.fd_in_ = 0;+  other.fd_out_ = 0;+#if defined(_WIN32)+  other.process_ = nullptr;+  other.process_id_ = 0;+#else+  other.pid_ = 0;+#endif+  return *this;+}++Stream::~Stream() { close(); }++Stream Stream::stdio_stream() {+  Stream stream;+  stream.kind_ = Kind::Stdio;+#if defined(_WIN32)+  stream.fd_in_ =+      reinterpret_cast<Socket>(GetStdHandle(STD_INPUT_HANDLE));+  stream.fd_out_ =+      reinterpret_cast<Socket>(GetStdHandle(STD_OUTPUT_HANDLE));+#else+  stream.fd_in_ = 0;+  stream.fd_out_ = 1;+#endif+  stream.open_ = true;+  return stream;+}++Stream Stream::fd_stream(Socket fd) {+  Stream stream;+  stream.kind_ = Kind::Fd;+  stream.fd_in_ = fd;+  stream.fd_out_ = fd;+  stream.open_ = true;+  return stream;+}++Stream Stream::tls_stream(Socket fd, void *ssl) {+  Stream stream;+  stream.kind_ = Kind::Tls;+  stream.fd_in_ = fd;+  stream.fd_out_ = fd;+  stream.ssl_ = ssl;+  stream.open_ = true;+  return stream;+}++std::optional<Stream> Stream::spawn_argv(const std::vector<std::string> &argv) {+  return vn::net::spawn_argv(argv);+}++std::int64_t Stream::read(void *buffer, std::size_t count) {+  if (!open_ || count == 0)+    return count == 0 ? 0 : -1;+  if (kind_ == Kind::Tls) {+    const int n = SSL_read(static_cast<SSL *>(ssl_), buffer,+                           static_cast<int>(std::min<std::size_t>(+                               count, static_cast<std::size_t>(INT_MAX))));+    if (n > 0)+      return n;+    if (n == 0)+      return 0;+    return -1;+  }+#if defined(_WIN32)+  if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {+    DWORD got = 0;+    if (!ReadFile(reinterpret_cast<HANDLE>(fd_in_), buffer,+                  static_cast<DWORD>(std::min<std::size_t>(+                      count, static_cast<std::size_t>(MAXDWORD))),+                  &got, nullptr))+      return -1;+    return static_cast<std::int64_t>(got);+  }+  const int n = recv(static_cast<SOCKET>(fd_in_),+                     static_cast<char *>(buffer),+                     static_cast<int>(std::min<std::size_t>(+                         count, static_cast<std::size_t>(INT_MAX))),+                     0);+  return n;+#else+  const int fd = kind_ == Kind::Stdio ? 0 : static_cast<int>(fd_in_);+  ssize_t n = 0;+  do {+    n = ::read(fd, buffer, count);+  } while (n < 0 && errno == EINTR);+  return n;+#endif+}++bool Stream::write_all(Bytes data) {+  if (!open_)+    return false;+  std::size_t offset = 0;+  while (offset < data.size()) {+    const std::size_t remaining = data.size() - offset;+    std::int64_t written = -1;+    if (kind_ == Kind::Tls) {+      const int n = SSL_write(+          static_cast<SSL *>(ssl_), data.data() + offset,+          static_cast<int>(std::min<std::size_t>(remaining,+                                                 static_cast<std::size_t>(+                                                     INT_MAX))));+      written = n;+    }+#if defined(_WIN32)+    else if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {+      DWORD count = 0;+      if (!WriteFile(reinterpret_cast<HANDLE>(fd_out_), data.data() + offset,+                     static_cast<DWORD>(std::min<std::size_t>(+                         remaining, static_cast<std::size_t>(MAXDWORD))),+                     &count, nullptr))+        return false;+      written = static_cast<std::int64_t>(count);+    } else {+      const int n = send(+          static_cast<SOCKET>(fd_out_),+          reinterpret_cast<const char *>(data.data() + offset),+          static_cast<int>(std::min<std::size_t>(+              remaining, static_cast<std::size_t>(INT_MAX))),+          0);+      written = n;+    }+#else+    else {+      ssize_t n = 0;+      do {+        n = ::write(kind_ == Kind::Stdio ? 1 : static_cast<int>(fd_out_),+                    data.data() + offset, remaining);+      } while (n < 0 && errno == EINTR);+      written = n;+    }+#endif+    if (written <= 0)+      return false;+    offset += static_cast<std::size_t>(written);+  }+  return true;+}++void Stream::close() {+  if (!open_)+    return;+  open_ = false;+  if (kind_ == Kind::Tls) {+    if (ssl_)+      tls_free(ssl_);+    ssl_ = nullptr;+#if defined(_WIN32)+    closesocket(static_cast<SOCKET>(fd_in_));+#else+    if (static_cast<int>(fd_in_) > 2)+      ::close(static_cast<int>(fd_in_));+#endif+    return;+  }+  if (kind_ == Kind::Proc) {+#if defined(_WIN32)+    if (fd_in_ != 0)+      CloseHandle(reinterpret_cast<HANDLE>(fd_in_));+    if (fd_out_ != 0)+      CloseHandle(reinterpret_cast<HANDLE>(fd_out_));+    if (process_) {+      WaitForSingleObject(reinterpret_cast<HANDLE>(process_), INFINITE);+      CloseHandle(reinterpret_cast<HANDLE>(process_));+      process_ = nullptr;+    }+#else+    if (static_cast<int>(fd_in_) > 2)+      ::close(static_cast<int>(fd_in_));+    if (static_cast<int>(fd_out_) > 2)+      ::close(static_cast<int>(fd_out_));+    if (pid_ > 0) {+      int status = 0;+      while (waitpid(pid_, &status, 0) < 0 && errno == EINTR) {+      }+      pid_ = 0;+    }+#endif+    return;+  }+  if (kind_ == Kind::Fd) {+#if defined(_WIN32)+    closesocket(static_cast<SOCKET>(fd_in_));+#else+    if (static_cast<int>(fd_in_) > 2)+      ::close(static_cast<int>(fd_in_));+#endif+  }+}++// ---------------------------------------------------------------------------+// Process spawning+// ---------------------------------------------------------------------------++#if defined(_WIN32)+std::optional<Stream> spawn_argv(const std::vector<std::string> &argv) {+  if (argv.empty())+    return std::nullopt;+  ensure_winsock();+  SECURITY_ATTRIBUTES attributes{};+  attributes.nLength = sizeof(attributes);+  attributes.bInheritHandle = TRUE;+  HANDLE child_stdin_read = nullptr;+  HANDLE child_stdin_write = nullptr;+  HANDLE child_stdout_read = nullptr;+  HANDLE child_stdout_write = nullptr;+  if (!CreatePipe(&child_stdin_read, &child_stdin_write, &attributes, 0) ||+      !CreatePipe(&child_stdout_read, &child_stdout_write, &attributes, 0)) {+    if (child_stdin_read)+      CloseHandle(child_stdin_read);+    if (child_stdin_write)+      CloseHandle(child_stdin_write);+    return std::nullopt;+  }+  SetHandleInformation(child_stdin_write, HANDLE_FLAG_INHERIT, 0);+  SetHandleInformation(child_stdout_read, HANDLE_FLAG_INHERIT, 0);+  STARTUPINFOW startup{};+  startup.cb = sizeof(startup);+  startup.dwFlags = STARTF_USESTDHANDLES;+  startup.hStdInput = child_stdin_read;+  startup.hStdOutput = child_stdout_write;+  startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);+  PROCESS_INFORMATION process{};+  std::wstring command_line = build_windows_command_line(argv);+  const BOOL started =+      CreateProcessW(nullptr, command_line.data(), nullptr, nullptr, TRUE, 0,+                     nullptr, nullptr, &startup, &process);+  CloseHandle(child_stdin_read);+  CloseHandle(child_stdout_write);+  if (!started) {+    CloseHandle(child_stdin_write);+    CloseHandle(child_stdout_read);+    return std::nullopt;+  }+  CloseHandle(process.hThread);+  Stream stream;+  stream.kind_ = Stream::Kind::Proc;+  stream.fd_in_ = reinterpret_cast<Socket>(child_stdout_read);+  stream.fd_out_ = reinterpret_cast<Socket>(child_stdin_write);+  stream.process_ = process.hProcess;+  stream.process_id_ = process.dwProcessId;+  stream.open_ = true;+  return stream;+}+#else+std::optional<Stream> spawn_argv(const std::vector<std::string> &argv) {+  if (argv.empty())+    return std::nullopt;+  int in_pipe[2];+  int out_pipe[2];+  if (::pipe(in_pipe) != 0)+    return std::nullopt;+  if (::pipe(out_pipe) != 0) {+    ::close(in_pipe[0]);+    ::close(in_pipe[1]);+    return std::nullopt;+  }+  std::vector<char *> raw;+  raw.reserve(argv.size() + 1);+  for (const auto &item : argv)+    raw.push_back(const_cast<char *>(item.c_str()));+  raw.push_back(nullptr);+  const pid_t pid = ::fork();+  if (pid == 0) {+    (void)::dup2(in_pipe[0], 0);+    (void)::dup2(out_pipe[1], 1);+    ::close(in_pipe[0]);+    ::close(in_pipe[1]);+    ::close(out_pipe[0]);+    ::close(out_pipe[1]);+    ::execvp(raw[0], raw.data());+    ::_exit(127);+  }+  ::close(in_pipe[0]);+  ::close(out_pipe[1]);+  if (pid < 0) {+    ::close(in_pipe[1]);+    ::close(out_pipe[0]);+    return std::nullopt;+  }+  Stream stream;+  stream.kind_ = Stream::Kind::Proc;+  stream.fd_in_ = out_pipe[0];+  stream.fd_out_ = in_pipe[1];+  stream.pid_ = pid;+  stream.open_ = true;+  return stream;+}+#endif++// ---------------------------------------------------------------------------+// TCP+// ---------------------------------------------------------------------------++std::optional<Socket> tcp_connect(std::string_view host, int port) {+  if (host.empty())+    return std::nullopt;+#if defined(_WIN32)+  ensure_winsock();+#endif+  addrinfo hints{};+  hints.ai_family = AF_UNSPEC;+  hints.ai_socktype = SOCK_STREAM;+  const std::string service = std::to_string(port);+  const std::string host_text(host);+  addrinfo *results = nullptr;+  if (getaddrinfo(host_text.c_str(), service.c_str(), &hints, &results) != 0)+    return std::nullopt;+  Socket connected = INVALID_SOCKET_VALUE;+  for (addrinfo *it = results; it != nullptr; it = it->ai_next) {+#if defined(_WIN32)+    SOCKET socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);+    if (socket == INVALID_SOCKET)+      continue;+    if (::connect(socket, it->ai_addr, static_cast<int>(it->ai_addrlen)) == 0) {+      connected = static_cast<Socket>(socket);+      break;+    }+    closesocket(socket);+#else+    const int socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);+    if (socket < 0)+      continue;+    if (::connect(socket, it->ai_addr, it->ai_addrlen) == 0) {+      connected = socket;+      break;+    }+    ::close(socket);+#endif+  }+  freeaddrinfo(results);+  return connected == INVALID_SOCKET_VALUE+             ? std::nullopt+             : std::optional<Socket>(connected);+}++Socket tcp_listen(int port, int backlog) {+#if defined(_WIN32)+  ensure_winsock();+  SOCKET listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);+  if (listener == INVALID_SOCKET)+    return INVALID_SOCKET_VALUE;+  BOOL reuse = TRUE;+  setsockopt(listener, SOL_SOCKET, SO_REUSEADDR,+             reinterpret_cast<const char *>(&reuse), sizeof(reuse));+  sockaddr_in address{};+  address.sin_family = AF_INET;+  address.sin_addr.s_addr = htonl(INADDR_ANY);+  address.sin_port = htons(static_cast<u_short>(port));+  if (::bind(listener, reinterpret_cast<sockaddr *>(&address),+             sizeof(address)) == SOCKET_ERROR ||+      ::listen(listener, backlog) == SOCKET_ERROR) {+    closesocket(listener);+    return INVALID_SOCKET_VALUE;+  }+  return static_cast<Socket>(listener);+#else+  const int listener = ::socket(AF_INET, SOCK_STREAM, 0);+  if (listener < 0)+    return INVALID_SOCKET_VALUE;+  int reuse = 1;+  (void)setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));+  sockaddr_in address{};+  address.sin_family = AF_INET;+  address.sin_addr.s_addr = htonl(INADDR_ANY);+  address.sin_port = htons(static_cast<std::uint16_t>(port));+  if (::bind(listener, reinterpret_cast<sockaddr *>(&address),+             sizeof(address)) != 0 ||+      ::listen(listener, backlog) != 0) {+    ::close(listener);+    return INVALID_SOCKET_VALUE;+  }+  return listener;+#endif+}++std::optional<Socket> tcp_accept(Socket listener) {+#if defined(_WIN32)+  const SOCKET accepted = ::accept(static_cast<SOCKET>(listener), nullptr, nullptr);+  if (accepted == INVALID_SOCKET)+    return std::nullopt;+  return static_cast<Socket>(accepted);+#else+  const int accepted = ::accept(static_cast<int>(listener), nullptr, nullptr);+  if (accepted < 0)+    return std::nullopt;+  return accepted;+#endif+}++void close_socket(Socket socket) {+  if (socket == INVALID_SOCKET_VALUE)+    return;+#if defined(_WIN32)+  closesocket(static_cast<SOCKET>(socket));+#else+  if (static_cast<int>(socket) > 2)+    ::close(static_cast<int>(socket));+#endif+}++// ---------------------------------------------------------------------------+// Process/platform helpers+// ---------------------------------------------------------------------------++void ignore_sigpipe() {+#if !defined(_WIN32)+  (void)::signal(SIGPIPE, SIG_IGN);+#endif+}++fs::path self_exe() {+#if defined(_WIN32)+  std::wstring buffer(32768, L'\0');+  const DWORD len =+      GetModuleFileNameW(nullptr, buffer.data(),+                         static_cast<DWORD>(buffer.size()));+  if (len > 0) {+    buffer.resize(len);+    return fs::path(buffer);+  }+  return fs::path("vn.exe");+#elif defined(__APPLE__)+  std::uint32_t size = 0;+  _NSGetExecutablePath(nullptr, &size);+  std::string buffer(size, '\0');+  if (_NSGetExecutablePath(buffer.data(), &size) == 0) {+    char resolved[PATH_MAX];+    if (::realpath(buffer.c_str(), resolved))+      return fs::path(resolved);+    buffer.resize(std::strlen(buffer.c_str()));+    return fs::path(buffer);+  }+  return fs::path("vn");+#else+  std::string buffer(4096, '\0');+  const ssize_t len = ::readlink("/proc/self/exe", buffer.data(),+                                 buffer.size() - 1);+  if (len > 0) {+    buffer.resize(static_cast<std::size_t>(len));+    return fs::path(buffer);+  }+  return fs::path("vn");+#endif+}++std::string quote_shell(std::string_view word) {+  std::string out;+  out.reserve(word.size() + 2);+  out.push_back('\'');+  for (char c : word) {+    if (c == '\'')+      out += "'\\''";+    else+      out.push_back(c);+  }+  out.push_back('\'');+  return out;+}++std::string build_shell_command(const std::vector<std::string> &parts) {+  std::string out;+  for (const auto &part : parts) {+    if (!out.empty())+      out.push_back(' ');+    out += quote_shell(part);+  }+  return out;+}++// ---------------------------------------------------------------------------+// TLS+// ---------------------------------------------------------------------------++void *tls_server_ctx(std::string_view cert_path, std::string_view key_path) {+  SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());+  if (!ctx)+    return nullptr;+  if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1)+    goto fail;+  if (SSL_CTX_use_certificate_chain_file(ctx,+                                         std::string(cert_path).c_str()) != 1)+    goto fail;+  if (SSL_CTX_use_PrivateKey_file(ctx, std::string(key_path).c_str(),+                                  SSL_FILETYPE_PEM) != 1)+    goto fail;+  if (SSL_CTX_check_private_key(ctx) != 1)+    goto fail;+  return ctx;+fail:+  SSL_CTX_free(ctx);+  return nullptr;+}++void *tls_client_ctx(bool pinned) {+  SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());+  if (!ctx)+    return nullptr;+  if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {+    SSL_CTX_free(ctx);+    return nullptr;+  }+  if (pinned) {+    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);+    return ctx;+  }+  SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr);+  if (SSL_CTX_set_default_verify_paths(ctx) != 1) {+    SSL_CTX_free(ctx);+    return nullptr;+  }+  return ctx;+}++void *tls_accept(void *ctx, Socket fd) {+  SSL *ssl = SSL_new(static_cast<SSL_CTX *>(ctx));+  if (!ssl)+    return nullptr;+  if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1 ||+      SSL_accept(ssl) != 1) {+    SSL_free(ssl);+    return nullptr;+  }+  return ssl;+}++void *tls_connect(void *ctx, Socket fd, std::string_view host) {+  SSL *ssl = SSL_new(static_cast<SSL_CTX *>(ctx));+  if (!ssl)+    return nullptr;+  if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1) {+    SSL_free(ssl);+    return nullptr;+  }+  if (!host.empty()) {+    const std::string text(host);+    SSL_set_tlsext_host_name(ssl, text.c_str());+    X509_VERIFY_PARAM *param = SSL_get0_param(ssl);+    X509_VERIFY_PARAM_set1_host(param, text.c_str(), 0);+  }+  if (SSL_connect(ssl) != 1) {+    SSL_free(ssl);+    return nullptr;+  }+  return ssl;+}++bool tls_exporter(void *ssl, std::uint8_t *out, std::size_t len) {+  static constexpr char label[] = "EXPORTER-veins-auth/1";+  return SSL_export_keying_material(static_cast<SSL *>(ssl), out, len, label,+                                    sizeof(label) - 1, nullptr, 0, 0) == 1;+}++bool tls_peer_sha256(void *ssl, std::uint8_t *out) {+  X509 *cert = SSL_get1_peer_certificate(static_cast<SSL *>(ssl));+  if (!cert)+    return false;+  unsigned int len = 0;+  const bool ok =+      X509_digest(cert, EVP_sha256(), out, &len) == 1 && len == 32;+  X509_free(cert);+  return ok;+}++void tls_free(void *ssl) {+  if (!ssl)+    return;+  SSL_shutdown(static_cast<SSL *>(ssl));+  SSL_free(static_cast<SSL *>(ssl));+}++void tls_ctx_free(void *ctx) {+  if (ctx)+    SSL_CTX_free(static_cast<SSL_CTX *>(ctx));+}++std::string tls_error() { return ssl_error_string(); }++std::string to_hex(Bytes data) {+  static constexpr char digits[] = "0123456789abcdef";+  std::string out;+  out.reserve(data.size() * 2);+  for (std::uint8_t byte : data) {+    out.push_back(digits[byte >> 4]);+    out.push_back(digits[byte & 15]);+  }+  return out;+}++bool hex_equal(std::string_view a, std::string_view b) {+  auto skip = [](std::string_view text, std::size_t &index) {+    while (index < text.size() && text[index] == ':')+      ++index;+  };+  std::size_t ai = 0;+  std::size_t bi = 0;+  for (;;) {+    skip(a, ai);+    skip(b, bi);+    if (ai >= a.size() || bi >= b.size())+      return ai >= a.size() && bi >= b.size();+    auto lower = [](char c) {+      return static_cast<char>((c >= 'A' && c <= 'Z') ? c + 32 : c);+    };+    if (lower(a[ai]) != lower(b[bi]))+      return false;+    ++ai;+    ++bi;+  }+}++} // namespace vn::net--- /dev/null+++ b/veins-cpprewrite/src/net.h@@ -0,0 +1,102 @@+#pragma once++#include "common.h"++#include <cstdint>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++namespace vn::net {++#if defined(_WIN32)+using Socket = std::uintptr_t;+constexpr Socket INVALID_SOCKET_VALUE = static_cast<Socket>(~0ull);+#else+using Socket = int;+constexpr Socket INVALID_SOCKET_VALUE = -1;+#endif++// A reliable, ordered byte stream over stdio, a file descriptor/socket, TLS,+// or a child process.+class Stream {+public:+  enum class Kind : std::uint8_t { Stdio, Fd, Tls, Proc };++  Stream() = default;+  ~Stream();++  Stream(Stream &&other) noexcept;+  Stream &operator=(Stream &&other) noexcept;+  Stream(const Stream &) = delete;+  Stream &operator=(const Stream &) = delete;++  static Stream stdio_stream();+  static Stream fd_stream(Socket fd);+  static Stream tls_stream(Socket fd, void *ssl);+  static std::optional<Stream> spawn_argv(const std::vector<std::string> &argv);++  friend std::optional<Stream>+  spawn_argv(const std::vector<std::string> &argv);++  [[nodiscard]] Kind kind() const { return kind_; }+  [[nodiscard]] void *ssl() const { return ssl_; }+  [[nodiscard]] Socket fd() const { return fd_in_; }+  [[nodiscard]] bool valid() const { return open_; }++  // Returns the number of bytes read, 0 at clean end of stream, -1 on error.+  std::int64_t read(void *buffer, std::size_t count);+  bool write_all(Bytes data);+  bool write_all(std::string_view text) {+    return write_all(Bytes(reinterpret_cast<const std::uint8_t *>(text.data()),+                           text.size()));+  }+  void close();++private:+  Kind kind_ = Kind::Stdio;+  Socket fd_in_ = 0;+  Socket fd_out_ = 0;+  void *ssl_ = nullptr;+#if defined(_WIN32)+  void *process_ = nullptr;+  std::uint32_t process_id_ = 0;+#else+  int pid_ = 0;+#endif+  bool open_ = false;+};++// Run argv[0] with the given arguments. stdin/stdout are connected to the+// stream; stderr is inherited.+std::optional<Stream> spawn_argv(const std::vector<std::string> &argv);++std::optional<Socket> tcp_connect(std::string_view host, int port);+Socket tcp_listen(int port, int backlog = 64);+std::optional<Socket> tcp_accept(Socket listener);+void close_socket(Socket socket);++void ignore_sigpipe();+fs::path self_exe();+std::string quote_shell(std::string_view word);+std::string build_shell_command(const std::vector<std::string> &parts);++// ---------------------------------------------------------------------------+// TLS 1.3+// ---------------------------------------------------------------------------++void *tls_server_ctx(std::string_view cert_path, std::string_view key_path);+void *tls_client_ctx(bool pinned);+void *tls_accept(void *ctx, Socket fd);+void *tls_connect(void *ctx, Socket fd, std::string_view host);+bool tls_exporter(void *ssl, std::uint8_t *out, std::size_t len);+bool tls_peer_sha256(void *ssl, std::uint8_t *out);+void tls_free(void *ssl);+void tls_ctx_free(void *ctx);+std::string tls_error();++std::string to_hex(Bytes data);+bool hex_equal(std::string_view a, std::string_view b);++} // namespace vn::net--- /dev/null+++ b/veins-cpprewrite/src/net_commands.cpp@@ -0,0 +1,1296 @@+#include "net_commands.h"++#include "auth.h"+#include "crypto.h"+#include "promisor.h"+#include "protocol.h"+#include "server.h"+#include "store.h"+#include "worktree.h"++#include <algorithm>+#include <cstddef>+#include <cstring>+#include <iostream>+#include <optional>+#include <set>+#include <string>+#include <vector>++namespace vn {++namespace {++bool starts_with(std::string_view text, std::string_view prefix) {+  return text.size() >= prefix.size() && text.substr(0, prefix.size()) == prefix;+}++bool is_flag(std::string_view arg) { return !arg.empty() && arg.front() == '-'; }++std::string arg_at(const std::vector<std::string> &args, std::size_t index) {+  return index < args.size() ? args[index] : std::string();+}++std::string trim_text(std::string_view text) {+  std::size_t start = 0;+  std::size_t end = text.size();+  auto blank = [](char c) {+    return c == ' ' || c == '\t' || c == '\r' || c == '\n';+  };+  while (start < end && blank(text[start]))+    ++start;+  while (end > start && blank(text[end - 1]))+    --end;+  return std::string(text.substr(start, end - start));+}++std::string remote_key(std::string_view remote, std::string_view field) {+  std::string out = "remote.";+  out += remote;+  out.push_back('.');+  out += field;+  return out;+}++std::string last_segment(std::string_view path) {+  while (path.size() > 1 && path.back() == '/')+    path.remove_suffix(1);+  const auto slash = path.rfind('/');+  if (slash != std::string_view::npos && slash + 1 < path.size())+    return std::string(path.substr(slash + 1));+  if (!path.empty() && path != "/")+    return std::string(path);+  return "repo";+}++bool same_id(const Id &a, const Id &b) {+  return std::memcmp(a.data(), b.data(), ID_LEN) == 0;+}++void report_client_error(const proto::Client &client,+                         std::string_view context) {+  error_prefix();+  if (!client.error().empty())+    std::cout << context << ": " << client.error() << "\n";+  else+    std::cout << context << "\n";+}++std::optional<Id> default_target(const std::vector<proto::RefInfo> &refs) {+  for (const auto &ref : refs) {+    if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))+      return ref.target;+  }+  for (const auto &ref : refs) {+    if (ref.kind == 0)+      return ref.target;+  }+  return std::nullopt;+}++std::vector<Id> selected_commits(const std::vector<proto::RefInfo> &refs,+                                 std::string_view policy) {+  std::vector<Id> out;+  if (policy == "none")+    return out;+  if (policy == "head") {+    if (auto target = default_target(refs))+      out.push_back(*target);+    return out;+  }+  for (const auto &ref : refs)+    out.push_back(ref.target);+  return out;+}++bool set_bookmark(View &view, std::string_view name, const Id &target) {+  if (auto index = find_bookmark(view, name)) {+    view.bookmarks[*index].targets.adds = {target};+    view.bookmarks[*index].targets.removes.clear();+    return true;+  }+  Bookmark bookmark;+  bookmark.name = std::string(name);+  bookmark.targets.adds = {target};+  view.bookmarks.push_back(std::move(bookmark));+  return true;+}++bool set_tag(View &view, std::string_view name, const Id &target) {+  if (auto index = find_tag(view, name)) {+    view.tags[*index].target = target;+    return true;+  }+  view.tags.push_back(TagRef{std::string(name), target});+  return true;+}++bool set_remote_ref(View &view, std::string_view remote, std::string_view name,+                    const Id &target) {+  for (auto &ref : view.remote_refs) {+    if (ref.remote == remote && ref.name == name) {+      ref.target = target;+      return true;+    }+  }+  view.remote_refs.push_back(+      RemoteRef{std::string(remote), std::string(name), target});+  return true;+}++bool apply_refs(const fs::path &root, const std::vector<proto::RefInfo> &refs,+                std::string_view remote, bool clone) {+  Store store = Store::open_all(root);+  auto tx = Txn::begin(root, store);+  if (!tx)+    return false;+  for (const auto &ref : refs) {+    if (ref.kind == 1) {+      set_tag(tx->view(), ref.name, ref.target);+    } else if (clone) {+      set_bookmark(tx->view(), ref.name, ref.target);+    } else {+      set_remote_ref(tx->view(), remote, ref.name, ref.target);+      if (!find_bookmark(tx->view(), ref.name))+        set_bookmark(tx->view(), ref.name, ref.target);+    }+  }+  rebuild_heads(tx->view());+  if (clone) {+    if (auto target = default_target(refs))+      set_workspace(tx->view(), *target);+  }+  return tx->finish("clone").has_value();+}++struct Walker {+  Walker(Store &store, bool want_objects)+      : store(store), want_objects(want_objects) {}++  Store &store;+  bool want_objects = false;+  std::set<Id> blobs;+  std::set<Id> conflicts;+  std::set<Id> chunks;+  std::set<Id> objects;+  std::vector<Id> chunk_out;+  std::vector<Id> object_out;++  void add_object(const Id &id) {+    if (want_objects && objects.insert(id).second)+      object_out.push_back(id);+  }++  void walk_blob(const Id &id) {+    if (!blobs.insert(id).second)+      return;+    add_object(id);+    auto body = store.read_body(id, TYPE_BLOB);+    if (!body)+      return;+    auto blob = decode_blob(bytes_of(*body));+    if (!blob)+      return;+    if (blob->form == BlobForm::Leaf) {+      for (const auto &entry : blob->entries) {+        if (chunks.insert(entry.id).second)+          chunk_out.push_back(entry.id);+        add_object(entry.id);+      }+    } else if (blob->form == BlobForm::Interior) {+      for (const auto &entry : blob->entries)+        walk_blob(entry.id);+    }+  }++  void walk_conflict(const Id &id) {+    if (!conflicts.insert(id).second)+      return;+    add_object(id);+    auto body = store.read_body(id, TYPE_CONFLICT);+    if (!body)+      return;+    auto conflict = decode_conflict(bytes_of(*body));+    if (!conflict)+      return;+    for (const auto &value : conflict->adds) {+      if (value.target)+        walk_value(value.kind, *value.target);+    }+    for (const auto &value : conflict->removes) {+      if (value.target)+        walk_value(value.kind, *value.target);+    }+  }++  void walk_value(std::uint8_t kind, const Id &id) {+    if (kind == KIND_SUBTREE)+      walk_tree(id);+    else if (kind == KIND_CONFLICT)+      walk_conflict(id);+    else+      walk_blob(id);+  }++  void walk_tree(const Id &id) {+    add_object(id);+    auto body = store.read_body(id, TYPE_TREE);+    if (!body)+      return;+    auto tree = decode_tree(bytes_of(*body));+    if (!tree)+      return;+    for (const auto &entry : tree->entries) {+      if (entry.kind == KIND_SUBTREE)+        walk_tree(entry.target);+      else if (entry.kind == KIND_CONFLICT)+        walk_conflict(entry.target);+      else if (entry.kind != KIND_SUBMODULE)+        walk_blob(entry.target);+    }+  }+};++std::vector<Id> chunks_for_commits(Store &store,+                                   const std::vector<Id> &commits) {+  Walker walker{store, false};+  for (const auto &id : commits) {+    auto loaded = load_commit(store, id);+    if (loaded)+      walker.walk_tree(loaded->commit.root_tree);+  }+  return std::move(walker.chunk_out);+}++std::vector<Id> objects_for_commits(Store &store,+                                    const std::vector<Id> &commits) {+  Walker walker{store, true};+  for (const auto &id : commits) {+    walker.add_object(id);+    auto loaded = load_commit(store, id);+    if (loaded)+      walker.walk_tree(loaded->commit.root_tree);+  }+  return std::move(walker.object_out);+}++bool send_chunks(proto::Client &client, const fs::path &root,+                 const std::vector<Id> &chunks) {+  constexpr std::size_t BATCH = 4096;+  for (std::size_t offset = 0; offset < chunks.size(); offset += BATCH) {+    const std::size_t end = std::min(offset + BATCH, chunks.size());+    std::vector<Id> batch(chunks.begin() + static_cast<std::ptrdiff_t>(offset),+                          chunks.begin() + static_cast<std::ptrdiff_t>(end));+    if (!client.get_chunks(root, batch))+      return false;+  }+  return true;+}++bool send_missing_chunks(proto::Client &client, const fs::path &root,+                         const std::vector<Id> &chunks) {+  Store store = Store::open_all(root);+  std::vector<Id> missing;+  for (const auto &id : chunks) {+    if (!store.find(id))+      missing.push_back(id);+  }+  return send_chunks(client, root, missing);+}++std::optional<std::string> config_value(const fs::path &root,+                                        std::string_view key) {+  return repo_config_value(root, key);+}++std::vector<std::string> list_remote_names(const fs::path &root) {+  std::vector<std::string> out;+  auto data = read_file_opt(config_path(root));+  if (!data)+    return out;+  const std::string_view text(reinterpret_cast<const char *>(data->data()),+                              data->size());+  std::size_t start = 0;+  for (std::size_t i = 0; i <= text.size(); ++i) {+    if (i != text.size() && text[i] != '\n')+      continue;+    const std::string_view line = text.substr(start, i - start);+    if (starts_with(line, "remote.")) {+      const auto dot = line.find(".url", 7);+      if (dot != std::string_view::npos && dot > 7)+        out.emplace_back(line.substr(7, dot - 7));+    }+    start = i + 1;+  }+  return out;+}++std::string role_text(std::uint8_t role) {+  if (role == 2)+    return "write";+  if (role == 1)+    return "read";+  return "anonymous";+}++void print_key(const auth::Key &key) {+  std::cout << "name: " << key.name << "\n";+  std::cout << "public key: " << format_public_key(key.public_key) << "\n";+  std::cout << "fingerprint: " << key.fingerprint << "\n";+}++void auth_usage() {+  std::cout << "usage: vn auth <use|list|remove> ...\n";+  std::cout << "  vn auth use <key> [<host|url>]   set the default or host key\n";+  std::cout << "  vn auth list                     show stored key mappings\n";+  std::cout << "  vn auth remove [<host|url>]      remove a mapping (default if "+               "omitted)\n";+}++std::optional<PublicKey> read_public_key(std::string_view arg) {+  if (starts_with(arg, "ed25519:"))+    return parse_public_key(arg);+  auto data = read_file_opt(path_from_bytes(arg));+  if (!data)+    return std::nullopt;+  const std::string text = trim_text(+      std::string_view(reinterpret_cast<const char *>(data->data()),+                       data->size()));+  return parse_public_key(text);+}++} // namespace++// ---------------------------------------------------------------------------+// remote+// ---------------------------------------------------------------------------++int remote_run(const std::vector<std::string> &args) {+  const std::string sub = arg_at(args, 2);+  if (sub.empty()) {+    error_prefix();+    std::cout << "expected a remote subcommand (add, set-url, list, remove)\n";+    return 1;+  }+  auto repo = discover_repo(".");+  if (!repo) {+    error_prefix();+    std::cout << "not a veins repository\n";+    return 1;+  }+  const fs::path root = *repo;++  if (sub == "add" || sub == "set-url") {+    const bool replace = sub == "set-url";+    std::string name;+    std::string url;+    std::optional<std::string> key;+    std::optional<std::string> pin;+    for (std::size_t i = 3; i < args.size(); ++i) {+      const std::string &arg = args[i];+      if (starts_with(arg, "-key:")) {+        key = arg.substr(5);+      } else if (starts_with(arg, "-tls-pin:")) {+        pin = arg.substr(9);+      } else if (is_flag(arg)) {+        error_prefix();+        std::cout << "unknown flag: " << arg << "\n";+        return 1;+      } else if (name.empty()) {+        name = arg;+      } else if (url.empty()) {+        url = arg;+      } else {+        error_prefix();+        std::cout << "too many arguments\n";+        return 1;+      }+    }+    if (name.empty() || url.empty()) {+      error_prefix();+      std::cout << (replace ? "remote set-url requires a name and URL\n"+                            : "remote add requires a name and URL\n");+      return 1;+    }+    const std::string url_key = remote_key(name, "url");+    const auto existing = config_value(root, url_key);+    if (existing && !replace) {+      error_prefix();+      std::cout << "remote already exists: " << name << "\n";+      return 1;+    }+    if (!existing && replace) {+      error_prefix();+      std::cout << "unknown remote: " << name << "\n";+      return 1;+    }+    if (!repo_config_set(root, url_key, url)) {+      error_prefix();+      std::cout << "cannot write repository config\n";+      return 1;+    }+    if (key) {+      const std::string field = remote_key(name, "key");+      const bool ok = key->empty() ? repo_config_remove(root, field)+                                   : repo_config_set(root, field, *key);+      if (!ok) {+        error_prefix();+        std::cout << "cannot write repository config\n";+        return 1;+      }+    }+    if (pin) {+      const std::string field = remote_key(name, "tls-pin");+      const bool ok = pin->empty() ? repo_config_remove(root, field)+                                   : repo_config_set(root, field, *pin);+      if (!ok) {+        error_prefix();+        std::cout << "cannot write repository config\n";+        return 1;+      }+    }+    return 0;+  }++  if (sub == "list" || sub == "ls") {+    for (const auto &name : list_remote_names(root)) {+      const auto url = config_value(root, remote_key(name, "url"));+      std::cout << name << "\t" << (url ? *url : std::string()) << "\n";+    }+    return 0;+  }++  if (sub == "remove" || sub == "rm") {+    const std::string name = arg_at(args, 3);+    if (name.empty()) {+      error_prefix();+      std::cout << "remote remove requires a name\n";+      return 1;+    }+    if (!config_value(root, remote_key(name, "url"))) {+      error_prefix();+      std::cout << "unknown remote: " << name << "\n";+      return 1;+    }+    (void)repo_config_remove(root, remote_key(name, "url"));+    (void)repo_config_remove(root, remote_key(name, "key"));+    (void)repo_config_remove(root, remote_key(name, "tls-pin"));+    return 0;+  }++  error_prefix();+  std::cout << "unknown remote subcommand: " << sub << "\n";+  return 1;+}++// ---------------------------------------------------------------------------+// clone+// ---------------------------------------------------------------------------++int clone_run(const std::vector<std::string> &args) {+  std::string url;+  std::string path;+  std::string policy = "head";+  std::string key_name;+  bool key_explicit = false;+  std::string tls_pin;+  for (std::size_t i = 2; i < args.size(); ++i) {+    const std::string &arg = args[i];+    if (starts_with(arg, "-blobs:")) {+      policy = arg.substr(7);+    } else if (starts_with(arg, "-key:")) {+      key_name = arg.substr(5);+      if (starts_with(key_name, "ed25519:")) {+        error_prefix();+        std::cout << "-key: expects a local key name, not a public key\n";+        return 1;+      }+      key_explicit = true;+    } else if (starts_with(arg, "-pin:")) {+      tls_pin = arg.substr(5);+    } else if (is_flag(arg)) {+      error_prefix();+      std::cout << "unknown flag: " << arg << "\n";+      return 1;+    } else if (url.empty()) {+      url = arg;+    } else {+      path = arg;+    }+  }+  if (url.empty()) {+    error_prefix();+    std::cout << "clone requires a URL\n";+    return 1;+  }+  const auto parsed = proto::parse_url(url);+  if (!parsed) {+    error_prefix();+    std::cout << "unsupported URL\n";+    return 1;+  }+  if (path.empty())+    path = last_segment(parsed->path);+  auto repo = init_repo(path_from_bytes(path));+  if (!repo) {+    error_prefix();+    std::cout << "cannot create repository\n";+    return 1;+  }+  const fs::path root = *repo;++  if (key_name.empty()) {+    if (auto fallback = auth::key_for_url(url))+      key_name = *fallback;+  }+  (void)repo_config_set(root, remote_key("origin", "url"), url);+  if (key_explicit && !key_name.empty())+    (void)repo_config_set(root, remote_key("origin", "key"), key_name);+  if (!tls_pin.empty())+    (void)repo_config_set(root, remote_key("origin", "tls-pin"), tls_pin);++  const std::string repo_name = proto::url_repo_name(url);+  auto client = proto::Client::connect(url, key_name, repo_name, tls_pin);+  if (!client) {+    error_prefix();+    std::cout << "cannot connect or authenticate\n";+    return 1;+  }+  std::vector<proto::RefInfo> refs;+  if (!client->list_refs(refs)) {+    report_client_error(*client, "cannot list remote refs");+    return 1;+  }+  std::vector<Id> wants;+  for (const auto &ref : refs)+    wants.push_back(ref.target);+  if (wants.empty()) {+    info_prefix();+    std::cout << "cloned empty repository into " << path << "\n";+    return 0;+  }+  if (!client->negotiate(wants, {})) {+    report_client_error(*client, "negotiation failed");+    return 1;+  }+  if (!client->fetch_skeleton(root, wants)) {+    report_client_error(*client, "fetch failed");+    return 1;+  }+  {+    Store store = Store::open_all(root);+    const auto commits = selected_commits(refs, policy);+    const auto chunks = chunks_for_commits(store, commits);+    if (!send_chunks(*client, root, chunks)) {+      report_client_error(*client, "chunk fetch failed");+      return 1;+    }+  }+  if (!apply_refs(root, refs, "origin", true)) {+    error_prefix();+    std::cout << "cannot write repository state\n";+    return 1;+  }+  (void)repo_config_set(root, "promisor", "origin");+  install_promisor_fetcher();+  if (policy == "none") {+    info_prefix();+    std::cout << "cloned metadata only; blobs are promised\n";+  }++  int checkout_status = 1;+  {+    Store store = Store::open_all(root);+    auto view = current_view(root, store);+    if (view) {+      if (auto wc = working_copy_id(*view)) {+        auto body = store.read_body(*wc, TYPE_COMMIT);+        if (body) {+          auto commit = decode_commit(bytes_of(*body));+          if (commit) {+            checkout_status = checkout_materialize_commit(+                root, store, std::nullopt, commit->root_tree);+          }+        }+      }+    }+  }+  if (checkout_status != 0) {+    info_prefix();+    std::cout << "cloned; checkout reported " << checkout_status << "\n";+  }+  info_prefix();+  std::cout << "cloned into " << path << "\n";+  return 0;+}++// ---------------------------------------------------------------------------+// fetch+// ---------------------------------------------------------------------------++int fetch_run(const std::vector<std::string> &args) {+  std::string remote_name = "origin";+  std::string path = ".";+  std::string explicit_key;+  std::string explicit_pin;+  bool have_remote = false;+  for (std::size_t i = 2; i < args.size(); ++i) {+    const std::string &arg = args[i];+    if (starts_with(arg, "-key:")) {+      explicit_key = arg.substr(5);+      if (starts_with(explicit_key, "ed25519:")) {+        error_prefix();+        std::cout << "-key: expects a local key name, not a public key\n";+        return 1;+      }+    } else if (starts_with(arg, "-pin:")) {+      explicit_pin = arg.substr(5);+    } else if (is_flag(arg)) {+      error_prefix();+      std::cout << "unknown flag: " << arg << "\n";+      return 1;+    } else if (!have_remote) {+      remote_name = arg;+      have_remote = true;+    } else {+      path = arg;+    }+  }+  auto repo = discover_repo(path_from_bytes(path));+  if (!repo) {+    error_prefix();+    std::cout << "not a veins repository\n";+    return 1;+  }+  const fs::path root = *repo;+  auto url = config_value(root, remote_key(remote_name, "url"));+  if (!url) {+    error_prefix();+    std::cout << "unknown remote\n";+    return 1;+  }+  std::string key;+  if (!explicit_key.empty()) {+    key = explicit_key;+  } else {+    auto configured = config_value(root, remote_key(remote_name, "key"));+    if (configured && auth::local_key_exists(*configured))+      key = *configured;+    if (key.empty()) {+      if (auto fallback = auth::key_for_url(*url))+        key = *fallback;+    }+  }+  std::string pin;+  if (!explicit_pin.empty()) {+    pin = explicit_pin;+  } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {+    pin = *configured;+  }+  const std::string repo_name = proto::url_repo_name(*url);+  auto client = proto::Client::connect(*url, key, repo_name, pin);+  if (!client) {+    error_prefix();+    std::cout << "cannot connect or authenticate\n";+    return 1;+  }+  std::vector<proto::RefInfo> refs;+  if (!client->list_refs(refs)) {+    report_client_error(*client, "cannot list remote refs");+    return 1;+  }+  std::vector<Id> haves = read_heads(root);+  std::vector<Id> wants;+  for (const auto &ref : refs)+    wants.push_back(ref.target);+  if (wants.empty()) {+    info_prefix();+    std::cout << "no refs to fetch\n";+    return 0;+  }+  if (!client->negotiate(wants, haves)) {+    report_client_error(*client, "negotiation failed");+    return 1;+  }+  if (!client->fetch_skeleton(root, wants)) {+    report_client_error(*client, "fetch failed");+    return 1;+  }+  {+    Store store = Store::open_all(root);+    const auto chunks = chunks_for_commits(store, wants);+    if (!send_missing_chunks(*client, root, chunks)) {+      report_client_error(*client, "chunk fetch failed");+      return 1;+    }+  }+  if (!apply_refs(root, refs, remote_name, false)) {+    error_prefix();+    std::cout << "cannot write repository state\n";+    return 1;+  }+  info_prefix();+  std::cout << "fetched from " << remote_name << "\n";+  return 0;+}++// ---------------------------------------------------------------------------+// push+// ---------------------------------------------------------------------------++int push_run(const std::vector<std::string> &args) {+  std::string remote_name = "origin";+  std::string bookmark;+  std::string explicit_key;+  std::string explicit_pin;+  std::string path = ".";+  bool have_remote = false;+  for (std::size_t i = 2; i < args.size(); ++i) {+    const std::string &arg = args[i];+    if (starts_with(arg, "-key:")) {+      explicit_key = arg.substr(5);+      if (starts_with(explicit_key, "ed25519:")) {+        error_prefix();+        std::cout << "-key: expects a local key name, not a public key\n";+        return 1;+      }+    } else if (starts_with(arg, "-pin:")) {+      explicit_pin = arg.substr(5);+    } else if (is_flag(arg)) {+      error_prefix();+      std::cout << "unknown flag: " << arg << "\n";+      return 1;+    } else if (!have_remote) {+      remote_name = arg;+      have_remote = true;+    } else if (bookmark.empty()) {+      bookmark = arg;+    } else {+      path = arg;+    }+  }+  if (bookmark.empty()) {+    error_prefix();+    std::cout << "push requires a bookmark name\n";+    return 1;+  }+  auto repo = discover_repo(path_from_bytes(path));+  if (!repo) {+    error_prefix();+    std::cout << "not a veins repository\n";+    return 1;+  }+  const fs::path root = *repo;+  auto url = config_value(root, remote_key(remote_name, "url"));+  if (!url) {+    error_prefix();+    std::cout << "unknown remote\n";+    return 1;+  }+  std::string key;+  if (!explicit_key.empty()) {+    key = explicit_key;+  } else {+    auto configured = config_value(root, remote_key(remote_name, "key"));+    if (configured && auth::local_key_exists(*configured))+      key = *configured;+    if (key.empty()) {+      if (auto fallback = auth::key_for_url(*url))+        key = *fallback;+    }+  }+  std::string pin;+  if (!explicit_pin.empty()) {+    pin = explicit_pin;+  } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {+    pin = *configured;+  }++  std::optional<Id> target;+  std::vector<Id> commits;+  std::vector<Id> objects;+  {+    Store store = Store::open_all(root);+    auto view = current_view(root, store);+    View empty;+    const View &current = view ? *view : empty;+    target = resolve_revision(store, current, bookmark);+    if (!target) {+      error_prefix();+      std::cout << "unknown bookmark: " << bookmark << "\n";+      return 1;+    }+    const std::array<Id, 1> roots{*target};+    commits = collect_commits(store, roots);+    objects = objects_for_commits(store, commits);+  }+  const std::string repo_name = proto::url_repo_name(*url);+  auto client = proto::Client::connect(*url, key, repo_name, pin);+  if (!client) {+    error_prefix();+    std::cout << "cannot connect or authenticate\n";+    return 1;+  }+  std::vector<proto::RefInfo> refs;+  if (!client->list_refs(refs)) {+    report_client_error(*client, "cannot list remote refs");+    return 1;+  }+  std::optional<Id> old;+  for (const auto &ref : refs) {+    if (ref.name == bookmark)+      old = ref.target;+  }+  if (old && same_id(*old, *target)) {+    info_prefix();+    std::cout << "nothing to push, everything is up to date\n";+    return 0;+  }+  if (!client->push_objects(root, objects)) {+    report_client_error(*client, "push failed");+    return 1;+  }+  std::vector<proto::UpdateRef> updates;+  updates.push_back(proto::UpdateRef{bookmark, old, target});+  if (!client->update_refs(updates)) {+    report_client_error(*client, "ref update rejected");+    return 1;+  }+  info_prefix();+  std::cout << "pushed " << bookmark << " to " << remote_name << "\n";+  return 0;+}++// ---------------------------------------------------------------------------+// serve+// ---------------------------------------------------------------------------++int serve_run(const std::vector<std::string> &args) {+  bool stdio_mode = false;+  std::string listen;+  std::string root = ".";+  std::string cert;+  std::string key;+  std::string repo_path = ".";+  for (std::size_t i = 2; i < args.size(); ++i) {+    const std::string &arg = args[i];+    if (arg == "-stdio") {+      stdio_mode = true;+      if (i + 1 < args.size())+        repo_path = args[++i];+    } else if (arg == "-listen") {+      if (i + 1 < args.size())+        listen = args[++i];+    } else if (arg == "-root") {+      if (i + 1 < args.size())+        root = args[++i];+    } else if (arg == "-tls-cert") {+      if (i + 1 < args.size())+        cert = args[++i];+    } else if (arg == "-tls-key") {+      if (i + 1 < args.size())+        key = args[++i];+    } else {+      error_prefix();+      std::cout << "unknown serve option: " << arg << "\n";+      return 1;+    }+  }+  if (stdio_mode) {+    auto repo = discover_repo(path_from_bytes(repo_path));+    if (!repo) {+      error_prefix();+      std::cout << "not a veins repository\n";+      return 1;+    }+    return server::serve_stdio(*repo);+  }+  if (listen.empty()) {+    error_prefix();+    std::cout << "serve requires -stdio or -listen\n";+    return 1;+  }+  if (cert.empty() || key.empty()) {+    error_prefix();+    std::cout << "TLS requires -tls-cert and -tls-key\n";+    return 1;+  }+  return server::serve_listen(listen, path_from_bytes(root), cert, key);+}++// ---------------------------------------------------------------------------+// key+// ---------------------------------------------------------------------------++int key_run(const std::vector<std::string> &args) {+  const std::string sub = arg_at(args, 2);+  if (sub.empty()) {+    error_prefix();+    std::cout+        << "expected key subcommand (generate, list, show, import)\n";+    return 1;+  }+  if (sub == "generate") {+    const std::string name = arg_at(args, 3);+    if (name.empty()) {+      error_prefix();+      std::cout << "key generate requires a name\n";+      return 1;+    }+    auto key = auth::generate_key(name);+    if (!key) {+      error_prefix();+      std::cout << "cannot create key\n";+      return 1;+    }+    print_key(*key);+    return 0;+  }+  if (sub == "list") {+    for (const auto &name : auth::list_key_names()) {+      if (auto key = auth::load_key(name))+        print_key(*key);+    }+    return 0;+  }+  if (sub == "show") {+    const std::string name = arg_at(args, 3);+    if (name.empty()) {+      error_prefix();+      std::cout << "key show requires a name\n";+      return 1;+    }+    auto key = auth::load_key(name);+    if (!key) {+      error_prefix();+      std::cout << "key not found or has unsafe permissions\n";+      return 1;+    }+    print_key(*key);+    return 0;+  }+  if (sub == "import") {+    error_prefix();+    std::cout << "OpenSSH key import is not supported\n";+    return 1;+  }+  error_prefix();+  std::cout << "unknown key subcommand: " << sub << "\n";+  return 1;+}++// ---------------------------------------------------------------------------+// auth+// ---------------------------------------------------------------------------++int auth_run(const std::vector<std::string> &args) {+  const std::string sub = arg_at(args, 2);+  if (sub.empty()) {+    auth_usage();+    return 1;+  }+  if (sub == "use") {+    const std::string name = arg_at(args, 3);+    if (name.empty()) {+      auth_usage();+      return 1;+    }+    if (!auth::load_key(name)) {+      error_prefix();+      std::cout << "key not found or has unsafe permissions: " << name+                << "\n";+      return 1;+    }+    const std::string target = auth::normalize_target(arg_at(args, 4));+    if (!auth::set_key(target, name)) {+      error_prefix();+      std::cout << "cannot write auth configuration\n";+      return 1;+    }+    if (target == "default")+      std::cout << "default key set to " << name << "\n";+    else+      std::cout << "key for " << target << " set to " << name << "\n";+    return 0;+  }+  if (sub == "list") {+    const auto lines = auth::list_credential_lines();+    if (lines.empty())+      std::cout << "no stored credentials\n";+    for (const auto &line : lines)+      std::cout << line;+    return 0;+  }+  if (sub == "remove") {+    const std::string target = auth::normalize_target(arg_at(args, 3));+    if (auth::remove_key(target)) {+      std::cout << "removed " << target << "\n";+      return 0;+    }+    error_prefix();+    std::cout << "no credential for " << target << "\n";+    return 1;+  }+  error_prefix();+  std::cout << "unknown auth subcommand: " << sub << "\n";+  auth_usage();+  return 1;+}++// ---------------------------------------------------------------------------+// access+// ---------------------------------------------------------------------------++int access_run(const std::vector<std::string> &args) {+  const std::string sub = arg_at(args, 2);+  if (sub.empty()) {+    error_prefix();+    std::cout << "expected access subcommand\n";+    return 1;+  }+  auto repo = discover_repo(".");+  if (!repo) {+    error_prefix();+    std::cout << "not a veins repository\n";+    return 1;+  }+  const fs::path root = *repo;+  if (sub == "add") {+    std::string role;+    std::string key_arg;+    std::string name;+    for (std::size_t i = 3; i < args.size(); ++i) {+      const std::string &arg = args[i];+      if (arg == "-role" && i + 1 < args.size()) {+        role = args[++i];+      } else if (arg == "-key" && i + 1 < args.size()) {+        key_arg = args[++i];+      } else if (arg == "-name" && i + 1 < args.size()) {+        name = args[++i];+      } else {+        error_prefix();+        std::cout << "unknown access add option: " << arg << "\n";+        return 1;+      }+    }+    if (role.empty() || key_arg.empty()) {+      error_prefix();+      std::cout << "access add requires -role and -key\n";+      return 1;+    }+    std::uint8_t role_code = auth::ROLE_READ;+    if (role == "write") {+      role_code = auth::ROLE_WRITE;+    } else if (role != "read") {+      error_prefix();+      std::cout << "role must be read or write\n";+      return 1;+    }+    auto public_key = read_public_key(key_arg);+    if (!public_key) {+      error_prefix();+      std::cout << "invalid public key\n";+      return 1;+    }+    if (!auth::add_access(root, role_code, *public_key, name)) {+      error_prefix();+      std::cout << "cannot add key\n";+      return 1;+    }+    info_prefix();+    std::cout << "access granted\n";+    return 0;+  }+  if (sub == "list") {+    const auth::Access access = auth::load_access(root);+    if (!access.valid) {+      error_prefix();+      std::cout << "invalid access file at line " << access.error_line << "\n";+      return 1;+    }+    std::cout << "anonymous: " << (access.anonymous_read ? "read" : "off")+              << "\n";+    for (const auto &entry : access.entries) {+      std::cout << (entry.role == auth::ROLE_WRITE ? "write" : "read") << " "+                << key_fingerprint(entry.public_key) << " " << entry.name+                << "\n";+    }+    return 0;+  }+  if (sub == "remove") {+    const std::string arg = arg_at(args, 3);+    if (arg.empty()) {+      error_prefix();+      std::cout << "access remove requires a fingerprint or name\n";+      return 1;+    }+    const bool is_fingerprint = arg.size() == 26;+    const std::string fingerprint = is_fingerprint ? arg : std::string();+    const std::string name = is_fingerprint ? std::string() : arg;+    if (!auth::remove_access(root, fingerprint, name)) {+      error_prefix();+      std::cout << "key not found or cannot write access file\n";+      return 1;+    }+    info_prefix();+    std::cout << "access removed\n";+    return 0;+  }+  if (sub == "anonymous") {+    const bool on = arg_at(args, 3) == "on";+    if (!auth::set_anonymous(root, on)) {+      error_prefix();+      std::cout << "cannot update access file\n";+      return 1;+    }+    return 0;+  }+  error_prefix();+  std::cout << "unknown access subcommand: " << sub << "\n";+  return 1;+}++// ---------------------------------------------------------------------------+// whoami+// ---------------------------------------------------------------------------++int whoami_run(const std::vector<std::string> &args) {+  std::string remote = "origin";+  std::string url;+  std::string key;+  std::string repo_name;+  std::string pin;+  const std::string arg = arg_at(args, 2);+  if (!arg.empty()) {+    if (starts_with(arg, "file://") || starts_with(arg, "ssh://") ||+        starts_with(arg, "veins://")) {+      url = arg;+      repo_name = proto::url_repo_name(url);+    } else {+      remote = arg;+    }+  }+  if (url.empty()) {+    auto repo = discover_repo(".");+    if (!repo) {+      error_prefix();+      std::cout << "not a veins repository\n";+      return 1;+    }+    const fs::path root = *repo;+    auto configured = config_value(root, remote_key(remote, "url"));+    if (!configured) {+      error_prefix();+      std::cout << "unknown remote\n";+      return 1;+    }+    url = *configured;+    if (auto k = config_value(root, remote_key(remote, "key"))) {+      if (auth::local_key_exists(*k))+        key = *k;+    }+    if (auto p = config_value(root, remote_key(remote, "tls-pin")))+      pin = *p;+    repo_name = proto::url_repo_name(url);+  }+  if (key.empty()) {+    if (auto fallback = auth::key_for_url(url))+      key = *fallback;+  }+  auto client = proto::Client::connect(url, key, repo_name, pin);+  if (!client) {+    error_prefix();+    std::cout << "cannot authenticate\n";+    return 1;+  }+  std::uint8_t role = 0;+  std::string fingerprint;+  if (!client->whoami(role, fingerprint)) {+    error_prefix();+    std::cout << "cannot authenticate\n";+    return 1;+  }+  std::cout << "role: " << role_text(role) << "\n";+  std::cout << "fingerprint: " << base32_text(bytes_of(fingerprint)) << "\n";+  return 0;+}++// ---------------------------------------------------------------------------+// Help+// ---------------------------------------------------------------------------++bool net_help(std::string_view command) {+  if (command == "remote") {+    std::cout << "usage: vn remote <add|set-url|list|remove> ...\n\n";+    std::cout << "manage native remotes stored in .veins/config\n\n";+    std::cout << "subcommands:\n";+    std::cout << "  add <name> <url> [-key:<name>] [-tls-pin:<hash>]\n";+    std::cout << "                            add a remote\n";+    std::cout << "  set-url <name> <url> [-key:<name>] [-tls-pin:<hash>]\n";+    std::cout << "                            change a remote URL (and "+                 "optionally key/pin)\n";+    std::cout << "  list                      list remotes\n";+    std::cout << "  remove <name>             remove a remote\n\n";+    std::cout << "an empty -key: or -tls-pin: value clears that setting\n\n";+    std::cout << "examples:\n";+    std::cout << "  vn remote add origin veins://127.0.0.1:7419/navid-m/veins2\n";+    std::cout << "  vn remote set-url origin veins://example/repo -key:my-key\n";+    return true;+  }+  if (command == "clone") {+    std::cout << "usage: vn clone <url> [-blobs:<head|none|all>] [-key:<name>] "+                 "[-pin:<sha256>] [path]\n\n";+    std::cout << "clone a repository over file://, ssh://, or veins://\n\n";+    std::cout << "without -key, the key stored by 'vn auth use' is used when "+                 "available\n";+    return true;+  }+  if (command == "fetch") {+    std::cout << "usage: vn fetch [-key:<name>] [<remote>] [path]\n\n";+    std::cout << "fetch new history and chunks from a configured native "+                 "remote\n\n";+    std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";+    return true;+  }+  if (command == "push") {+    std::cout << "usage: vn push [-key:<name>] [<remote>] <bookmark> [path]\n\n";+    std::cout << "push a bookmark to a configured native remote\n\n";+    std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";+    return true;+  }+  if (command == "serve") {+    std::cout << "usage: vn serve -stdio <repo>\n";+    std::cout << "       vn serve -listen <addr:port> -root <dir> -tls-cert "+                 "<file> -tls-key <file>\n\n";+    std::cout << "run the native server over standard input/output or TLS 1.3\n";+    return true;+  }+  if (command == "key") {+    std::cout << "usage: vn key <generate|list|show> [name]\n\n";+    std::cout << "manage local Ed25519 keys in the user key directory\n";+    return true;+  }+  if (command == "auth") {+    std::cout << "usage: vn auth <use|list|remove> ...\n\n";+    std::cout << "remember which key clone/fetch/push should use\n\n";+    std::cout << "  vn auth use <key> [<host|url>]   set the default or host "+                 "key\n";+    std::cout << "  vn auth list                     show stored key mappings\n";+    std::cout << "  vn auth remove [<host|url>]      remove a mapping\n";+    return true;+  }+  if (command == "access") {+    std::cout << "usage: vn access <add|list|remove|anonymous> ...\n\n";+    std::cout << "manage a served repository's .veins/access policy\n";+    return true;+  }+  if (command == "whoami") {+    std::cout << "usage: vn whoami [<remote>|<url>]\n\n";+    std::cout << "connect to a server and report the granted role and key "+                 "fingerprint\n";+    return true;+  }+  return false;+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/net_commands.h@@ -0,0 +1,23 @@+#pragma once++#include <string>+#include <string_view>+#include <vector>++namespace vn {++int remote_run(const std::vector<std::string> &args);+int clone_run(const std::vector<std::string> &args);+int fetch_run(const std::vector<std::string> &args);+int push_run(const std::vector<std::string> &args);+int serve_run(const std::vector<std::string> &args);+int key_run(const std::vector<std::string> &args);+int auth_run(const std::vector<std::string> &args);+int access_run(const std::vector<std::string> &args);+int whoami_run(const std::vector<std::string> &args);++// Print help for a network command. Returns false when `command` is not one of+// them.+bool net_help(std::string_view command);++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/promisor.cpp@@ -0,0 +1,57 @@+#include "promisor.h"++#include "protocol.h"+#include "store.h"++#include <optional>+#include <string>+#include <vector>++namespace vn {++namespace {++std::string remote_field(std::string_view remote, std::string_view field) {+  std::string out = "remote.";+  out += remote;+  out.push_back('.');+  out += field;+  return out;+}++bool fetch_missing_chunk(const fs::path &root, const Id &id) {+  static thread_local bool active = false;+  if (active)+    return false;+  active = true;+  struct Guard {+    bool &flag;+    ~Guard() { flag = false; }+  } guard{active};++  auto promisor = repo_config_value(root, "promisor");+  if (!promisor || promisor->empty())+    return false;+  auto url = repo_config_value(root, remote_field(*promisor, "url"));+  if (!url || url->empty())+    return false;+  auto key = repo_config_value(root, remote_field(*promisor, "key"));+  auto pin = repo_config_value(root, remote_field(*promisor, "tls-pin"));+  const std::string repo_name = proto::url_repo_name(*url);+  auto client = proto::Client::connect(*url, key ? *key : std::string(),+                                       repo_name, pin ? *pin : std::string());+  if (!client)+    return false;+  const std::vector<Id> ids = {id};+  return client->get_chunks(root, ids);+}++} // namespace++void install_promisor_fetcher() {+  set_promisor_fetcher([](const fs::path &root, const Id &id) {+    return fetch_missing_chunk(root, id);+  });+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/promisor.h@@ -0,0 +1,9 @@+#pragma once++namespace vn {++// Register the lazy-chunk fetch hook used by the store. Safe to call more than+// once; the last registration wins.+void install_promisor_fetcher();++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/protocol.cpp@@ -0,0 +1,901 @@+#include "protocol.h"++#include "auth.h"+#include "store.h"++#include <blake3.h>++#include <algorithm>+#include <array>+#include <cstring>++namespace vn::proto {++namespace {++void put_u16_be(ByteWriter &writer, std::uint16_t value) {+  writer.u8(static_cast<std::uint8_t>((value >> 8) & 255u));+  writer.u8(static_cast<std::uint8_t>(value & 255u));+}++std::optional<std::uint16_t> read_u16_be(Reader &reader) {+  const auto high = reader.u8();+  if (!high)+    return std::nullopt;+  const auto low = reader.u8();+  if (!low)+    return std::nullopt;+  return static_cast<std::uint16_t>((static_cast<std::uint16_t>(*high) << 8) |+                                    *low);+}++std::vector<std::uint8_t>+encode_string_list(const std::vector<std::string> &items) {+  ByteWriter writer(128);+  writer.varint(items.size());+  for (const auto &item : items)+    writer.length_prefixed(item);+  return writer.take();+}++std::optional<std::vector<std::string>> decode_string_list(Reader &reader,+                                                           std::size_t max) {+  const auto count = reader.list_len(max);+  if (!count)+    return std::nullopt;+  std::vector<std::string> out;+  out.reserve(*count);+  for (std::size_t i = 0; i < *count; ++i) {+    const auto value = reader.bytes(4096);+    if (!value)+      return std::nullopt;+    out.emplace_back(str_of(*value));+  }+  return out;+}++std::string bytes_to_string(Bytes data) { return std::string(str_of(data)); }++void append_id(ByteWriter &writer, const Id &id) {+  writer.raw(Bytes(id.data(), id.size()));+}++std::optional<Id> read_id(Reader &reader) {+  const auto id = reader.id();+  if (!id)+    return std::nullopt;+  return *id;+}++std::size_t find_char(std::string_view text, char needle) {+  const auto at = text.find(needle);+  return at == std::string_view::npos ? std::string_view::npos : at;+}++struct Authority {+  std::string host;+  int port = 0;+};++Authority parse_authority(std::string_view authority, int default_port,+                          bool strip_user) {+  if (strip_user) {+    const auto at = find_char(authority, '@');+    if (at != std::string_view::npos)+      authority.remove_prefix(at + 1);+  }+  Authority out;+  out.host = std::string(authority);+  out.port = default_port;+  const auto colon = find_char(authority, ':');+  if (colon != std::string_view::npos) {+    out.host = std::string(authority.substr(0, colon));+    const std::string_view port_text = authority.substr(colon + 1);+    if (!port_text.empty()) {+      int port = 0;+      bool numeric = true;+      for (char c : port_text) {+        if (c < '0' || c > '9') {+          numeric = false;+          break;+        }+        if (port > 1000000)+          port = 1000000;+        port = port * 10 + (c - '0');+      }+      if (numeric)+        out.port = port;+    }+  }+  return out;+}++std::optional<net::Stream> connect_stream(const Url &url,+                                          std::string_view tls_pin,+                                          std::string &binding) {+  if (url.ssh) {+    std::vector<std::string> remote = {"vn", "serve", "-stdio", url.path};+    const std::string remote_command = net::build_shell_command(remote);+    std::vector<std::string> argv = {"ssh"};+    if (url.port != 22) {+      argv.push_back("-p");+      argv.push_back(std::to_string(url.port));+    }+    argv.push_back(url.host);+    argv.push_back(remote_command);+    return net::Stream::spawn_argv(argv);+  }+  if (url.tls) {+    auto fd = net::tcp_connect(url.host, url.port);+    if (!fd)+      return std::nullopt;+    void *ctx = net::tls_client_ctx(!tls_pin.empty());+    if (!ctx) {+      net::close_socket(*fd);+      return std::nullopt;+    }+    void *ssl = net::tls_connect(ctx, *fd, url.host);+    net::tls_ctx_free(ctx);+    if (!ssl) {+      net::close_socket(*fd);+      return std::nullopt;+    }+    std::array<std::uint8_t, 32> exported{};+    if (net::tls_exporter(ssl, exported.data(), exported.size()))+      binding.assign(reinterpret_cast<const char *>(exported.data()),+                     exported.size());+    if (!tls_pin.empty()) {+      std::array<std::uint8_t, 32> digest{};+      const bool got = net::tls_peer_sha256(ssl, digest.data());+      const std::string hex = net::to_hex(Bytes(digest.data(), digest.size()));+      if (!got || !net::hex_equal(hex, tls_pin)) {+        net::close_socket(*fd);+        net::tls_free(ssl);+        return std::nullopt;+      }+    }+    return net::Stream::tls_stream(*fd, ssl);+  }+  std::vector<std::string> argv = {path_to_bytes(net::self_exe()), "serve",+                                   "-stdio", url.path};+  return net::Stream::spawn_argv(argv);+}++std::string id_text(const Id &id) { return hex_encode(id); }++} // namespace++// ---------------------------------------------------------------------------+// Message codecs+// ---------------------------------------------------------------------------++std::vector<std::uint8_t> encode_hello(const Hello &hello) {+  ByteWriter writer(128);+  put_u16_be(writer, hello.min_version);+  put_u16_be(writer, hello.max_version);+  writer.raw(Bytes(encode_string_list(hello.capabilities)));+  writer.length_prefixed(hello.repo);+  writer.length_prefixed(hello.client_nonce);+  return writer.take();+}++std::optional<Hello> decode_hello(Bytes data) {+  Reader reader(data);+  const auto min_version = read_u16_be(reader);+  if (!min_version)+    return std::nullopt;+  const auto max_version = read_u16_be(reader);+  if (!max_version)+    return std::nullopt;+  auto capabilities = decode_string_list(reader, 64);+  if (!capabilities)+    return std::nullopt;+  const auto repo = reader.bytes(4096);+  if (!repo)+    return std::nullopt;+  const auto nonce = reader.bytes(64);+  if (!nonce)+    return std::nullopt;+  if (!reader.finish())+    return std::nullopt;+  Hello out;+  out.min_version = *min_version;+  out.max_version = *max_version;+  out.capabilities = std::move(*capabilities);+  out.repo = bytes_to_string(*repo);+  out.client_nonce = bytes_to_string(*nonce);+  return out;+}++std::vector<std::uint8_t> encode_hello_ok(const HelloOk &hello) {+  ByteWriter writer(128);+  put_u16_be(writer, hello.version);+  writer.raw(Bytes(encode_string_list(hello.capabilities)));+  writer.length_prefixed(hello.server_nonce);+  writer.u8(hello.auth_required);+  return writer.take();+}++std::optional<HelloOk> decode_hello_ok(Bytes data) {+  Reader reader(data);+  const auto version = read_u16_be(reader);+  if (!version)+    return std::nullopt;+  auto capabilities = decode_string_list(reader, 64);+  if (!capabilities)+    return std::nullopt;+  const auto nonce = reader.bytes(64);+  if (!nonce)+    return std::nullopt;+  const auto auth = reader.u8();+  if (!auth)+    return std::nullopt;+  if (!reader.finish())+    return std::nullopt;+  HelloOk out;+  out.version = *version;+  out.capabilities = std::move(*capabilities);+  out.server_nonce = bytes_to_string(*nonce);+  out.auth_required = *auth;+  return out;+}++std::vector<std::uint8_t> encode_auth(const Auth &auth) {+  ByteWriter writer(128);+  writer.length_prefixed(auth.public_key);+  writer.length_prefixed(auth.signature);+  return writer.take();+}++std::optional<Auth> decode_auth(Bytes data) {+  Reader reader(data);+  const auto public_key = reader.bytes(64);+  if (!public_key)+    return std::nullopt;+  const auto signature = reader.bytes(128);+  if (!signature)+    return std::nullopt;+  if (!reader.finish())+    return std::nullopt;+  return Auth{bytes_to_string(*public_key), bytes_to_string(*signature)};+}++std::vector<std::uint8_t> encode_auth_ok(const AuthOk &auth) {+  ByteWriter writer(64);+  writer.u8(auth.role);+  writer.length_prefixed(auth.fingerprint);+  return writer.take();+}++std::optional<AuthOk> decode_auth_ok(Bytes data) {+  Reader reader(data);+  const auto role = reader.u8();+  if (!role)+    return std::nullopt;+  const auto fingerprint = reader.bytes(64);+  if (!fingerprint)+    return std::nullopt;+  if (!reader.finish())+    return std::nullopt;+  return AuthOk{*role, bytes_to_string(*fingerprint)};+}++std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo> &refs) {+  ByteWriter writer(256);+  writer.varint(refs.size());+  for (const auto &ref : refs) {+    writer.length_prefixed(ref.name);+    append_id(writer, ref.target);+    writer.length_prefixed(ref.change_id);+    writer.u8(ref.kind);+  }+  return writer.take();+}++std::optional<std::vector<RefInfo>> decode_refs(Bytes data) {+  Reader reader(data);+  const auto count = reader.list_len(1000000);+  if (!count)+    return std::nullopt;+  std::vector<RefInfo> out;+  out.reserve(*count);+  for (std::size_t i = 0; i < *count; ++i) {+    const auto name = reader.bytes(4096);+    if (!name)+      return std::nullopt;+    const auto target = read_id(reader);+    if (!target)+      return std::nullopt;+    const auto change_id = reader.bytes(64);+    if (!change_id)+      return std::nullopt;+    const auto kind = reader.u8();+    if (!kind)+      return std::nullopt;+    RefInfo ref;+    ref.name = bytes_to_string(*name);+    ref.target = *target;+    ref.change_id = bytes_to_string(*change_id);+    ref.kind = *kind;+    out.push_back(std::move(ref));+  }+  if (!reader.finish())+    return std::nullopt;+  return out;+}++std::vector<std::uint8_t> encode_ids(const std::vector<Id> &ids) {+  ByteWriter writer(ids.size() * 32 + 8);+  writer.varint(ids.size());+  for (const auto &id : ids)+    append_id(writer, id);+  return writer.take();+}++std::optional<std::vector<Id>> decode_ids(Bytes data, std::size_t max) {+  Reader reader(data);+  const auto count = reader.list_len(max);+  if (!count)+    return std::nullopt;+  std::vector<Id> out;+  out.reserve(*count);+  for (std::size_t i = 0; i < *count; ++i) {+    const auto id = read_id(reader);+    if (!id)+      return std::nullopt;+    out.push_back(*id);+  }+  if (!reader.finish())+    return std::nullopt;+  return out;+}++std::vector<std::uint8_t> encode_negotiate(const std::vector<Id> &wants,+                                           const std::vector<Id> &haves) {+  ByteWriter writer(256);+  writer.varint(wants.size());+  for (const auto &id : wants)+    append_id(writer, id);+  writer.varint(haves.size());+  for (const auto &id : haves)+    append_id(writer, id);+  return writer.take();+}++std::optional<Negotiate> decode_negotiate(Bytes data) {+  Reader reader(data);+  const auto want_count = reader.list_len(1000000);+  if (!want_count)+    return std::nullopt;+  Negotiate out;+  out.wants.reserve(*want_count);+  for (std::size_t i = 0; i < *want_count; ++i) {+    const auto id = read_id(reader);+    if (!id)+      return std::nullopt;+    out.wants.push_back(*id);+  }+  const auto have_count = reader.list_len(1000000);+  if (!have_count)+    return std::nullopt;+  out.haves.reserve(*have_count);+  for (std::size_t i = 0; i < *have_count; ++i) {+    const auto id = read_id(reader);+    if (!id)+      return std::nullopt;+    out.haves.push_back(*id);+  }+  if (!reader.finish())+    return std::nullopt;+  return out;+}++std::vector<std::uint8_t>+encode_negotiate_ok(const std::vector<std::uint8_t> &known,+                    std::uint8_t enough) {+  ByteWriter writer(known.size() + 16);+  writer.u8(enough);+  writer.varint(known.size());+  for (std::uint8_t bit : known)+    writer.u8(bit);+  return writer.take();+}++std::optional<std::vector<std::uint8_t>> decode_negotiate_ok(Bytes data) {+  Reader reader(data);+  const auto enough = reader.u8();+  if (!enough)+    return std::nullopt;+  const auto count = reader.list_len(1000000);+  if (!count)+    return std::nullopt;+  std::vector<std::uint8_t> out;+  out.reserve(*count);+  for (std::size_t i = 0; i < *count; ++i) {+    const auto bit = reader.u8();+    if (!bit)+      return std::nullopt;+    out.push_back(*bit);+  }+  if (!reader.finish())+    return std::nullopt;+  return out;+}++std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t> &bits) {+  ByteWriter writer(bits.size() + 8);+  writer.varint(bits.size());+  for (std::uint8_t bit : bits)+    writer.u8(bit);+  return writer.take();+}++std::optional<std::vector<std::uint8_t>> decode_bitmap(Bytes data) {+  Reader reader(data);+  const auto count = reader.list_len(1000000);+  if (!count)+    return std::nullopt;+  std::vector<std::uint8_t> out;+  out.reserve(*count);+  for (std::size_t i = 0; i < *count; ++i) {+    const auto bit = reader.u8();+    if (!bit)+      return std::nullopt;+    out.push_back(*bit);+  }+  if (!reader.finish())+    return std::nullopt;+  return out;+}++std::vector<std::uint8_t>+encode_update_refs(const std::vector<UpdateRef> &updates) {+  ByteWriter writer(256);+  writer.varint(updates.size());+  for (const auto &update : updates) {+    writer.length_prefixed(update.name);+    writer.opt_id(update.expected);+    writer.opt_id(update.target);+  }+  return writer.take();+}++std::optional<std::vector<UpdateRef>> decode_update_refs(Bytes data) {+  Reader reader(data);+  const auto count = reader.list_len(1000000);+  if (!count)+    return std::nullopt;+  std::vector<UpdateRef> out;+  out.reserve(*count);+  for (std::size_t i = 0; i < *count; ++i) {+    const auto name = reader.bytes(4096);+    if (!name)+      return std::nullopt;+    const auto expected = reader.opt_id();+    if (!expected)+      return std::nullopt;+    const auto target = reader.opt_id();+    if (!target)+      return std::nullopt;+    UpdateRef update;+    update.name = bytes_to_string(*name);+    update.expected = *expected;+    update.target = *target;+    out.push_back(std::move(update));+  }+  if (!reader.finish())+    return std::nullopt;+  return out;+}++std::string auth_message(std::uint16_t version, std::string_view repo,+                         Bytes server_nonce, Bytes client_nonce, Bytes binding) {+  ByteWriter writer(128);+  writer.raw(std::string_view("veins-auth/1"));+  writer.u8(0);+  writer.u8(static_cast<std::uint8_t>((version >> 8) & 255u));+  writer.u8(static_cast<std::uint8_t>(version & 255u));+  writer.length_prefixed(repo);+  writer.raw(server_nonce);+  writer.raw(client_nonce);+  writer.raw(binding);+  return std::string(str_of(writer.view()));+}++std::string_view role_name(std::uint8_t role) {+  if (role == 2)+    return "write";+  if (role == 1)+    return "read";+  return "anonymous";+}++// ---------------------------------------------------------------------------+// URLs+// ---------------------------------------------------------------------------++std::optional<Url> parse_url(std::string_view url) {+  constexpr std::string_view file_prefix = "file://";+  constexpr std::string_view ssh_prefix = "ssh://";+  constexpr std::string_view veins_prefix = "veins://";+  if (url.starts_with(file_prefix))+    return Url{false, false, {}, 0, std::string(url.substr(file_prefix.size()))};+  if (url.starts_with(ssh_prefix)) {+    std::string_view rest = url.substr(ssh_prefix.size());+    const auto slash = rest.find('/');+    if (slash == std::string_view::npos)+      return std::nullopt;+    const auto authority = parse_authority(rest.substr(0, slash), 22, true);+    return Url{false, true, authority.host, authority.port,+               std::string(rest.substr(slash + 1))};+  }+  if (url.starts_with(veins_prefix)) {+    std::string_view rest = url.substr(veins_prefix.size());+    const auto slash = rest.find('/');+    if (slash == std::string_view::npos)+      return std::nullopt;+    const auto authority = parse_authority(rest.substr(0, slash), 7419, false);+    return Url{true, false, authority.host, authority.port,+               std::string(rest.substr(slash + 1))};+  }+  return std::nullopt;+}++std::string url_repo_name(std::string_view url) {+  auto parsed = parse_url(url);+  if (!parsed || !parsed->tls)+    return {};+  return parsed->path;+}++// ---------------------------------------------------------------------------+// Client+// ---------------------------------------------------------------------------++void Client::set_error(std::string text) { last_error_ = std::move(text); }++void Client::set_error_frame(const wire::Frame &frame) {+  const std::uint8_t code = wire::read_error(frame.payload);+  const std::string_view name = wire::error_code_name(code);+  const std::string message = wire::error_message(frame.payload);+  std::string text = "server error: ";+  text += name;+  if (!message.empty()) {+    text += ": ";+    text += message;+  }+  set_error(std::move(text));+}++std::optional<wire::Frame> Client::request(std::uint8_t kind, Bytes payload) {+  const std::uint32_t rid =+      static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+  if (!wire::write_frame(stream_, kind, rid, payload)) {+    set_error("connection closed while sending request");+    return std::nullopt;+  }+  auto frame = wire::read_frame(stream_);+  if (!frame) {+    set_error("connection closed while waiting for server response");+    return std::nullopt;+  }+  if (frame->kind == wire::ERROR) {+    set_error_frame(*frame);+    return std::nullopt;+  }+  return frame;+}++std::optional<Client> Client::connect(std::string_view url,+                                      std::string_view key_name,+                                      std::string_view repo_name,+                                      std::string_view tls_pin) {+  auto parsed = parse_url(url);+  if (!parsed)+    return std::nullopt;+  std::string binding;+  auto stream = connect_stream(*parsed, tls_pin, binding);+  if (!stream)+    return std::nullopt;++  const auto nonce_bytes = secure_random(32);+  if (nonce_bytes.size() != 32) {+    stream->close();+    return std::nullopt;+  }+  const std::string client_nonce(reinterpret_cast<const char *>(+                                     nonce_bytes.data()),+                                 nonce_bytes.size());++  Hello hello;+  hello.capabilities = {"zstd-records", "lazy-chunks", "push", "auth-ed25519"};+  hello.repo = std::string(repo_name);+  hello.client_nonce = client_nonce;+  const auto hello_body = encode_hello(hello);+  if (!wire::write_frame(*stream, wire::HELLO, 1, hello_body)) {+    stream->close();+    return std::nullopt;+  }+  auto hello_frame = wire::read_frame(*stream);+  if (!hello_frame || hello_frame->kind != wire::HELLO_OK) {+    stream->close();+    return std::nullopt;+  }+  auto hello_ok = decode_hello_ok(hello_frame->payload);+  if (!hello_ok) {+    stream->close();+    return std::nullopt;+  }++  Client client;+  client.stream_ = std::move(*stream);+  client.binding_ = std::move(binding);+  client.version_ = hello_ok->version;++  std::string selected_key(key_name);+  if (selected_key.empty() && hello_ok->auth_required != 0)+    selected_key = "default";++  if (!selected_key.empty()) {+    auto key = auth::load_key(selected_key);+    if (key) {+      const std::string message = auth_message(+          hello_ok->version, repo_name,+          Bytes(reinterpret_cast<const std::uint8_t *>(+                    hello_ok->server_nonce.data()),+                hello_ok->server_nonce.size()),+          Bytes(reinterpret_cast<const std::uint8_t *>(client_nonce.data()),+                client_nonce.size()),+          Bytes(reinterpret_cast<const std::uint8_t *>(client.binding_.data()),+                client.binding_.size()));+      auto signature = ed25519_sign(Bytes(key->seed.data(), key->seed.size()),+                                    Bytes(reinterpret_cast<const std::uint8_t *>(+                                              message.data()),+                                          message.size()));+      if (signature) {+        Auth auth;+        auth.public_key.assign(+            reinterpret_cast<const char *>(key->public_key.data()),+            key->public_key.size());+        auth.signature.assign(+            reinterpret_cast<const char *>(signature->data()),+            signature->size());+        const auto body = encode_auth(auth);+        if (wire::write_frame(client.stream_, wire::AUTH, 2, body)) {+          auto reply = wire::read_frame(client.stream_);+          if (reply && reply->kind == wire::AUTH_OK) {+            auto ok = decode_auth_ok(reply->payload);+            if (ok) {+              client.role_ = ok->role;+              client.authed_ = true;+              client.fingerprint_ = std::move(ok->fingerprint);+            }+          }+        }+      }+    }+  }++  if (hello_ok->auth_required != 0 && !client.authed_) {+    client.stream_.close();+    return std::nullopt;+  }+  return client;+}++bool Client::list_refs(std::vector<RefInfo> &refs) {+  auto frame = request(wire::LIST_REFS, Bytes{});+  if (!frame)+    return false;+  if (frame->kind != wire::REFS) {+    set_error("unexpected response to ref listing (message kind " ++              std::to_string(frame->kind) + ")");+    return false;+  }+  auto decoded = decode_refs(frame->payload);+  if (!decoded)+    return false;+  refs = std::move(*decoded);+  return true;+}++bool Client::negotiate(const std::vector<Id> &wants,+                       const std::vector<Id> &haves) {+  const auto body = encode_negotiate(wants, haves);+  auto frame = request(wire::NEGOTIATE, body);+  if (!frame)+    return false;+  if (frame->kind != wire::NEGOTIATE_OK) {+    set_error("unexpected response to negotiation (message kind " ++              std::to_string(frame->kind) + ")");+    return false;+  }+  return true;+}++bool Client::receive_stream(const fs::path &repo) {+  blake3_hasher hasher;+  blake3_hasher_init(&hasher);+  Writer writer;+  bool good = true;++  for (;;) {+    auto frame = wire::read_frame(stream_);+    if (!frame) {+      set_error("connection closed while receiving data");+      return false;+    }+    if (frame->kind == wire::END) {+      std::array<std::uint8_t, 32> digest{};+      blake3_hasher_finalize(&hasher, digest.data(), digest.size());+      if (frame->payload.size() != digest.size() ||+          std::memcmp(frame->payload.data(), digest.data(), digest.size()) !=+              0) {+        set_error("server sent a corrupt transfer checksum");+        return false;+      }+      break;+    }+    if (frame->kind == wire::ERROR) {+      set_error_frame(*frame);+      return false;+    }+    if (frame->kind != wire::RECORDS) {+      set_error("unexpected message while receiving data (message kind " ++                std::to_string(frame->kind) + ")");+      return false;+    }+    blake3_hasher_update(&hasher, frame->payload.data(), frame->payload.size());+    auto record = wire::parse_record(bytes_of(frame->payload));+    if (!record) {+      good = false;+    } else {+      const Id computed =+          object_id(record->kind, bytes_of(record->body));+      if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {+        good = false;+      } else {+        writer.add_known(record->kind, record->id, std::move(record->body));+      }+    }+    if (!good)+      return false;+  }++  if (!writer.finish(repo)) {+    set_error("cannot write incoming objects to the store");+    return false;+  }+  return true;+}++bool Client::fetch_skeleton(const fs::path &repo,+                            const std::vector<Id> &wants) {+  const auto body = encode_ids(wants);+  const std::uint32_t rid =+      static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+  if (!wire::write_frame(stream_, wire::FETCH_SKELETON, rid, body)) {+    set_error("connection closed while requesting objects");+    return false;+  }+  return receive_stream(repo);+}++bool Client::get_chunks(const fs::path &repo, const std::vector<Id> &ids) {+  if (ids.empty())+    return true;+  const auto body = encode_ids(ids);+  const std::uint32_t rid =+      static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+  if (!wire::write_frame(stream_, wire::GET_CHUNKS, rid, body)) {+    set_error("connection closed while requesting chunks");+    return false;+  }+  return receive_stream(repo);+}++bool Client::have_query(const std::vector<Id> &ids,+                        std::vector<std::uint8_t> &bits) {+  const auto body = encode_ids(ids);+  auto frame = request(wire::HAVE_QUERY, body);+  if (!frame)+    return false;+  if (frame->kind != wire::HAVE_BITMAP)+    return false;+  auto decoded = decode_bitmap(frame->payload);+  if (!decoded)+    return false;+  bits = std::move(*decoded);+  return true;+}++bool Client::push_objects(const fs::path &repo, const std::vector<Id> &ids) {+  const std::uint32_t rid =+      static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+  if (!wire::write_frame(stream_, wire::PUT_RECORDS, rid, Bytes{})) {+    set_error("connection closed while starting push");+    return false;+  }+  Store store = Store::open_all(repo);+  blake3_hasher hasher;+  blake3_hasher_init(&hasher);+  bool good = true;+  for (const auto &id : ids) {+    const auto loc = store.find(id);+    if (!loc) {+      set_error("local object is missing from the store: " + id_text(id));+      good = false;+      break;+    }+    auto body = store.read_body(id, loc->kind);+    if (!body) {+      set_error("cannot read local object from the store: " + id_text(id));+      good = false;+      break;+    }+    const auto record = wire::make_record(id, loc->kind, bytes_of(*body));+    blake3_hasher_update(&hasher, record.data(), record.size());+    if (!wire::write_frame(stream_, wire::RECORDS, rid,+                           Bytes(record.data(), record.size()))) {+      set_error("connection closed while sending object: " + id_text(id));+      good = false;+      break;+    }+  }+  std::array<std::uint8_t, 32> digest{};+  blake3_hasher_finalize(&hasher, digest.data(), digest.size());+  if (!good)+    return false;+  if (!wire::write_frame(stream_, wire::END, rid,+                         Bytes(digest.data(), digest.size()))) {+    set_error("connection closed while finishing push");+    return false;+  }+  auto ack = wire::read_frame(stream_);+  if (!ack) {+    set_error("server closed the connection before acknowledging the push");+    return false;+  }+  if (ack->kind == wire::END)+    return true;+  if (ack->kind == wire::ERROR) {+    set_error_frame(*ack);+    return false;+  }+  set_error("unexpected response to object push (message kind " ++            std::to_string(ack->kind) + ")");+  return false;+}++bool Client::update_refs(const std::vector<UpdateRef> &updates) {+  const auto body = encode_update_refs(updates);+  auto frame = request(wire::UPDATE_REFS, body);+  if (!frame)+    return false;+  if (frame->kind != wire::UPDATE_REFS_OK) {+    set_error("unexpected response to ref update (message kind " ++              std::to_string(frame->kind) + ")");+    return false;+  }+  return true;+}++bool Client::whoami(std::uint8_t &role, std::string &fingerprint) {+  auto frame = request(wire::WHOAMI, Bytes{});+  if (!frame)+    return false;+  if (frame->kind != wire::WHOAMI_OK)+    return false;+  Reader reader(frame->payload);+  const auto role_value = reader.u8();+  if (!role_value)+    return false;+  const auto fp = reader.bytes(64);+  if (!fp)+    return false;+  role = *role_value;+  fingerprint = bytes_to_string(*fp);+  return true;+}++} // namespace vn::proto--- /dev/null+++ b/veins-cpprewrite/src/protocol.h@@ -0,0 +1,162 @@+#pragma once++#include "crypto.h"+#include "net.h"+#include "wire.h"++#include <cstdint>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++namespace vn::proto {++constexpr std::uint16_t PROTOCOL_VERSION = 1;++struct Hello {+  std::uint16_t min_version = PROTOCOL_VERSION;+  std::uint16_t max_version = PROTOCOL_VERSION;+  std::vector<std::string> capabilities;+  std::string repo;+  std::string client_nonce;+};++struct HelloOk {+  std::uint16_t version = 0;+  std::vector<std::string> capabilities;+  std::string server_nonce;+  std::uint8_t auth_required = 0;+};++struct Auth {+  std::string public_key;+  std::string signature;+};++struct AuthOk {+  std::uint8_t role = 0;+  std::string fingerprint;+};++struct RefInfo {+  std::string name;+  Id target{};+  std::string change_id;+  std::uint8_t kind = 0; // 0 bookmark, 1 tag+};++struct Negotiate {+  std::vector<Id> wants;+  std::vector<Id> haves;+};++struct UpdateRef {+  std::string name;+  std::optional<Id> expected;+  std::optional<Id> target;+};++std::vector<std::uint8_t> encode_hello(const Hello &hello);+std::optional<Hello> decode_hello(Bytes data);++std::vector<std::uint8_t> encode_hello_ok(const HelloOk &hello);+std::optional<HelloOk> decode_hello_ok(Bytes data);++std::vector<std::uint8_t> encode_auth(const Auth &auth);+std::optional<Auth> decode_auth(Bytes data);++std::vector<std::uint8_t> encode_auth_ok(const AuthOk &auth);+std::optional<AuthOk> decode_auth_ok(Bytes data);++std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo> &refs);+std::optional<std::vector<RefInfo>> decode_refs(Bytes data);++std::vector<std::uint8_t> encode_ids(const std::vector<Id> &ids);+std::optional<std::vector<Id>> decode_ids(Bytes data, std::size_t max);++std::vector<std::uint8_t> encode_negotiate(const std::vector<Id> &wants,+                                           const std::vector<Id> &haves);+std::optional<Negotiate> decode_negotiate(Bytes data);++std::vector<std::uint8_t> encode_negotiate_ok(const std::vector<std::uint8_t> &known,+                                              std::uint8_t enough);+std::optional<std::vector<std::uint8_t>> decode_negotiate_ok(Bytes data);++std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t> &bits);+std::optional<std::vector<std::uint8_t>> decode_bitmap(Bytes data);++std::vector<std::uint8_t> encode_update_refs(const std::vector<UpdateRef> &updates);+std::optional<std::vector<UpdateRef>> decode_update_refs(Bytes data);++// The bytes signed in AUTH.+std::string auth_message(std::uint16_t version, std::string_view repo,+                         Bytes server_nonce, Bytes client_nonce, Bytes binding);+std::string_view role_name(std::uint8_t role);++// ---------------------------------------------------------------------------+// URLs+// ---------------------------------------------------------------------------++struct Url {+  bool tls = false;+  bool ssh = false;+  std::string host;+  int port = 0;+  std::string path;+};++std::optional<Url> parse_url(std::string_view url);+std::string url_repo_name(std::string_view url);++// ---------------------------------------------------------------------------+// Client+// ---------------------------------------------------------------------------++class Client {+public:+  Client() = default;+  ~Client() = default;+  Client(Client &&) noexcept = default;+  Client &operator=(Client &&) noexcept = default;+  Client(const Client &) = delete;+  Client &operator=(const Client &) = delete;++  // Connect and authenticate. An empty key name means anonymous unless the+  // server requires authentication, in which case "default" is used.+  static std::optional<Client> connect(std::string_view url,+                                       std::string_view key_name,+                                       std::string_view repo_name,+                                       std::string_view tls_pin = {});++  bool list_refs(std::vector<RefInfo> &refs);+  bool negotiate(const std::vector<Id> &wants, const std::vector<Id> &haves);+  bool fetch_skeleton(const fs::path &repo, const std::vector<Id> &wants);+  bool get_chunks(const fs::path &repo, const std::vector<Id> &ids);+  bool have_query(const std::vector<Id> &ids, std::vector<std::uint8_t> &bits);+  bool push_objects(const fs::path &repo, const std::vector<Id> &ids);+  bool update_refs(const std::vector<UpdateRef> &updates);+  bool whoami(std::uint8_t &role, std::string &fingerprint);++  [[nodiscard]] const std::string &error() const { return last_error_; }+  [[nodiscard]] std::uint8_t role() const { return role_; }+  [[nodiscard]] bool authenticated() const { return authed_; }+  [[nodiscard]] const std::string &fingerprint() const { return fingerprint_; }+  [[nodiscard]] bool has_connection() const { return stream_.valid(); }++private:+  std::optional<wire::Frame> request(std::uint8_t kind, Bytes payload);+  bool receive_stream(const fs::path &repo);+  void set_error(std::string text);+  void set_error_frame(const wire::Frame &frame);++  net::Stream stream_;+  std::string binding_;+  std::uint16_t version_ = PROTOCOL_VERSION;+  std::uint8_t role_ = 0;+  bool authed_ = false;+  std::string fingerprint_;+  std::string last_error_;+};++} // namespace vn::proto--- /dev/null+++ b/veins-cpprewrite/src/server.cpp@@ -0,0 +1,912 @@+#include "server.h"++#include "auth.h"+#include "crypto.h"+#include "net.h"+#include "protocol.h"+#include "store.h"+#include "wire.h"++#include <blake3.h>++#include <algorithm>+#include <cstddef>+#include <cstring>+#include <iostream>+#include <optional>+#include <set>+#include <string>++namespace vn::server {++namespace {++constexpr std::size_t MAX_CHUNKS_PER_REQUEST = 4096;++struct Session {+  net::Stream stream;+  fs::path repo_root;+  bool repo_present = false;+  Store store;+  bool store_open = false;+  auth::Access access;+  std::string hello_repo;+  std::string server_nonce;+  std::string client_nonce;+  std::string binding;+  std::uint16_t version = proto::PROTOCOL_VERSION;+  bool authed = false;+  std::uint8_t role = auth::ROLE_ANONYMOUS;+  PublicKey public_key{};+  bool has_public_key = false;+  std::string fingerprint;+  std::vector<Id> haves;+  int failed_auth = 0;+  bool closing = false;+  fs::path root;+};++std::uint8_t effective_role(const Session &session) {+  if (session.authed)+    return session.role;+  if (session.access.valid && session.access.anonymous_read &&+      session.repo_present)+    return auth::ROLE_READ;+  return auth::ROLE_ANONYMOUS;+}++bool deny(Session &session, std::uint32_t request_id, bool write) {+  const std::uint8_t role = effective_role(session);+  if (write) {+    if (role == auth::ROLE_WRITE)+      return false;+    if (!session.authed) {+      wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,+                        "authentication required");+    } else {+      wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,+                        "write role required");+    }+    return true;+  }+  if (role == auth::ROLE_READ || role == auth::ROLE_WRITE)+    return false;+  if (!session.authed) {+    wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,+                      "authentication required");+  } else {+    wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,+                      "read role required");+  }+  return true;+}++void log_line(Session &session, std::string_view text) {+  if (!session.repo_present)+    return;+  (void)append_file(veins_dir(session.repo_root) / "server.log",+                    bytes_of(text));+}++void log_outcome(Session &session, std::string_view outcome) {+  if (!session.repo_present)+    return;+  const std::string line =+      std::to_string(unix_now_millis()) + " " ++      std::string(proto::role_name(effective_role(session))) + " " ++      std::string(outcome) + " " + session.hello_repo + "\n";+  log_line(session, line);+}++bool safe_repo_name(std::string_view name) {+  if (name.empty() || name.size() > 4096)+    return false;+  if (name.front() == '/')+    return false;+  if (name.find('\0') != std::string_view::npos ||+      name.find('\\') != std::string_view::npos)+    return false;+  std::size_t start = 0;+  for (std::size_t i = 0; i <= name.size(); ++i) {+    if (i == name.size() || name[i] == '/') {+      if (i - start == 2 && name[start] == '.' && name[start + 1] == '.')+        return false;+      start = i + 1;+    }+  }+  return true;+}++void open_session_store(Session &session) {+  if (session.store_open)+    return;+  session.store = Store::open_all(session.repo_root);+  session.store_open = true;+}++void select_repo(Session &session, bool has_root) {+  if (session.repo_present || !has_root)+    return;+  if (!safe_repo_name(session.hello_repo))+    return;+  const fs::path joined = session.root / path_from_bytes(session.hello_repo);+  if (auto found = discover_repo(joined)) {+    session.repo_root = *found;+    session.repo_present = true;+  }+}++std::string change_id_of(Session &session, const Id &id) {+  auto loaded = load_commit(session.store, id);+  if (!loaded)+    return {};+  return std::string(reinterpret_cast<const char *>(loaded->commit.change_id.data()),+                     loaded->commit.change_id.size());+}++bool send_record(Session &session, std::uint32_t request_id,+                 blake3_hasher &hasher, const Id &id, std::uint8_t kind,+                 Bytes body) {+  const auto record = wire::make_record(id, kind, body);+  blake3_hasher_update(&hasher, record.data(), record.size());+  return wire::write_frame(session.stream, wire::RECORDS, request_id,+                           Bytes(record.data(), record.size()));+}++bool send_end(Session &session, std::uint32_t request_id,+              blake3_hasher &hasher) {+  std::array<std::uint8_t, 32> digest{};+  blake3_hasher_finalize(&hasher, digest.data(), digest.size());+  return wire::write_frame(session.stream, wire::END, request_id,+                           Bytes(digest.data(), digest.size()));+}++std::uint8_t value_kind_to_type(std::uint8_t kind) {+  if (kind == KIND_SUBTREE)+    return TYPE_TREE;+  if (kind == KIND_CONFLICT)+    return TYPE_CONFLICT;+  if (kind == KIND_FILE || kind == KIND_EXECUTABLE || kind == KIND_SYMLINK)+    return TYPE_BLOB;+  return 0;+}++void collect_object(Session &session, std::uint32_t request_id,+                    blake3_hasher &hasher, const Id &id, std::uint8_t kind,+                    std::set<Id> &seen, bool send, bool &failed);++void collect_tree(Session &session, std::uint32_t request_id,+                  blake3_hasher &hasher, const Id &id, std::set<Id> &seen,+                  bool send, bool &failed) {+  if (!seen.insert(id).second)+    return;+  auto body = session.store.read_body(id, TYPE_TREE);+  if (!body) {+    failed = true;+    return;+  }+  if (send && !send_record(session, request_id, hasher, id, TYPE_TREE,+                           bytes_of(*body))) {+    failed = true;+  }+  auto tree = decode_tree(bytes_of(*body));+  if (!tree) {+    failed = true;+    return;+  }+  for (const auto &entry : tree->entries) {+    if (entry.kind == KIND_SUBTREE) {+      collect_tree(session, request_id, hasher, entry.target, seen, send,+                   failed);+    } else if (entry.kind == KIND_CONFLICT) {+      collect_object(session, request_id, hasher, entry.target, TYPE_CONFLICT,+                     seen, send, failed);+    } else if (entry.kind != KIND_SUBMODULE) {+      collect_object(session, request_id, hasher, entry.target, TYPE_BLOB, seen,+                     send, failed);+    }+    if (failed)+      return;+  }+}++void collect_object(Session &session, std::uint32_t request_id,+                    blake3_hasher &hasher, const Id &id, std::uint8_t kind,+                    std::set<Id> &seen, bool send, bool &failed) {+  if (!seen.insert(id).second)+    return;+  auto body = session.store.read_body(id, kind);+  if (!body) {+    failed = true;+    return;+  }+  if (send && !send_record(session, request_id, hasher, id, kind,+                           bytes_of(*body))) {+    failed = true;+  }+  if (kind == TYPE_BLOB) {+    auto blob = decode_blob(bytes_of(*body));+    if (!blob) {+      failed = true;+      return;+    }+    if (blob->form == BlobForm::Interior) {+      for (const auto &entry : blob->entries) {+        collect_object(session, request_id, hasher, entry.id, TYPE_BLOB, seen,+                       send, failed);+        if (failed)+          return;+      }+    }+  } else if (kind == TYPE_CONFLICT) {+    auto conflict = decode_conflict(bytes_of(*body));+    if (!conflict) {+      failed = true;+      return;+    }+    for (const auto &value : conflict->adds) {+      if (!value.target)+        continue;+      const std::uint8_t child = value_kind_to_type(value.kind);+      if (child != 0)+        collect_object(session, request_id, hasher, *value.target, child, seen,+                       send, failed);+      if (failed)+        return;+    }+    for (const auto &value : conflict->removes) {+      if (!value.target)+        continue;+      const std::uint8_t child = value_kind_to_type(value.kind);+      if (child != 0)+        collect_object(session, request_id, hasher, *value.target, child, seen,+                       send, failed);+      if (failed)+        return;+    }+  }+}++bool handle_hello(Session &session, const wire::Frame &frame, bool has_root) {+  auto hello = proto::decode_hello(bytes_of(frame.payload));+  if (!hello) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+                      "bad HELLO");+    return false;+  }+  if (hello->min_version > proto::PROTOCOL_VERSION ||+      hello->max_version < proto::PROTOCOL_VERSION) {+    wire::write_error(session.stream, frame.request_id,+                      wire::ERR_UNSUPPORTED_VERSION, "no common version");+    return false;+  }+  session.version = proto::PROTOCOL_VERSION;+  session.hello_repo = std::move(hello->repo);+  session.client_nonce = std::move(hello->client_nonce);+  select_repo(session, has_root);+  if (!session.repo_present && !session.hello_repo.empty()) {+    error_prefix();+    std::cout << "repository not found: " << session.hello_repo << "\n";+    wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,+                      "repository not found");+    return false;+  }+  if (session.repo_present) {+    session.access = auth::load_access(session.repo_root);+    if (!session.access.valid) {+      error_prefix();+      std::cout << "access file error at line " << session.access.error_line+                << " in " << path_display(session.repo_root) << "\n";+      wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+                        "invalid access file");+      return false;+    }+    open_session_store(session);+  }+  log_outcome(session, "hello");++  const auto nonce = secure_random(32);+  if (nonce.size() != 32) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+                      "cannot generate nonce");+    return false;+  }+  session.server_nonce.assign(reinterpret_cast<const char *>(nonce.data()),+                              nonce.size());++  proto::HelloOk hello_ok;+  hello_ok.version = session.version;+  hello_ok.capabilities = {"zstd-records", "lazy-chunks", "push",+                           "auth-ed25519"};+  hello_ok.server_nonce = session.server_nonce;+  hello_ok.auth_required =+      (session.repo_present && session.access.anonymous_read) ? 0 : 1;+  const auto body = proto::encode_hello_ok(hello_ok);+  return wire::write_frame(session.stream, wire::HELLO_OK, frame.request_id,+                           body);+}++bool handle_auth(Session &session, const wire::Frame &frame) {+  if (session.authed) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+                      "repeated AUTH");+    session.closing = true;+    return false;+  }+  auto auth = proto::decode_auth(bytes_of(frame.payload));+  if (!auth) {+    ++session.failed_auth;+    wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,+                      "authentication failed");+    return false;+  }+  PublicKey public_key{};+  const bool key_well_formed = auth->public_key.size() == public_key.size();+  if (key_well_formed) {+    std::memcpy(public_key.data(), auth->public_key.data(),+                public_key.size());+  }+  std::uint8_t role = auth::ROLE_UNKNOWN;+  if (key_well_formed && session.repo_present && session.access.valid)+    role = auth::role_for(session.access, &public_key);++  const std::string message = proto::auth_message(+      session.version, session.hello_repo, bytes_of(session.server_nonce),+      bytes_of(session.client_nonce), bytes_of(session.binding));+  const bool signature_ok =+      role != auth::ROLE_UNKNOWN &&+      ed25519_verify(public_key, bytes_of(message), bytes_of(auth->signature));+  if (!signature_ok) {+    ++session.failed_auth;+    wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,+                      "authentication failed");+    if (session.failed_auth >= 3)+      session.closing = true;+    return false;+  }++  session.authed = true;+  session.role = role;+  session.public_key = public_key;+  session.has_public_key = true;+  const auto raw_fingerprint = key_fingerprint_bytes(public_key);+  session.fingerprint.assign(+      reinterpret_cast<const char *>(raw_fingerprint.data()),+      raw_fingerprint.size());++  proto::AuthOk auth_ok;+  auth_ok.role = role;+  auth_ok.fingerprint = session.fingerprint;+  const auto body = proto::encode_auth_ok(auth_ok);+  const bool wrote = wire::write_frame(session.stream, wire::AUTH_OK,+                                       frame.request_id, body);+  log_outcome(session, "auth-ok");+  return wrote;+}++bool handle_whoami(Session &session, const wire::Frame &frame) {+  ByteWriter writer(64);+  writer.u8(effective_role(session));+  writer.length_prefixed(session.fingerprint);+  return wire::write_frame(session.stream, wire::WHOAMI_OK, frame.request_id,+                           writer.view());+}++bool handle_list_refs(Session &session, const wire::Frame &frame) {+  if (deny(session, frame.request_id, false))+    return true;+  log_outcome(session, "list-refs");+  std::optional<View> view = current_view(session.repo_root, session.store);+  if (!view) {+    const auto heads = read_heads(session.repo_root);+    if (!heads.empty()) {+      wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+                        "cannot read operation state");+      log_outcome(session, "list-refs-error");+      return true;+    }+    view = empty_view();+  }+  std::vector<proto::RefInfo> refs;+  for (const auto &bookmark : view->bookmarks) {+    if (bookmark.targets.adds.size() != 1 || !bookmark.targets.adds.front())+      continue;+    proto::RefInfo ref;+    ref.name = bookmark.name;+    ref.target = *bookmark.targets.adds.front();+    ref.change_id = change_id_of(session, ref.target);+    ref.kind = 0;+    refs.push_back(std::move(ref));+  }+  for (const auto &tag : view->tags) {+    proto::RefInfo ref;+    ref.name = tag.name;+    ref.target = tag.target;+    ref.change_id = change_id_of(session, tag.target);+    ref.kind = 1;+    refs.push_back(std::move(ref));+  }+  const auto body = proto::encode_refs(refs);+  const bool wrote =+      wire::write_frame(session.stream, wire::REFS, frame.request_id, body);+  if (!wrote)+    log_outcome(session, "list-refs-write-error");+  return wrote;+}++bool handle_negotiate(Session &session, const wire::Frame &frame) {+  if (deny(session, frame.request_id, false))+    return true;+  auto negotiate = proto::decode_negotiate(bytes_of(frame.payload));+  if (!negotiate) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+                      "bad NEGOTIATE");+    return true;+  }+  session.haves = std::move(negotiate->haves);+  std::vector<std::uint8_t> known;+  known.reserve(session.haves.size());+  bool any_known = false;+  for (const auto &id : session.haves) {+    const bool found = session.store.find(id).has_value();+    known.push_back(found ? 1 : 0);+    any_known = any_known || found;+  }+  const std::uint8_t enough =+      (session.haves.empty() || any_known) ? 1 : 0;+  const auto body = proto::encode_negotiate_ok(known, enough);+  return wire::write_frame(session.stream, wire::NEGOTIATE_OK,+                           frame.request_id, body);+}++bool handle_fetch(Session &session, const wire::Frame &frame) {+  if (deny(session, frame.request_id, false))+    return true;+  auto wants = proto::decode_ids(bytes_of(frame.payload), 1000000);+  if (!wants) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+                      "bad wants");+    return true;+  }+  if (wants->empty()) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+                      "empty wants");+    return true;+  }+  const auto all = collect_commits(session.store, *wants);+  std::set<Id> exclude;+  for (const auto &have : session.haves) {+    const std::array<Id, 1> roots{have};+    for (const auto &id : collect_commits(session.store, roots))+      exclude.insert(id);+  }++  blake3_hasher hasher;+  blake3_hasher_init(&hasher);+  bool failed = false;+  std::set<Id> seen;+  for (const auto &id : all) {+    if (exclude.contains(id))+      continue;+    auto loaded = load_commit(session.store, id);+    if (!loaded) {+      failed = true;+      break;+    }+    if (!send_record(session, frame.request_id, hasher, id, TYPE_COMMIT,+                     bytes_of(loaded->body))) {+      failed = true;+      break;+    }+    collect_tree(session, frame.request_id, hasher, loaded->commit.root_tree,+                 seen, true, failed);+    if (failed)+      break;+  }+  if (!failed)+    (void)send_end(session, frame.request_id, hasher);+  log_outcome(session, "fetch");+  return !failed;+}++bool handle_get_chunks(Session &session, const wire::Frame &frame) {+  if (deny(session, frame.request_id, false))+    return true;+  auto ids = proto::decode_ids(bytes_of(frame.payload),+                               MAX_CHUNKS_PER_REQUEST);+  if (!ids) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+                      "bad chunk list");+    return true;+  }+  blake3_hasher hasher;+  blake3_hasher_init(&hasher);+  bool failed = false;+  for (const auto &id : *ids) {+    const auto loc = session.store.find(id);+    if (!loc || loc->kind != TYPE_CHUNK) {+      failed = true;+      break;+    }+    auto body = session.store.get(*loc);+    if (!body) {+      failed = true;+      break;+    }+    if (!send_record(session, frame.request_id, hasher, id, TYPE_CHUNK,+                     bytes_of(*body))) {+      failed = true;+      break;+    }+  }+  if (failed) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,+                      "chunk not found");+  } else {+    (void)send_end(session, frame.request_id, hasher);+  }+  return !failed;+}++bool handle_have_query(Session &session, const wire::Frame &frame) {+  if (deny(session, frame.request_id, true))+    return true;+  auto ids = proto::decode_ids(bytes_of(frame.payload), 1000000);+  if (!ids) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+                      "bad HAVE_QUERY");+    return true;+  }+  std::vector<std::uint8_t> bits;+  bits.reserve(ids->size());+  for (const auto &id : *ids)+    bits.push_back(session.store.find(id).has_value() ? 1 : 0);+  const auto body = proto::encode_bitmap(bits);+  return wire::write_frame(session.stream, wire::HAVE_BITMAP,+                           frame.request_id, body);+}++bool object_exists(Session &session, const Id &id) {+  return session.store.find(id).has_value();+}++bool check_closure(Session &session, const Id &id, std::uint8_t kind) {+  auto body = session.store.read_body(id, kind);+  if (!body)+    return false;+  bool fine = true;+  if (kind == TYPE_COMMIT) {+    auto commit = decode_commit(bytes_of(*body));+    if (!commit)+      return false;+    if (!object_exists(session, commit->root_tree))+      fine = false;+    for (const auto &parent : commit->parents) {+      if (!object_exists(session, parent))+        fine = false;+    }+  } else if (kind == TYPE_TREE) {+    auto tree = decode_tree(bytes_of(*body));+    if (!tree)+      return false;+    for (const auto &entry : tree->entries) {+      if (entry.kind != KIND_SUBMODULE && !object_exists(session, entry.target))+        fine = false;+    }+  } else if (kind == TYPE_BLOB) {+    auto blob = decode_blob(bytes_of(*body));+    if (!blob)+      return false;+    for (const auto &entry : blob->entries) {+      if (!object_exists(session, entry.id))+        fine = false;+    }+  } else if (kind == TYPE_CONFLICT) {+    auto conflict = decode_conflict(bytes_of(*body));+    if (!conflict)+      return false;+    for (const auto &value : conflict->adds) {+      if (value.target && !object_exists(session, *value.target))+        fine = false;+    }+    for (const auto &value : conflict->removes) {+      if (value.target && !object_exists(session, *value.target))+        fine = false;+    }+  }+  return fine;+}++bool handle_put_records(Session &session, const wire::Frame &frame) {+  if (deny(session, frame.request_id, true))+    return true;+  Writer writer;+  blake3_hasher hasher;+  blake3_hasher_init(&hasher);+  bool failed = false;+  std::vector<Id> accepted;++  for (;;) {+    auto frame_opt = wire::read_frame(session.stream);+    if (!frame_opt) {+      failed = true;+      break;+    }+    const auto &incoming = *frame_opt;+    if (incoming.kind == wire::END) {+      std::array<std::uint8_t, 32> digest{};+      blake3_hasher_finalize(&hasher, digest.data(), digest.size());+      if (incoming.payload.size() != digest.size() ||+          std::memcmp(incoming.payload.data(), digest.data(), digest.size()) !=+              0) {+        failed = true;+      }+      break;+    }+    if (incoming.kind != wire::RECORDS) {+      failed = true;+      break;+    }+    blake3_hasher_update(&hasher, incoming.payload.data(),+                         incoming.payload.size());+    auto record = wire::parse_record(bytes_of(incoming.payload));+    if (!record) {+      failed = true;+      break;+    }+    const Id computed = object_id(record->kind, bytes_of(record->body));+    if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {+      failed = true;+      break;+    }+    writer.add_known(record->kind, record->id, std::move(record->body));+    accepted.push_back(record->id);+  }++  if (failed) {+    wire::write_error(session.stream, frame.request_id,+                      wire::ERR_HASH_MISMATCH, "record rejected");+    return true;+  }+  if (!writer.finish(session.repo_root)) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+                      "pack write failed");+    return true;+  }+  open_session_store(session);+  session.store.refresh(session.repo_root);++  bool closure_ok = true;+  for (const auto &id : accepted) {+    const auto loc = session.store.find(id);+    if (!loc)+      continue;+    if (!check_closure(session, id, loc->kind)) {+      closure_ok = false;+      break;+    }+  }+  if (!closure_ok) {+    wire::write_error(session.stream, frame.request_id,+                      wire::ERR_MISSING_CLOSURE, "missing object closure");+    return true;+  }+  return wire::write_frame(session.stream, wire::END, frame.request_id,+                           Bytes{});+}++std::optional<Id> first_target(const TargetSet &targets) {+  if (targets.adds.empty())+    return std::nullopt;+  return targets.adds.front();+}++bool ref_matches(const View &view, std::string_view name,+                 const std::optional<Id> &expected) {+  std::optional<Id> current;+  if (auto index = find_bookmark(view, name)) {+    current = first_target(view.bookmarks[*index].targets);+  } else if (auto index = find_tag(view, name)) {+    current = view.tags[*index].target;+  }+  if (!expected)+    return !current.has_value();+  if (!current)+    return false;+  return std::memcmp(current->data(), expected->data(), ID_LEN) == 0;+}++void apply_ref(View &view, std::string_view name,+               const std::optional<Id> &target) {+  if (!target) {+    if (auto index = find_bookmark(view, name))+      view.bookmarks.erase(view.bookmarks.begin() ++                           static_cast<std::ptrdiff_t>(*index));+    if (auto index = find_tag(view, name))+      view.tags.erase(view.tags.begin() ++                      static_cast<std::ptrdiff_t>(*index));+    return;+  }+  if (auto index = find_bookmark(view, name)) {+    auto &bookmark = view.bookmarks[*index];+    bookmark.targets.adds = {*target};+    bookmark.targets.removes.clear();+    return;+  }+  if (auto index = find_tag(view, name)) {+    view.tags[*index].target = *target;+    return;+  }+  Bookmark bookmark;+  bookmark.name = std::string(name);+  bookmark.targets.adds = {*target};+  view.bookmarks.push_back(std::move(bookmark));+}++bool handle_update_refs(Session &session, const wire::Frame &frame) {+  if (deny(session, frame.request_id, true))+    return true;+  auto updates = proto::decode_update_refs(bytes_of(frame.payload));+  if (!updates) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+                      "bad UPDATE_REFS");+    return true;+  }+  auto tx = Txn::begin(session.repo_root, session.store);+  if (!tx) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+                      "cannot update refs");+    return true;+  }+  for (const auto &update : *updates) {+    if (!ref_matches(tx->view(), update.name, update.expected)) {+      wire::write_error(session.stream, frame.request_id,+                        wire::ERR_REF_CONFLICT, "ref changed");+      return true;+    }+  }+  for (const auto &update : *updates)+    apply_ref(tx->view(), update.name, update.target);+  rebuild_heads(tx->view());+  const auto status = tx->finish("remote push");+  if (!status) {+    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+                      "commit failed");+    return true;+  }+  session.store.refresh(session.repo_root);+  const std::string line = std::to_string(unix_now_millis()) + " " ++                           base32_text(bytes_of(session.fingerprint)) ++                           " update-refs\n";+  log_line(session, line);+  return wire::write_simple(session.stream, wire::UPDATE_REFS_OK,+                            frame.request_id);+}++bool dispatch(Session &session, const wire::Frame &frame) {+  if (frame.kind == wire::HELLO)+    return handle_hello(session, frame, !session.root.empty());+  if (frame.kind == wire::AUTH)+    return handle_auth(session, frame);+  if (frame.kind == wire::WHOAMI)+    return handle_whoami(session, frame);+  if (!session.repo_present) {+    wire::write_error(session.stream, frame.request_id,+                      wire::ERR_UNAUTHENTICATED, "authentication required");+    return true;+  }+  if (frame.kind == wire::LIST_REFS)+    return handle_list_refs(session, frame);+  if (frame.kind == wire::NEGOTIATE)+    return handle_negotiate(session, frame);+  if (frame.kind == wire::FETCH_SKELETON)+    return handle_fetch(session, frame);+  if (frame.kind == wire::GET_CHUNKS)+    return handle_get_chunks(session, frame);+  if (frame.kind == wire::HAVE_QUERY)+    return handle_have_query(session, frame);+  if (frame.kind == wire::PUT_RECORDS)+    return handle_put_records(session, frame);+  if (frame.kind == wire::UPDATE_REFS)+    return handle_update_refs(session, frame);+  wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+                    "unknown request");+  return true;+}++void run_session(net::Stream stream, std::optional<fs::path> fixed,+                 std::optional<fs::path> root, std::string binding) {+  Session session;+  session.stream = std::move(stream);+  session.binding = std::move(binding);+  if (root)+    session.root = *root;+  if (fixed) {+    session.repo_root = *fixed;+    session.repo_present = true;+    session.access = auth::load_access(session.repo_root);+    if (session.access.valid)+      open_session_store(session);+  }+  while (!session.closing) {+    auto frame = wire::read_frame(session.stream);+    if (!frame)+      break;+    const bool keep = dispatch(session, *frame);+    if (!keep)+      break;+  }+  log_outcome(session, "close");+  session.stream.close();+}++std::optional<int> parse_port(std::string_view address) {+  const auto colon = address.rfind(':');+  if (colon == std::string_view::npos || colon + 1 >= address.size())+    return std::nullopt;+  int port = 0;+  for (char c : address.substr(colon + 1)) {+    if (c < '0' || c > '9')+      return std::nullopt;+    port = port * 10 + (c - '0');+    if (port > 65535)+      return std::nullopt;+  }+  return port;+}++} // namespace++int serve_stdio(const fs::path &repo) {+  run_session(net::Stream::stdio_stream(), repo, std::nullopt, {});+  return 0;+}++int serve_listen(std::string_view address, const fs::path &root,+                 std::string_view cert_path, std::string_view key_path) {+  net::ignore_sigpipe();+  auto port = parse_port(address);+  if (!port) {+    error_prefix();+    std::cout << "invalid listen address\n";+    return 1;+  }+  void *ctx = net::tls_server_ctx(cert_path, key_path);+  if (!ctx) {+    error_prefix();+    std::cout << "cannot load TLS certificate or key\n";+    return 1;+  }+  const net::Socket listener = net::tcp_listen(*port);+  if (listener == net::INVALID_SOCKET_VALUE) {+    error_prefix();+    std::cout << "cannot listen on port " << *port << "\n";+    net::tls_ctx_free(ctx);+    return 1;+  }+  info_prefix();+  std::cout << "listening on " << address << "\n";+  for (;;) {+    auto accepted = net::tcp_accept(listener);+    if (!accepted)+      break;+    void *ssl = net::tls_accept(ctx, *accepted);+    if (!ssl) {+      net::close_socket(*accepted);+      continue;+    }+    std::array<std::uint8_t, 32> exported{};+    std::string binding;+    if (net::tls_exporter(ssl, exported.data(), exported.size())) {+      binding.assign(reinterpret_cast<const char *>(exported.data()),+                     exported.size());+    }+    run_session(net::Stream::tls_stream(*accepted, ssl), std::nullopt, root,+                std::move(binding));+  }+  net::close_socket(listener);+  net::tls_ctx_free(ctx);+  return 0;+}++} // namespace vn::server--- /dev/null+++ b/veins-cpprewrite/src/server.h@@ -0,0 +1,13 @@+#pragma once++#include "common.h"++#include <string_view>++namespace vn::server {++int serve_stdio(const fs::path &repo);+int serve_listen(std::string_view address, const fs::path &root,+                 std::string_view cert_path, std::string_view key_path);++} // namespace vn::server--- a/veins-cpprewrite/src/store.cpp+++ b/veins-cpprewrite/src/store.cpp@@ -10,6 +10,14 @@ #include <zstd.h>  namespace vn {++namespace {+PromisorFetcher promisor_fetcher;+} // namespace++void set_promisor_fetcher(PromisorFetcher fetcher) {+  promisor_fetcher = std::move(fetcher);+}  // --------------------------------------------------------------------------- // Layout@@ -559,6 +567,7 @@  Store Store::open_all(const fs::path &root) {   Store store;+  store.root_ = root;   for (const auto &name : list_directory(packs_dir(root))) {     if (name.size() <= 6)       continue;@@ -640,7 +649,13 @@  std::optional<std::vector<std::uint8_t>> Store::read_body(const Id &id, std::uint8_t expected) {-  const auto loc = find(id);+  auto loc = find(id);+  if (!loc && expected == TYPE_CHUNK && promisor_fetcher && !root_.empty()) {+    if (promisor_fetcher(root_, id)) {+      refresh(root_);+      loc = find(id);+    }+  }   if (!loc || loc->kind != expected)     return std::nullopt;   auto body = get(*loc);--- a/veins-cpprewrite/src/store.h+++ b/veins-cpprewrite/src/store.h@@ -2,6 +2,7 @@  #include "object.h" +#include <functional> #include <memory> #include <optional> #include <set>@@ -9,6 +10,11 @@ #include <vector>  namespace vn {++// Called when a promised chunk is missing. Returns true when the object was+// fetched and written to a pack.+using PromisorFetcher = std::function<bool(const fs::path &, const Id &)>;+void set_promisor_fetcher(PromisorFetcher fetcher);  // --------------------------------------------------------------------------- // Repository layout@@ -124,11 +130,13 @@    std::vector<StoreHandle> &handles() { return handles_; }   const std::vector<StoreHandle> &handles() const { return handles_; }+  const fs::path &root() const { return root_; }   void preload();  private:   bool ensure_index(StoreHandle &handle);   bool ensure_pack(StoreHandle &handle);+  fs::path root_;   std::vector<StoreHandle> handles_; }; --- /dev/null+++ b/veins-cpprewrite/src/wire.cpp@@ -0,0 +1,185 @@+#include "wire.h"++#include <zstd.h>++#include <array>+#include <cstring>++namespace vn::wire {++namespace {++bool read_exact(net::Stream &stream, std::uint8_t *out, std::size_t count) {+  std::size_t got = 0;+  while (got < count) {+    const std::int64_t n = stream.read(out + got, count - got);+    if (n <= 0)+      return false;+    got += static_cast<std::size_t>(n);+  }+  return true;+}++} // namespace++std::optional<Frame> read_frame(net::Stream &stream) {+  std::array<std::uint8_t, 4> head{};+  if (!read_exact(stream, head.data(), head.size()))+    return std::nullopt;+  const std::uint32_t length = (static_cast<std::uint32_t>(head[0]) << 24) |+                               (static_cast<std::uint32_t>(head[1]) << 16) |+                               (static_cast<std::uint32_t>(head[2]) << 8) |+                               static_cast<std::uint32_t>(head[3]);+  if (length < 5 || length > MAX_FRAME)+    return std::nullopt;+  std::vector<std::uint8_t> body(length);+  if (!read_exact(stream, body.data(), body.size()))+    return std::nullopt;+  Frame frame;+  frame.kind = body[0];+  frame.request_id = (static_cast<std::uint32_t>(body[1]) << 24) |+                     (static_cast<std::uint32_t>(body[2]) << 16) |+                     (static_cast<std::uint32_t>(body[3]) << 8) |+                     static_cast<std::uint32_t>(body[4]);+  frame.payload.assign(body.begin() + 5, body.end());+  return frame;+}++bool write_frame(net::Stream &stream, std::uint8_t kind,+                 std::uint32_t request_id, Bytes payload) {+  if (payload.size() > MAX_FRAME - 5)+    return false;+  const std::uint32_t length = static_cast<std::uint32_t>(5 + payload.size());+  std::array<std::uint8_t, 9> head{};+  head[0] = static_cast<std::uint8_t>((length >> 24) & 255u);+  head[1] = static_cast<std::uint8_t>((length >> 16) & 255u);+  head[2] = static_cast<std::uint8_t>((length >> 8) & 255u);+  head[3] = static_cast<std::uint8_t>(length & 255u);+  head[4] = kind;+  head[5] = static_cast<std::uint8_t>((request_id >> 24) & 255u);+  head[6] = static_cast<std::uint8_t>((request_id >> 16) & 255u);+  head[7] = static_cast<std::uint8_t>((request_id >> 8) & 255u);+  head[8] = static_cast<std::uint8_t>(request_id & 255u);+  if (!stream.write_all(Bytes(head.data(), head.size())))+    return false;+  return payload.empty() || stream.write_all(payload);+}++bool write_simple(net::Stream &stream, std::uint8_t kind,+                  std::uint32_t request_id) {+  return write_frame(stream, kind, request_id, Bytes{});+}++bool write_error(net::Stream &stream, std::uint32_t request_id,+                 std::uint8_t code, std::string_view message) {+  ByteWriter writer(64);+  writer.u8(code);+  writer.length_prefixed(message);+  return write_frame(stream, ERROR, request_id, writer.view());+}++std::uint8_t read_error(Bytes payload) {+  if (payload.empty())+    return ERR_INTERNAL;+  return payload[0];+}++std::string error_message(Bytes payload) {+  if (payload.size() < 2)+    return {};+  Reader reader(payload.subspan(1));+  auto value = reader.bytes(4096);+  if (!value)+    return {};+  return std::string(str_of(*value));+}++std::string_view error_code_name(std::uint8_t code) {+  switch (code) {+  case ERR_UNSUPPORTED_VERSION:+    return "unsupported protocol version";+  case ERR_BAD_FRAME:+    return "bad frame";+  case ERR_NOT_FOUND:+    return "object not found";+  case ERR_HASH_MISMATCH:+    return "hash mismatch";+  case ERR_NON_CANONICAL:+    return "non-canonical object";+  case ERR_MISSING_CLOSURE:+    return "missing object closure";+  case ERR_REF_CONFLICT:+    return "ref conflict";+  case ERR_REJECTED:+    return "request rejected";+  case ERR_INTERNAL:+    return "server internal error";+  case ERR_UNAUTHENTICATED:+    return "authentication required";+  case ERR_FORBIDDEN:+    return "permission denied";+  case ERR_AUTH_FAILED:+    return "authentication failed";+  default:+    return "unknown server error";+  }+}++std::optional<IncomingRecord> parse_record(Bytes data) {+  if (data.size() < 35)+    return std::nullopt;+  Reader reader(data);+  const auto id = reader.id();+  if (!id)+    return std::nullopt;+  const auto kind = reader.u8();+  if (!kind)+    return std::nullopt;+  const auto compression = reader.u8();+  if (!compression)+    return std::nullopt;+  const auto raw_len = reader.varint();+  if (!raw_len)+    return std::nullopt;+  const auto stored_len = reader.varint();+  if (!stored_len)+    return std::nullopt;+  if (*raw_len == 0 || *raw_len > 64u * 1024u * 1024u ||+      *stored_len > MAX_FRAME)+    return std::nullopt;+  const auto stored = reader.raw(static_cast<std::size_t>(*stored_len));+  if (!stored)+    return std::nullopt;+  if (!reader.at_end())+    return std::nullopt;+  IncomingRecord record;+  record.id = *id;+  record.kind = *kind;+  if (*compression == 0) {+    if (stored->size() != static_cast<std::size_t>(*raw_len))+      return std::nullopt;+    record.body.assign(stored->begin(), stored->end());+    return record;+  }+  record.body.resize(static_cast<std::size_t>(*raw_len));+  const std::size_t result =+      ZSTD_decompress(record.body.data(), record.body.size(), stored->data(),+                      stored->size());+  if (ZSTD_isError(result) || result != record.body.size())+    return std::nullopt;+  return record;+}++std::vector<std::uint8_t> make_record(const Id &id, std::uint8_t kind,+                                      Bytes body) {+  ByteWriter writer(body.size() + 64);+  writer.raw(Bytes(id.data(), id.size()));+  writer.u8(kind);+  writer.u8(0);+  writer.varint(body.size());+  writer.varint(body.size());+  writer.raw(body);+  return writer.take();+}++} // namespace vn::wire--- /dev/null+++ b/veins-cpprewrite/src/wire.h@@ -0,0 +1,80 @@+#pragma once++#include "net.h"++#include <cstdint>+#include <optional>+#include <string>+#include <vector>++namespace vn::wire {++constexpr std::size_t MAX_FRAME = 16u * 1024u * 1024u;++enum Kind : std::uint8_t {+  HELLO = 1,+  HELLO_OK = 2,+  AUTH = 3,+  AUTH_OK = 4,+  WHOAMI = 5,+  WHOAMI_OK = 6,+  LIST_REFS = 7,+  REFS = 8,+  NEGOTIATE = 9,+  NEGOTIATE_OK = 10,+  FETCH_SKELETON = 11,+  GET_CHUNKS = 12,+  HAVE_QUERY = 13,+  HAVE_BITMAP = 14,+  PUT_RECORDS = 15,+  UPDATE_REFS = 16,+  UPDATE_REFS_OK = 17,+  RECORDS = 18,+  END = 19,+  ERROR = 20,+};++enum ErrorCode : std::uint8_t {+  ERR_UNSUPPORTED_VERSION = 1,+  ERR_BAD_FRAME = 2,+  ERR_NOT_FOUND = 3,+  ERR_HASH_MISMATCH = 4,+  ERR_NON_CANONICAL = 5,+  ERR_MISSING_CLOSURE = 6,+  ERR_REF_CONFLICT = 7,+  ERR_REJECTED = 8,+  ERR_INTERNAL = 9,+  ERR_UNAUTHENTICATED = 10,+  ERR_FORBIDDEN = 11,+  ERR_AUTH_FAILED = 12,+};++struct Frame {+  std::uint8_t kind = 0;+  std::uint32_t request_id = 0;+  std::vector<std::uint8_t> payload;+};++std::optional<Frame> read_frame(net::Stream &stream);+bool write_frame(net::Stream &stream, std::uint8_t kind,+                 std::uint32_t request_id, Bytes payload);+bool write_simple(net::Stream &stream, std::uint8_t kind,+                  std::uint32_t request_id);+bool write_error(net::Stream &stream, std::uint32_t request_id,+                 std::uint8_t code, std::string_view message);++std::uint8_t read_error(Bytes payload);+std::string error_message(Bytes payload);+std::string_view error_code_name(std::uint8_t code);++// Encode/decode the record layout shared by packs and RECORDS frames.+struct IncomingRecord {+  Id id{};+  std::uint8_t kind = 0;+  std::vector<std::uint8_t> body;+};+std::optional<IncomingRecord> parse_record(Bytes data);+std::vector<std::uint8_t> make_record(const Id &id, std::uint8_t kind,+                                      Bytes body);++} // namespace vn::wire