This commit is contained in:
Kieran 2023-11-28 15:03:21 +00:00
commit ac85adbca4
Signed by: Kieran
GPG Key ID: DE71CEB3925BE941
16 changed files with 25108 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
build/

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "uWebSockets"]
path = uWebSockets
url = git@github.com:uNetworking/uWebSockets.git

17
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,17 @@
{
"configurations": [
{
"name": "Debug",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/relay_middleware",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build",
"environment": [],
"externalConsole": false,
"MIMode": "lldb"
}
],
"version": "2.0.0"
}

89
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,89 @@
{
"files.associations": {
"libusockets.h": "c",
"internal.h": "c",
"bsd.h": "c",
"string_view": "cpp",
"__bit_reference": "cpp",
"__bits": "cpp",
"__config": "cpp",
"__debug": "cpp",
"__errc": "cpp",
"__hash_table": "cpp",
"__locale": "cpp",
"__mutex_base": "cpp",
"__node_handle": "cpp",
"__split_buffer": "cpp",
"__threading_support": "cpp",
"__tree": "cpp",
"__tuple": "cpp",
"__verbose_abort": "cpp",
"any": "cpp",
"array": "cpp",
"atomic": "cpp",
"bit": "cpp",
"bitset": "cpp",
"cctype": "cpp",
"charconv": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"complex": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"deque": "cpp",
"exception": "cpp",
"forward_list": "cpp",
"initializer_list": "cpp",
"iomanip": "cpp",
"ios": "cpp",
"iosfwd": "cpp",
"iostream": "cpp",
"istream": "cpp",
"limits": "cpp",
"list": "cpp",
"locale": "cpp",
"map": "cpp",
"memory": "cpp",
"mutex": "cpp",
"new": "cpp",
"optional": "cpp",
"ostream": "cpp",
"ratio": "cpp",
"set": "cpp",
"span": "cpp",
"sstream": "cpp",
"stack": "cpp",
"stdexcept": "cpp",
"streambuf": "cpp",
"string": "cpp",
"system_error": "cpp",
"thread": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"typeinfo": "cpp",
"unordered_map": "cpp",
"unordered_set": "cpp",
"valarray": "cpp",
"variant": "cpp",
"vector": "cpp",
"__nullptr": "cpp",
"__string": "cpp",
"chrono": "cpp",
"compare": "cpp",
"concepts": "cpp",
"numeric": "cpp",
"ranges": "cpp",
"algorithm": "cpp",
"functional": "cpp",
"iterator": "cpp",
"memory_resource": "cpp",
"queue": "cpp"
}
}

26
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: clang build active file",
"command": "/opt/homebrew/opt/llvm/bin/clang",
"args": [
"-fcolor-diagnostics",
"-fansi-escape-codes",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}

63
CMakeLists.txt Normal file
View File

@ -0,0 +1,63 @@
cmake_minimum_required(VERSION 3.5)
project(relay_middleware VERSION 0.1.0)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_LOWER)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(relay_middleware
src/main.cpp
)
target_include_directories(relay_middleware PUBLIC "include" "uWebSockets/src" "uWebSockets/uSockets/src")
add_library(uWs STATIC
uWebSockets/uSockets/src/udp.c
uWebSockets/uSockets/src/socket.c
uWebSockets/uSockets/src/quic.c
uWebSockets/uSockets/src/loop.c
uWebSockets/uSockets/src/context.c
uWebSockets/uSockets/src/bsd.c
uWebSockets/uSockets/src/crypto/openssl.c
uWebSockets/uSockets/src/crypto/sni_tree.cpp
uWebSockets/uSockets/src/eventing/asio.cpp
uWebSockets/uSockets/src/eventing/epoll_kqueue.c
uWebSockets/uSockets/src/eventing/gcd.c
uWebSockets/uSockets/src/eventing/libuv.c
)
target_include_directories(uWs PRIVATE "uWebSockets/src" "uWebSockets/uSockets/src" "/opt/homebrew/opt/openssl@3.0/include")
target_compile_definitions(uWs PRIVATE LIBUS_USE_OPENSSL)
find_library(LIBSSL_LIB ssl)
find_library(LIBCRYPTO_LIB crypto)
target_link_libraries(uWs PRIVATE z ${LIBCRYPTO_LIB} ${LIBSSL_LIB})
if (${CMAKE_CXX_COMPILER_ID} STREQUAL GNU OR ${CMAKE_CXX_COMPILER_ID} STREQUAL AppleClang)
target_link_libraries(relay_middleware PRIVATE uWs)
elseif (${CMAKE_CXX_COMPILER_ID} STREQUAL MSVC)
target_include_directories(relay_middleware PUBLIC ${VCPKG_INCLUDE_DIR})
target_link_directories(relay_middleware PRIVATE ${VCPKG_LIB_DIR})
endif()
install(TARGETS relay_middleware RUNTIME DESTINATION bin)
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
set(CPACK_PACKAGE_DESCRIPTION "Nostr Relay middleware")
set(CPACK_PACKAGE_HOMEPAGE_URL "https://git.v0l.io/Kieran/relay_middleware")
set(CPACK_PACKAGE_CONTACT "v0l <relay_middleware@v0l.io>")
set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/LICENSE")
if(${CMAKE_CXX_COMPILER_ID} STREQUAL AppleClang)
set(CPACK_GENERATOR "DragNDrop")
else()
set(CPACK_GENERATOR "DEB" "TGZ" "TXZ")
endif()
set(CPACK_PACKAGE_CHECKSUM SHA256)
set(CPACK_STRIP_FILES true)
set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "amd64")
set(CPACK_DEBIAN_PACKAGE_SECTION "other")
set(CPACK_DEBIAN_COMPRESSION_TYPE "xz")
include(CPack)

0
LICENSE Normal file
View File

19
include/event.hpp Normal file
View File

@ -0,0 +1,19 @@
#pragma once
#include "json.hpp"
namespace relay_middelware::nostr {
class NostrEvent {
public:
const std::string id;
const std::string pubkey;
const int kind;
const long created_at;
const std::vector<std::vector<std::string>> tags;
const std::string sig;
static auto from_json(const nlohmann::json &data) -> NostrEvent {
}
};
}

87
include/filter.hpp Normal file
View File

@ -0,0 +1,87 @@
#pragma once
#include <vector>
#include <optional>
#include <map>
#include "json.hpp"
namespace relay_middleware::nostr
{
class NostrFilter
{
public:
const std::optional<std::vector<std::string>> ids;
const std::optional<std::vector<std::string>> authors;
const std::optional<std::vector<int>> kinds;
const std::map<std::string, std::vector<std::string>> tags;
const std::optional<long> since;
const std::optional<long> until;
const std::optional<int> limit;
const std::optional<std::string> search;
static auto from_json(const nlohmann::json &json) -> NostrFilter
{
if (!json.is_object())
{
throw std::runtime_error("Filter json must be object");
}
auto ids = json.contains("ids") && json["ids"].is_array() ? std::optional<std::vector<std::string>>{json["ids"].get<std::vector<std::string>>()} : std::nullopt;
auto authors = json.contains("authors") && json["authors"].is_array() ? std::optional<std::vector<std::string>>{json["authors"].get<std::vector<std::string>>()} : std::nullopt;
auto kinds = json.contains("kinds") && json["kinds"].is_array() ? std::optional<std::vector<int>>{json["kinds"].get<std::vector<int>>()} : std::nullopt;
auto since = json.contains("since") && json["since"].is_number() ? std::optional<long>{json["since"].get<long>()} : std::nullopt;
auto until = json.contains("until") && json["until"].is_number() ? std::optional<long>{json["until"].get<long>()} : std::nullopt;
auto limit = json.contains("limit") && json["limit"].is_number() ? std::optional<long>{json["limit"].get<long>()} : std::nullopt;
auto search = json.contains("search") && json["search"].is_string() ? std::optional<std::string>(json["search"].get<std::string>()) : std::nullopt;
auto tags = std::map<std::string, std::vector<std::string>>();
for (auto &[k, v] : json.items())
{
if (v.is_array() && k.starts_with('#'))
{
tags.emplace(k, v.get<std::vector<std::string>>());
}
}
return NostrFilter{ids, authors, kinds, tags, since, until, limit, search};
}
auto to_json() const -> nlohmann::json
{
auto ret = nlohmann::json();
if (ids.has_value())
{
ret["ids"] = ids.value();
}
if (authors.has_value())
{
ret["authors"] = authors.value();
}
if (kinds.has_value())
{
ret["kinds"] = kinds.value();
}
for (const auto &[k, v] : tags)
{
ret[k] = v;
}
if (since.has_value())
{
ret["since"] = since.value();
}
if (until.has_value())
{
ret["until"] = until.value();
}
if (limit.has_value())
{
ret["limit"] = limit.value();
}
if (search.has_value())
{
ret["search"] = search.value();
}
return ret;
}
};
}

24596
include/json.hpp Normal file

File diff suppressed because it is too large Load Diff

21
include/proxy.hpp Normal file
View File

@ -0,0 +1,21 @@
#pragma once
#include <queue>
#include "request.hpp"
using namespace relay_middleware::nostr;
namespace relay_middleware::proxy
{
class RelayProxy
{
private:
std::queue<const NostrRequest> req_queue;
public:
auto push(const NostrRequest &&req) -> void
{
req_queue.push(std::move(req));
}
};
}

50
include/request.hpp Normal file
View File

@ -0,0 +1,50 @@
#pragma once
#include "json.hpp"
#include "filter.hpp"
namespace relay_middleware::nostr
{
class NostrRequest
{
public:
const std::string id;
const std::vector<NostrFilter> filters;
static auto from_json(const nlohmann::json &data) -> NostrRequest
{
if (!data.is_array())
{
throw std::runtime_error("Data must be array");
}
if (data[0].get<std::string>() != "REQ")
{
throw std::runtime_error("Not REQ command");
}
auto filters = std::vector<NostrFilter>();
auto f = data.begin();
f += 2;
for (; f != data.end(); f++)
{
auto fx = NostrFilter::from_json(*f);
filters.push_back(fx);
}
return NostrRequest{
data[1].get<std::string>(),
filters,
};
}
auto to_json() const -> nlohmann::json
{
auto ret = nlohmann::json();
ret[0] = "REQ";
ret[1] = id;
for (const auto &x : filters)
{
ret.push_back(x.to_json());
}
return ret;
}
};
}

38
include/socket.hpp Normal file
View File

@ -0,0 +1,38 @@
#pragma once
#include <sstream>
#include <WebSocket.h>
#include "state.h"
namespace relay_middleware::nostr
{
class NostrSocket
{
private:
uWS::WebSocket<false, true, StateObj> *ws;
public:
NostrSocket(uWS::WebSocket<false, true, StateObj> *ws)
{
this->ws = ws;
}
auto eose(const std::string &id) const -> void
{
auto msg = "[\"EOSE\",\"" + id + "\"]";
ws->send(msg, uWS::OpCode::TEXT);
}
auto notice(const std::string &msg) const -> void
{
auto notice = "[\"NOTICE\",\"" + msg + "\"]";
ws->send(notice, uWS::OpCode::TEXT);
}
auto ok(const std::string &id, bool accepted, const std::string &reason) const -> void
{
auto msg = "[\"OK\",\"" + id + "\"," + (accepted ? "true" : "false") + ",\"" + reason + "\"]";
ws->send(msg, uWS::OpCode::TEXT);
}
};
}

22
include/state.h Normal file
View File

@ -0,0 +1,22 @@
#ifndef __STATE_HPP
#define __STATE_HPP
namespace relay_middleware
{
namespace nostr
{
class NostrSocket;
}
namespace proxy
{
class RelayProxy;
}
}
typedef struct StateObj
{
relay_middleware::proxy::RelayProxy *proxy;
relay_middleware::nostr::NostrSocket *socket;
} StateObj;
#endif

75
src/main.cpp Normal file
View File

@ -0,0 +1,75 @@
#include <sstream>
#include "App.h"
#include "json.hpp"
#include "request.hpp"
#include "proxy.hpp"
#include "socket.hpp"
#include "state.h"
int main()
{
uWS::App().ws<StateObj>("/", {.compression = uWS::SHARED_COMPRESSOR,
.maxPayloadLength = 16 * 1024 * 1024,
.idleTimeout = 16,
.maxBackpressure = 1 * 1024 * 1024,
.closeOnBackpressureLimit = false,
.resetIdleTimeoutOnSend = false,
.sendPingsAutomatically = true,
.upgrade = nullptr,
.open = [](auto *ws)
{
StateObj *state = ws->getUserData();
std::cout << "New connection" << std::endl;
state->socket = new relay_middleware::nostr::NostrSocket(ws);
state->proxy = new relay_middleware::proxy::RelayProxy(); },
.close = [](auto *ws, auto code, auto msg)
{
StateObj *state = ws->getUserData();
delete state->proxy;
delete state->socket; },
.message = [](auto *ws, std::string_view message, uWS::OpCode opCode)
{
std::cout << "In: " << message << std::endl;
if (opCode == uWS::OpCode::TEXT)
{
StateObj *state = ws->getUserData();
try {
auto j = nlohmann::json::parse(message);
if (!j.is_array())
{
return;
}
auto q = j[0].get<std::string>();
if (q == "REQ")
{
auto filter = NostrRequest::from_json(j);
std::cout << "Out: " << filter.to_json() << std::endl;
state->socket->eose(filter.id);
}
else if (q == "EVENT")
{
auto id = j[1]["id"].get<std::string>();
// do something
state->socket->ok(id, false, "not implemented");
} else if (q == "CLOSE") {
// nothing
} else {
state->socket->notice("Command not supported");
}
}catch (const std::exception& e) {
state->socket->notice("Unknown error: " + std::string(e.what()));
}
} }})
.listen(3334, [](auto *listen_socket)
{
if (listen_socket) {
std::cout << "Listening on port " << 3334 << std::endl;
} })
.run();
std::cout << "Failed to listen on port 3334" << std::endl;
}

1
uWebSockets Submodule

@ -0,0 +1 @@
Subproject commit bc2815d95b6ff4cad0973226d0058eadaaec99ad