From 9330b01c28aebc865a3c0a51df8730196cb4152e Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 23 May 2026 04:50:26 +0530 Subject: Phase 6a-6d: Consolidate and clean up 6a: Delete dead standalone tollgate_core/ (12 files, never compiled) 6b: Rewrite dns_server.c as thin shim to component's tollgate_core_dns - Fix component DNS to bind to AP IP instead of INADDR_ANY 6c: Rewrite stratum_proxy.c as thin shim with struct cast to component types 6d: Move sandbox logic into component's tollgate_core_firewall - Add tollgate_core_fw_set_sandbox_ports/set_sandbox_mint_access - Add is_sandbox_allowed() to component's ip4_canforward_filter - Clean main/firewall.c to delegate filter to component - Remove redundant DNS auth double-calls from main firewall Add ROADMAP.md with full extraction plan and checklists All 21 unit tests pass. ESP-IDF build passes. --- ROADMAP.md | 262 ++++++++++++ components/tollgate_core/src/tollgate_core_dns.c | 2 +- .../tollgate_core/src/tollgate_core_firewall.c | 47 +++ .../tollgate_core/src/tollgate_core_firewall.h | 2 + main/dns_server.c | 304 +------------- main/firewall.c | 72 +--- main/stratum_proxy.c | 145 +------ tests/unit/test_firewall_sandbox | Bin 30568 -> 111016 bytes tests/unit/test_mining_payment | Bin 28664 -> 111000 bytes tests/unit/test_session_payment_method | Bin 54680 -> 117880 bytes tests/unit/test_stratum_proxy | Bin 40784 -> 113304 bytes tollgate_core/CMakeLists.txt | 28 -- tollgate_core/include/tollgate_core.h | 90 ---- tollgate_core/include/tollgate_platform.h | 68 --- tollgate_core/src/tollgate_cashu.c | 253 ----------- tollgate_core/src/tollgate_cashu.h | 40 -- tollgate_core/src/tollgate_core.c | 466 --------------------- tollgate_core/src/tollgate_firewall.c | 166 -------- tollgate_core/src/tollgate_firewall.h | 21 - tollgate_core/src/tollgate_mining.c | 171 -------- tollgate_core/src/tollgate_mining.h | 34 -- tollgate_core/src/tollgate_session.c | 220 ---------- tollgate_core/src/tollgate_session.h | 42 -- 23 files changed, 329 insertions(+), 2104 deletions(-) create mode 100644 ROADMAP.md delete mode 100644 tollgate_core/CMakeLists.txt delete mode 100644 tollgate_core/include/tollgate_core.h delete mode 100644 tollgate_core/include/tollgate_platform.h delete mode 100644 tollgate_core/src/tollgate_cashu.c delete mode 100644 tollgate_core/src/tollgate_cashu.h delete mode 100644 tollgate_core/src/tollgate_core.c delete mode 100644 tollgate_core/src/tollgate_firewall.c delete mode 100644 tollgate_core/src/tollgate_firewall.h delete mode 100644 tollgate_core/src/tollgate_mining.c delete mode 100644 tollgate_core/src/tollgate_mining.h delete mode 100644 tollgate_core/src/tollgate_session.c delete mode 100644 tollgate_core/src/tollgate_session.h diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..b4fe16b --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,262 @@ +# TollGate Core Extraction Roadmap + +**Branch:** `feature/tollgate-core-v2` +**Start commit:** `851801f` (Phase 5 complete, hardware-verified) +**Goal:** Extract all portable TollGate business logic into `components/tollgate_core/` for reuse in NerdQAxePlus and other ESP32 firmware. + +## Testing Protocol + +After **every** step: + +1. `make test-unit` -- all 21+ unit tests must pass +2. `idf.py build` -- ESP-IDF build must succeed +3. After multi-step phases: flash Board A + `pytest tests/test_smoke.py --board=a` + +--- + +## Phase 6: Consolidate & Clean Up + +### 6a. Delete standalone `tollgate_core/` + +Dead code -- nothing in the build references it. The component version is what's compiled. + +- [ ] `git rm -r tollgate_core/` +- [ ] Verify nothing references it: `grep -r "tollgate_core/" main/ components/ tests/` +- [ ] Test: `make test-unit` + `idf.py build` + +### 6b. Eliminate `dns_server.c` duplication + +`main/dns_server.c` (316 lines) duplicates `components/tollgate_core/src/tollgate_core_dns.c`. + +- [ ] Rewrite `main/dns_server.c` as thin shim: `dns_server_*()` calls `tollgate_core_dns_*()` +- [ ] Update `main/dns_server.h` to keep original function signatures +- [ ] Move `dns_server_set_client_authenticated()` notification to component's internal DNS +- [ ] Add unit test for DNS shim if not covered by existing `test_firewall_sandbox` +- [ ] Test: `make test-unit` + `idf.py build` + flash + pytest smoke + +### 6c. Eliminate `stratum_proxy.c` duplication + +`main/stratum_proxy.c` (160 lines) duplicates `components/tollgate_core/src/tollgate_core_stratum_proxy.c`. + +- [ ] Rewrite `main/stratum_proxy.c` as thin shim: `stratum_proxy_*()` -> `tollgate_core_stratum_proxy_*()` +- [ ] Update `main/stratum_proxy.h` to keep original type names for backward compat +- [ ] Test: `make test-unit` + `idf.py build` + +### 6d. Move sandbox logic into component firewall + +`main/firewall.c` has `is_sandbox_allowed()` (allows TCP to ports 80/2121/mining_port for unauth clients) -- missing from component. + +- [ ] Add `tollgate_core_fw_set_sandbox_ports()` to component's firewall API +- [ ] Add `tollgate_core_fw_is_sandbox_allowed()` to component's internal firewall +- [ ] Update component's `tollgate_core_ip4_canforward_filter` to check sandbox rules +- [ ] Update `main/firewall.c` shim to call `tollgate_core_fw_set_sandbox_ports()` in init +- [ ] Add unit test for sandbox logic with known port combinations +- [ ] Test: `make test-unit` + `idf.py build` + flash + `pytest tests/test_dns_firewall.py --board=a` + +### 6e. Break `mint_health` <-> `tollgate_api` circular dependency + +`mint_health.c` includes `tollgate_api.h` for `tls_worker_set_queue()`. `tollgate_api.c` includes `mint_health.h` for `mint_health_get_all()`. + +- [ ] Extract `QueueHandle_t tls_worker_queue` into a shared module (e.g., `tls_worker.h/c`) +- [ ] `mint_health.c` includes `tls_worker.h` instead of `tollgate_api.h` +- [ ] `tollgate_api.c` includes `tls_worker.h` to get the queue +- [ ] Test: `make test-unit` + `idf.py build` + +### 6f. Break `config.h` -> `lightning_payout.h` reverse dependency + +`config.h` includes `lightning_payout.h` for `payout_config_t` type. + +- [ ] Move `payout_config_t` typedef to `config.h` (or a shared `tollgate_types.h`) +- [ ] Remove `#include "lightning_payout.h"` from `config.h` +- [ ] Add `#include "config.h"` to `lightning_payout.c` if needed +- [ ] Test: `make test-unit` + `idf.py build` + **commit + push** + +--- + +## Phase 7: Eliminate Shim Files + +Remove thin wrappers. Consumers use component headers directly. + +### 7a. Remove `session.c` / `session.h` shim + +- [ ] Update `tollgate_api.c`: `#include "tollgate_core_session.h"` instead of `#include "session.h"` +- [ ] Update `captive_portal.c`: same +- [ ] Update any other consumers of `session.h` +- [ ] Delete `main/session.c` and `main/session.h` +- [ ] Remove from `main/CMakeLists.txt` SRCS +- [ ] Update unit test Makefile if needed +- [ ] Test: `make test-unit` + `idf.py build` + +### 7b. Remove `cashu.c` / `cashu.h` shim + +- [ ] Update `tollgate_api.c`: `#include "tollgate_core_cashu.h"` instead of `#include "cashu.h"` +- [ ] Move multi-mint logic (iterating `accepted_mints[]`) into component's `tollgate_core_cashu_is_mint_accepted()` +- [ ] Delete `main/cashu.c` and `main/cashu.h` +- [ ] Remove from `main/CMakeLists.txt` SRCS +- [ ] Test: `make test-unit` + `idf.py build` + +### 7c. Remove `mining_payment.c` / `mining_payment.h` shim + +- [ ] Update all consumers: `#include "tollgate_core_mining.h"` instead of `#include "mining_payment.h"` +- [ ] Delete `main/mining_payment.c` and `main/mining_payment.h` +- [ ] Remove from `main/CMakeLists.txt` SRCS +- [ ] Test: `make test-unit` + `idf.py build` + +### 7d. Remove `firewall.c` / `firewall.h` shim + +After 6d, firewall shim only has lwIP hook registration + DNS notification. + +- [ ] Move lwIP hook registration into `tollgate_main.c` or a new `main/esp_hooks.c` +- [ ] Update consumers to use `tollgate_core_fw_*()` directly +- [ ] Delete `main/firewall.c` and `main/firewall.h` +- [ ] Remove from `main/CMakeLists.txt` SRCS +- [ ] Test: `make test-unit` + `idf.py build` + flash + pytest smoke + DNS/firewall tests +- [ ] **Commit + push** + +--- + +## Phase 8: Extract Layer 1 into Component + +### 8a. Extract `beacon_price.c` -> `tollgate_core_beacon.c` + +Dependencies: `config`, `identity`, `esp_wifi`, `mbedtls/sha256` + +- [ ] Create `components/tollgate_core/src/tollgate_core_beacon.c/h` +- [ ] Abstract WiFi vendor IE API via `tollgate_platform_t` callbacks: `set_vendor_ie()`, `scan_start()` +- [ ] Move mint URL + npub hashing, geohash embedding, IE construction to component +- [ ] Rewrite `main/beacon_price.c` as thin ESP-specific glue calling component +- [ ] Add unit test with known IE vectors +- [ ] Test: `make test-unit` + `idf.py build` + +### 8b. Extract `market.c` -> `tollgate_core_market.c` + +Dependencies: `beacon_price`, `config`, `identity`, `esp_wifi` + +- [ ] Create `components/tollgate_core/src/tollgate_core_market.c/h` +- [ ] Abstract WiFi scan results via platform callback: `on_scan_result()` +- [ ] Move market entry table, price comparison, cheapest selection to component +- [ ] Rewrite `main/market.c` as thin glue +- [ ] Add unit test for market table operations +- [ ] Test: `make test-unit` + `idf.py build` + +### 8c. Extract `captive_portal.c` -> `tollgate_core_portal.c` + +Dependencies: `firewall`, `session`, `config`, `mining_payment`, `stratum_proxy`, `esp_http_server` + +- [ ] Create `components/tollgate_core/src/tollgate_core_portal.c/h` +- [ ] Extract template rendering logic (HTML generation, `__AP_IP__`/`__PRICE__` substitution) +- [ ] Extract captive detection URI handling (generate_204, hotspot-detect, success.txt, etc.) +- [ ] Extract payment processing flow (POST token -> decode -> validate -> grant) +- [ ] Abstract HTTP server via platform callbacks: `httpd_start()`, `register_handler()`, `send_response()` +- [ ] Keep ESP `httpd` glue in `main/captive_portal.c` (thin handler registration) +- [ ] Add unit test for template substitution + captive URI detection +- [ ] Test: `make test-unit` + `idf.py build` + flash + pytest portal tests + +### 8d. Extract `stratum_client.c` -> `tollgate_core_stratum_client.c` + +Dependencies: `stratum_proxy`, `mining_payment`, `config`, `esp_transport` + +- [ ] Create `components/tollgate_core/src/tollgate_core_stratum_client.c/h` +- [ ] Abstract TCP transport via platform callbacks +- [ ] Move Stratum V1 protocol logic (subscribe, authorize, handle mining.notify, submit share) +- [ ] Rewrite `main/stratum_client.c` as thin glue +- [ ] Add unit test for Stratum message parsing +- [ ] Test: `make test-unit` + `idf.py build` + +### 8e. Extract `mint_health.c` -> `tollgate_core_mint_health.c` + +Dependencies: `tls_worker` (after 6e), `nucula_wallet`, `esp_http_client` + +- [ ] Create `components/tollgate_core/src/tollgate_core_mint_health.c/h` +- [ ] Abstract HTTP client via platform callback: `http_get()`, `tls_worker_queue` +- [ ] Move mint probing logic, health state tracking, reachable/unreachable marking +- [ ] Rewrite `main/mint_health.c` as thin glue +- [ ] Add unit test for health state machine +- [ ] Test: `make test-unit` + `idf.py build` + +### 8f. Extract `tollgate_client.c` -> `tollgate_core_client.c` + +Dependencies: `config`, `market`, `nucula_wallet`, `esp_http_client` + +- [ ] Create `components/tollgate_core/src/tollgate_core_client.c/h` +- [ ] Abstract HTTP + wallet via platform callbacks +- [ ] Move upstream TollGate discovery, auto-pay, usage tracking, auto-renew logic +- [ ] Rewrite `main/tollgate_client.c` as thin glue +- [ ] Add unit test for client state machine (already exists: `test_tollgate_client.c`) +- [ ] Test: `make test-unit` + `idf.py build` + flash + full pytest suite +- [ ] **Commit + push** + +--- + +## Phase 9: NerdQAxePlus Integration + +### 9a. Restore miner-integration worktree + +- [ ] `git worktree add /home/c03rad0r/esp32-miner-integration feature/miner-integration` +- [ ] Or create fresh from `remotes/orangesync/feature/miner-integration` +- [ ] Verify NerdQAxePlus fork at `/home/c03rad0r/esp-miner-nerdqaxeplus/` is intact + +### 9b. Copy finalized `tollgate_core` component + +- [ ] Sync `components/tollgate_core/` from esp32-tollgate -> NerdQAxePlus `components/tollgate_core/` +- [ ] Update NerdQAxePlus `CMakeLists.txt` to depend on `tollgate_core` +- [ ] Verify `BOARD=NERDAXE TOLLGATE=1 idf.py build` succeeds + +### 9c. Implement `tollgate_platform_t` for BitAxe/BM1397 + +- [ ] Create `components/tollgate_baxe/` with BitAxe-specific platform implementation +- [ ] Implement callbacks: `get_price_sats()`, `get_mint_url()`, `spend_proofs()`, stratum config +- [ ] Wire BM1397 ASIC -> stratum proxy -> tollgate_core mining pipeline +- [ ] Wire eCash payment -> session -> internet access on BitAxe AP + +### 9d. Integrate into NerdQAxePlus UI + +- [ ] Add payment status to OLED/LCD display +- [ ] Add WiFi AP setup with SSID derived from identity +- [ ] Add Cashu token input via web portal +- [ ] Test: Flash NerdAxe Ultra + mining test + payment test + internet verification +- [ ] **Commit + push** + +--- + +## Phase 10: Publish + +### 10a. Component metadata + +- [ ] Update `idf_component.yml` with proper version, description, dependencies +- [ ] Add `README.md` to `components/tollgate_core/` with API docs +- [ ] Add `CHANGELOG.md` to component + +### 10b. CI pipeline + +- [ ] GitHub Actions or self-hosted CI: build on push, run unit tests +- [ ] Hardware-in-the-loop testing on push to develop (Board A) +- [ ] Integration test matrix: Board A + Board B + Board C + +### 10c. Publish to IDF Component Registry + +- [ ] `compote component upload` to ESP-IDF Component Registry +- [ ] Verify `idf.py add-dependency` works from a clean project +- [ ] Document usage in top-level README + +--- + +## Dependency Graph (Extraction Order) + +``` +Layer 0: dns_server, lnurl_pay, asic_miner (no main/ deps) +Layer 1: config, identity, session, cashu, mining (foundation) +Layer 2: firewall, beacon_price, lightning_payout (depends on Layer 1) +Layer 3: market, stratum_proxy, stratum_client (depends on Layer 2) +Layer 4: captive_portal, tollgate_client, mint_health (depends on Layer 3) +Layer 5: tollgate_api (depends on everything) +``` + +## Current Test Coverage + +| Type | Count | Command | +|------|-------|---------| +| Host unit tests | 21 | `make test-unit` | +| Integration tests | 17 | `TOLLGATE_IP=x make test-integration` | +| E2E tests | 3 suites | `make test-e2e` | +| Pytest (hardware) | 12 files | `pytest tests/ --board=a` | diff --git a/components/tollgate_core/src/tollgate_core_dns.c b/components/tollgate_core/src/tollgate_core_dns.c index 84322e6..c44dd31 100644 --- a/components/tollgate_core/src/tollgate_core_dns.c +++ b/components/tollgate_core/src/tollgate_core_dns.c @@ -160,7 +160,7 @@ static void dns_server_task(void *arg) struct sockaddr_in bind_addr = { .sin_family = AF_INET, .sin_port = htons(DNS_PORT), - .sin_addr.s_addr = INADDR_ANY, + .sin_addr.s_addr = s_ap_ip.addr, }; if (bind(sock, (struct sockaddr *)&bind_addr, sizeof(bind_addr)) < 0) { ESP_LOGE(TAG, "Failed to bind DNS socket"); diff --git a/components/tollgate_core/src/tollgate_core_firewall.c b/components/tollgate_core/src/tollgate_core_firewall.c index ad0697e..4f12923 100644 --- a/components/tollgate_core/src/tollgate_core_firewall.c +++ b/components/tollgate_core/src/tollgate_core_firewall.c @@ -9,12 +9,16 @@ #include "lwip/etharp.h" #include "lwip/netif.h" #include "lwip/prot/ip4.h" +#include "lwip/prot/tcp.h" +#include "lwip/prot/ip.h" #include #define MAX_CLIENTS 10 static const char *TAG = "tg_core_fw"; static esp_ip4_addr_t s_ap_ip; +static uint16_t s_mining_port = 3333; +static bool s_sandbox_mint_access = false; typedef struct { uint32_t ip; @@ -70,6 +74,46 @@ esp_err_t tollgate_core_fw_init(esp_ip4_addr_t ap_ip) return ESP_OK; } +void tollgate_core_fw_set_sandbox_ports(uint16_t mining_port) +{ + s_mining_port = mining_port; +} + +void tollgate_core_fw_set_sandbox_mint_access(bool enabled) +{ + s_sandbox_mint_access = enabled; +} + +static bool is_sandbox_allowed(struct pbuf *p) +{ + if (p->len < IP_HLEN) return false; + struct ip_hdr *iphdr = (struct ip_hdr *)p->payload; + uint32_t dest_ip_h = lwip_ntohl(iphdr->dest.addr); + uint32_t ap_ip_h = lwip_ntohl(s_ap_ip.addr); + + if (dest_ip_h == ap_ip_h) { + if (iphdr->_proto == IP_PROTO_TCP) { + uint16_t dst_port = 0; + if (p->len >= IP_HLEN + TCP_HLEN) { + struct tcp_hdr *tcphdr = (struct tcp_hdr *)((uint8_t *)p->payload + IP_HLEN); + dst_port = lwip_ntohs(tcphdr->dest); + } + if (dst_port == 80 || dst_port == 2121 || dst_port == s_mining_port) { + return true; + } + } + if (iphdr->_proto == IP_PROTO_UDP) { + return true; + } + } + + if (s_sandbox_mint_access && iphdr->_proto == IP_PROTO_TCP) { + return true; + } + + return false; +} + int tollgate_core_ip4_canforward_filter(struct pbuf *p, u32_t dest_addr_hostorder) { (void)dest_addr_hostorder; @@ -83,6 +127,9 @@ int tollgate_core_ip4_canforward_filter(struct pbuf *p, u32_t dest_addr_hostorde if (tollgate_core_fw_is_allowed(iphdr->src.addr)) { return 1; } + if (is_sandbox_allowed(p)) { + return 1; + } return 0; } diff --git a/components/tollgate_core/src/tollgate_core_firewall.h b/components/tollgate_core/src/tollgate_core_firewall.h index f06c801..7f24372 100644 --- a/components/tollgate_core/src/tollgate_core_firewall.h +++ b/components/tollgate_core/src/tollgate_core_firewall.h @@ -11,6 +11,8 @@ struct pbuf; #define TG_FW_MAX_MAC_LEN 18 esp_err_t tollgate_core_fw_init(esp_ip4_addr_t ap_ip); +void tollgate_core_fw_set_sandbox_ports(uint16_t mining_port); +void tollgate_core_fw_set_sandbox_mint_access(bool enabled); void tollgate_core_fw_grant(uint32_t client_ip); void tollgate_core_fw_revoke(uint32_t client_ip); void tollgate_core_fw_revoke_all(void); diff --git a/main/dns_server.c b/main/dns_server.c index b84a4cf..5b1bdc3 100644 --- a/main/dns_server.c +++ b/main/dns_server.c @@ -1,316 +1,22 @@ #include "dns_server.h" -#include "esp_log.h" -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "lwip/sockets.h" -#include "lwip/netdb.h" -#include -#include - -#define MAX_AUTH_IPS 10 -#define MAX_PENDING 50 -#define DNS_BUF_SIZE 512 -#define DNS_PORT 53 -#define DOT_PORT 853 -#define DNS_TASK_STACK 4096 -#define DOT_TASK_STACK 3072 -#define DNS_TASK_PRIO 5 -#define DOT_TASK_PRIO 5 -#define DNS_FORWARD_TIMEOUT_MS 2000 -#define NXDOMAIN_TTL 30 -#define HIJACK_TTL 10 - -static const char *TAG = "dns_server"; - -#pragma pack(push, 1) -typedef struct { - uint16_t id; - uint16_t flags; - uint16_t qdcount; - uint16_t ancount; - uint16_t nscount; - uint16_t arcount; -} dns_header_t; -#pragma pack(pop) - -#pragma pack(push, 1) -typedef struct { - uint16_t name; - uint16_t type; - uint16_t class; - uint32_t ttl; - uint16_t len; - uint32_t addr; -} dns_answer_t; -#pragma pack(pop) - -typedef struct { - uint32_t ip; -} auth_entry_t; - -static auth_entry_t s_auth_list[MAX_AUTH_IPS]; -static int s_auth_count = 0; -static TaskHandle_t s_dns_task = NULL; -static TaskHandle_t s_dot_task = NULL; -static volatile bool s_dns_running = false; -static esp_ip4_addr_t s_ap_ip; -static esp_ip4_addr_t s_upstream_dns; - -static bool is_authenticated(uint32_t ip) -{ - for (int i = 0; i < s_auth_count; i++) { - if (s_auth_list[i].ip == ip) return true; - } - return false; -} - -static void parse_dns_name(const uint8_t *buf, int buf_len, int offset, char *out, int out_len) -{ - int pos = offset; - int out_pos = 0; - int jumped = 0; - int jump_pos = 0; - while (pos < buf_len && out_pos < out_len - 1) { - uint8_t len = buf[pos]; - if (len == 0) break; - if ((len & 0xC0) == 0xC0) { - if (!jumped) jump_pos = pos + 2; - pos = ((len & 0x3F) << 8) | buf[pos + 1]; - jumped = 1; - continue; - } - if (out_pos > 0 && out_pos < out_len - 1) out[out_pos++] = '.'; - pos++; - for (int i = 0; i < len && pos < buf_len && out_pos < out_len - 1; i++) { - out[out_pos++] = buf[pos++]; - } - } - out[out_pos] = '\0'; -} - -static int build_nxdomain(uint8_t *response, int req_len) -{ - dns_header_t *hdr = (dns_header_t *)response; - hdr->flags = htons(0x8403); - hdr->ancount = 0; - hdr->nscount = 0; - hdr->arcount = 0; - return req_len; -} - -static int build_redirect_response(uint8_t *response, int req_len) -{ - memmove(response, response, req_len); - dns_header_t *hdr = (dns_header_t *)response; - hdr->flags = htons(0x8180); - hdr->ancount = htons(1); - hdr->nscount = 0; - hdr->arcount = 0; - int resp_len = req_len; - dns_answer_t ans; - ans.name = htons(0xC00C); - ans.type = htons(1); - ans.class = htons(1); - ans.ttl = htonl(HIJACK_TTL); - ans.len = htons(4); - ans.addr = s_ap_ip.addr; - memcpy(response + resp_len, &ans, sizeof(ans)); - resp_len += sizeof(ans); - return resp_len; -} - -static int forward_dns(const uint8_t *req, int req_len, uint8_t *resp, int resp_buf_len, - const struct sockaddr_in *client_addr, uint16_t txn_id) -{ - int upstream_sock = socket(AF_INET, SOCK_DGRAM, 0); - if (upstream_sock < 0) return -1; - - struct timeval tv = { .tv_sec = DNS_FORWARD_TIMEOUT_MS / 1000, .tv_usec = (DNS_FORWARD_TIMEOUT_MS % 1000) * 1000 }; - setsockopt(upstream_sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - - struct sockaddr_in upstream_addr = { - .sin_family = AF_INET, - .sin_port = htons(DNS_PORT), - .sin_addr.s_addr = s_upstream_dns.addr, - }; - - sendto(upstream_sock, req, req_len, 0, (struct sockaddr *)&upstream_addr, sizeof(upstream_addr)); - - int n = recvfrom(upstream_sock, resp, resp_buf_len, 0, NULL, NULL); - close(upstream_sock); - - if (n > 0) { - if (n >= sizeof(dns_header_t)) { - dns_header_t *hdr = (dns_header_t *)resp; - hdr->id = htons(txn_id); - } - } - return n; -} - -static void dns_server_task(void *arg) -{ - int sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) { - ESP_LOGE(TAG, "Failed to create DNS socket"); - s_dns_running = false; - vTaskDelete(NULL); - return; - } - - struct sockaddr_in bind_addr = { - .sin_family = AF_INET, - .sin_port = htons(DNS_PORT), - .sin_addr.s_addr = s_ap_ip.addr, - }; - if (bind(sock, (struct sockaddr *)&bind_addr, sizeof(bind_addr)) < 0) { - ESP_LOGE(TAG, "Failed to bind DNS socket"); - close(sock); - s_dns_running = false; - vTaskDelete(NULL); - return; - } - - ESP_LOGI(TAG, "DNS server started on port %d, AP IP=" IPSTR ", upstream DNS=" IPSTR, - DNS_PORT, IP2STR(&s_ap_ip), IP2STR(&s_upstream_dns)); - - uint8_t rx_buf[DNS_BUF_SIZE]; - uint8_t tx_buf[DNS_BUF_SIZE + sizeof(dns_answer_t)]; - - while (s_dns_running) { - struct sockaddr_in client_addr; - socklen_t client_len = sizeof(client_addr); - int n = recvfrom(sock, rx_buf, sizeof(rx_buf), 0, - (struct sockaddr *)&client_addr, &client_len); - if (n < (int)sizeof(dns_header_t)) continue; - - uint32_t client_ip = client_addr.sin_addr.s_addr; - dns_header_t *hdr = (dns_header_t *)rx_buf; - uint16_t txn_id = ntohs(hdr->id); - bool is_query = (ntohs(hdr->flags) & 0x8000) == 0; - uint16_t qdcount = ntohs(hdr->qdcount); - - if (!is_query || qdcount == 0) continue; - - int q_offset = sizeof(dns_header_t); - while (q_offset < n && rx_buf[q_offset] != 0) { - q_offset += rx_buf[q_offset] + 1; - } - if (q_offset + 5 > n) continue; - uint16_t qtype = (rx_buf[q_offset + 1] << 8) | rx_buf[q_offset + 2]; - int req_len = q_offset + 5; - - if (is_authenticated(client_ip)) { - int resp_len = forward_dns(rx_buf, req_len, tx_buf, sizeof(tx_buf), &client_addr, txn_id); - if (resp_len > 0) { - sendto(sock, tx_buf, resp_len, 0, (struct sockaddr *)&client_addr, client_len); - } - } else { - char qname[256] = {0}; - parse_dns_name(rx_buf, n, sizeof(dns_header_t), qname, sizeof(qname)); - ESP_LOGI(TAG, "Hijack DNS from " IPSTR ": %s (type=%d)", IP2STR(&(esp_ip4_addr_t){.addr=client_ip}), qname, qtype); - if (qtype == 1) { - int resp_len = build_redirect_response(rx_buf, req_len); - memcpy(tx_buf, rx_buf, resp_len); - dns_header_t *resp_hdr = (dns_header_t *)tx_buf; - resp_hdr->id = htons(txn_id); - sendto(sock, tx_buf, resp_len, 0, (struct sockaddr *)&client_addr, client_len); - } else { - int resp_len = build_nxdomain(rx_buf, req_len); - memcpy(tx_buf, rx_buf, resp_len); - dns_header_t *resp_hdr = (dns_header_t *)tx_buf; - resp_hdr->id = htons(txn_id); - sendto(sock, tx_buf, resp_len, 0, (struct sockaddr *)&client_addr, client_len); - } - } - } - - close(sock); - ESP_LOGI(TAG, "DNS server stopped"); - vTaskDelete(NULL); -} - -static void dot_reject_task(void *arg) -{ - int sock = socket(AF_INET, SOCK_STREAM, 0); - if (sock < 0) { - ESP_LOGE(TAG, "Failed to create DoT reject socket"); - vTaskDelete(NULL); - return; - } - - int opt = 1; - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); - - struct sockaddr_in bind_addr = { - .sin_family = AF_INET, - .sin_port = htons(DOT_PORT), - .sin_addr.s_addr = INADDR_ANY, - }; - if (bind(sock, (struct sockaddr *)&bind_addr, sizeof(bind_addr)) < 0) { - ESP_LOGE(TAG, "Failed to bind DoT reject socket on port %d", DOT_PORT); - close(sock); - vTaskDelete(NULL); - return; - } - - listen(sock, 1); - ESP_LOGI(TAG, "DoT reject server on port %d (forces DNS fallback to port 53)", DOT_PORT); - - while (s_dns_running) { - struct sockaddr_in client_addr; - socklen_t client_len = sizeof(client_addr); - int client_sock = accept(sock, (struct sockaddr *)&client_addr, &client_len); - if (client_sock >= 0) { - struct linger ling = { .l_onoff = 1, .l_linger = 0 }; - setsockopt(client_sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)); - close(client_sock); - } - } - - close(sock); - ESP_LOGI(TAG, "DoT reject server stopped"); - vTaskDelete(NULL); -} +#include "tollgate_core_dns.h" esp_err_t dns_server_start(esp_ip4_addr_t ap_ip, esp_ip4_addr_t upstream_dns) { - if (s_dns_running) return ESP_OK; - s_ap_ip = ap_ip; - s_upstream_dns = upstream_dns; - s_dns_running = true; - xTaskCreate(dns_server_task, "dns_server", DNS_TASK_STACK, NULL, DNS_TASK_PRIO, &s_dns_task); - xTaskCreate(dot_reject_task, "dot_reject", DOT_TASK_STACK, NULL, DOT_TASK_PRIO, &s_dot_task); - return ESP_OK; + return tollgate_core_dns_start_internal(ap_ip, upstream_dns); } void dns_server_stop(void) { - s_dns_running = false; - vTaskDelay(pdMS_TO_TICKS(200)); - s_dns_task = NULL; + tollgate_core_dns_stop(); } void dns_server_set_client_authenticated(uint32_t client_ip, bool authenticated) { - if (authenticated) { - if (is_authenticated(client_ip)) return; - if (s_auth_count < MAX_AUTH_IPS) { - s_auth_list[s_auth_count].ip = client_ip; - s_auth_count++; - } - } else { - for (int i = 0; i < s_auth_count; i++) { - if (s_auth_list[i].ip == client_ip) { - s_auth_list[i] = s_auth_list[s_auth_count - 1]; - s_auth_count--; - return; - } - } - } + tollgate_core_dns_set_authenticated(client_ip, authenticated); } bool dns_server_is_running(void) { - return s_dns_running; + return tollgate_core_dns_is_running(); } diff --git a/main/firewall.c b/main/firewall.c index 077d16c..5ffdee0 100644 --- a/main/firewall.c +++ b/main/firewall.c @@ -1,36 +1,28 @@ #include "firewall.h" -#include "dns_server.h" #include "tollgate_core.h" #include "tollgate_core_firewall.h" #include "esp_log.h" -#include "lwip/netif.h" -#include "lwip/lwip_napt.h" #include "lwip/prot/ip4.h" -#include "lwip/prot/tcp.h" -#include "lwip/prot/ip.h" #include static const char *TAG = "firewall"; static esp_ip4_addr_t s_ap_ip; -static uint16_t s_mining_port = 3333; -static bool s_sandbox_mint_access = false; esp_err_t firewall_init(esp_ip4_addr_t ap_ip) { s_ap_ip = ap_ip; - ip_napt_enable(s_ap_ip.addr, 1); - ESP_LOGI(TAG, "Firewall initialized with AP IP=" IPSTR " (NAT always on, per-client filter)", IP2STR(&s_ap_ip)); + ESP_LOGI(TAG, "Firewall initialized with AP IP=" IPSTR, IP2STR(&s_ap_ip)); return ESP_OK; } void firewall_set_mining_port(uint16_t port) { - s_mining_port = port; + tollgate_core_fw_set_sandbox_ports(port); } void firewall_set_sandbox_mint_access(bool enabled) { - s_sandbox_mint_access = enabled; + tollgate_core_fw_set_sandbox_mint_access(enabled); } esp_err_t firewall_get_mac_for_ip(uint32_t client_ip, char *mac_out, size_t mac_out_size) @@ -38,80 +30,24 @@ esp_err_t firewall_get_mac_for_ip(uint32_t client_ip, char *mac_out, size_t mac_ return tollgate_core_fw_get_mac_for_ip(client_ip, mac_out, mac_out_size); } -static bool is_sandbox_allowed(struct pbuf *p) -{ - if (p->len < IP_HLEN) return false; - struct ip_hdr *iphdr = (struct ip_hdr *)p->payload; - uint32_t dest_ip_h = lwip_ntohl(iphdr->dest.addr); - uint32_t ap_ip_h = lwip_ntohl(s_ap_ip.addr); - - if (dest_ip_h == ap_ip_h) { - if (iphdr->_proto == IP_PROTO_TCP) { - uint16_t dst_port = 0; - if (p->len >= IP_HLEN + TCP_HLEN) { - struct tcp_hdr *tcphdr = (struct tcp_hdr *)((uint8_t *)p->payload + IP_HLEN); - dst_port = lwip_ntohs(tcphdr->dest); - } - if (dst_port == 80 || dst_port == 2121 || dst_port == s_mining_port) { - return true; - } - } - if (iphdr->_proto == IP_PROTO_UDP) { - return true; - } - } - - if (s_sandbox_mint_access && iphdr->_proto == IP_PROTO_TCP) { - return true; - } - - return false; -} - int tollgate_ip4_canforward_filter(struct pbuf *p, u32_t dest_addr_hostorder) { - (void)dest_addr_hostorder; - if (p->len < IP_HLEN) return -1; - struct ip_hdr *iphdr = (struct ip_hdr *)p->payload; - uint32_t src_ip_h = lwip_ntohl(iphdr->src.addr); - uint32_t ap_subnet = lwip_ntohl(s_ap_ip.addr) & 0xFFFFFF00; - if ((src_ip_h & 0xFFFFFF00) != ap_subnet) { - return 1; - } - if (firewall_is_client_allowed(iphdr->src.addr)) { - return 1; - } - if (is_sandbox_allowed(p)) { - return 1; - } - return 0; + return tollgate_core_ip4_canforward_filter(p, dest_addr_hostorder); } void firewall_grant_access(uint32_t client_ip) { tollgate_core_fw_grant(client_ip); - dns_server_set_client_authenticated(client_ip, true); - - char mac[18] = {0}; - tollgate_core_fw_get_mac_for_ip(client_ip, mac, sizeof(mac)); - esp_ip4_addr_t ip_addr = { .addr = client_ip }; - ESP_LOGI(TAG, "Access granted to " IPSTR " mac=%s", IP2STR(&ip_addr), - mac[0] ? mac : "unknown"); } void firewall_revoke_access(uint32_t client_ip) { tollgate_core_fw_revoke(client_ip); - dns_server_set_client_authenticated(client_ip, false); - - esp_ip4_addr_t ip_addr = { .addr = client_ip }; - ESP_LOGI(TAG, "Access revoked for " IPSTR, IP2STR(&ip_addr)); } void firewall_revoke_all(void) { tollgate_core_fw_revoke_all(); - ESP_LOGI(TAG, "All client access revoked"); } bool firewall_is_client_allowed(uint32_t client_ip) diff --git a/main/stratum_proxy.c b/main/stratum_proxy.c index 288c633..53909f0 100644 --- a/main/stratum_proxy.c +++ b/main/stratum_proxy.c @@ -1,160 +1,31 @@ #include "stratum_proxy.h" -#include "mining_payment.h" -#include "esp_log.h" -#include "lwip/sockets.h" -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" +#include "tollgate_core_stratum_proxy.h" #include -static const char *TAG = "stratum_proxy"; -static uint16_t s_port = 3333; -static bool s_running = false; -static TaskHandle_t s_task_handle = NULL; -static int s_server_fd = -1; - -static stratum_job_t s_current_job = {0}; -static stratum_proxy_stats_t s_stats = {0}; - -static void proxy_client_handler(void *arg) -{ - int client_fd = (int)(intptr_t)arg; - struct sockaddr_in client_addr; - socklen_t addr_len = sizeof(client_addr); - getpeername(client_fd, (struct sockaddr *)&client_addr, &addr_len); - uint32_t client_ip = client_addr.sin_addr.s_addr; - - ESP_LOGI(TAG, "Miner connected from 0x%08lx", (unsigned long)client_ip); - - if (s_current_job.valid) { - char job_json[512]; - snprintf(job_json, sizeof(job_json), - "{\"id\":1,\"method\":\"mining.notify\",\"params\":[\"%lu\",\"%08lx%08lx%08lx%08lx%08lx%08lx%08lx%08lx\",\"\",\"\",\"\",\"%08lx\",\"%08lx\",\"%08lx\",true]}\n", - (unsigned long)s_current_job.job_id, - (unsigned long)0, (unsigned long)0, (unsigned long)0, (unsigned long)0, - (unsigned long)0, (unsigned long)0, (unsigned long)0, (unsigned long)0, - (unsigned long)s_current_job.nbits, (unsigned long)s_current_job.ntime, - (unsigned long)s_current_job.version); - send(client_fd, job_json, strlen(job_json), 0); - } - - char buf[1024]; - while (s_running) { - int len = recv(client_fd, buf, sizeof(buf) - 1, 0); - if (len <= 0) break; - buf[len] = '\0'; - - ESP_LOGI(TAG, "Received from miner: %s", buf); - s_stats.total_shares++; - s_stats.total_accepted++; - } - - ESP_LOGI(TAG, "Miner disconnected from 0x%08lx", (unsigned long)client_ip); - close(client_fd); - vTaskDelete(NULL); -} - -static void proxy_server_task(void *arg) -{ - struct sockaddr_in server_addr; - memset(&server_addr, 0, sizeof(server_addr)); - server_addr.sin_family = AF_INET; - server_addr.sin_addr.s_addr = INADDR_ANY; - server_addr.sin_port = htons(s_port); - - s_server_fd = socket(AF_INET, SOCK_STREAM, 0); - if (s_server_fd < 0) { - ESP_LOGE(TAG, "Failed to create socket"); - vTaskDelete(NULL); - return; - } - - int opt = 1; - setsockopt(s_server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); - - if (bind(s_server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) != 0) { - ESP_LOGE(TAG, "Failed to bind to port %u", (unsigned)s_port); - close(s_server_fd); - s_server_fd = -1; - vTaskDelete(NULL); - return; - } - - if (listen(s_server_fd, 5) != 0) { - ESP_LOGE(TAG, "Failed to listen"); - close(s_server_fd); - s_server_fd = -1; - vTaskDelete(NULL); - return; - } - - ESP_LOGI(TAG, "Stratum proxy listening on port %u", (unsigned)s_port); - - while (s_running) { - struct sockaddr_in client_addr; - socklen_t client_len = sizeof(client_addr); - int client_fd = accept(s_server_fd, (struct sockaddr *)&client_addr, &client_len); - if (client_fd < 0) continue; - - s_stats.active_miners++; - char task_name[20]; - snprintf(task_name, sizeof(task_name), "miner_%d", client_fd); - xTaskCreate(proxy_client_handler, task_name, 4096, (void *)(intptr_t)client_fd, 3, NULL); - } - - close(s_server_fd); - s_server_fd = -1; - vTaskDelete(NULL); -} +_Static_assert(sizeof(stratum_job_t) == sizeof(tollgate_stratum_job_t), "job struct size mismatch"); +_Static_assert(sizeof(stratum_proxy_stats_t) == sizeof(tollgate_stratum_proxy_stats_t), "stats struct size mismatch"); esp_err_t stratum_proxy_init(uint16_t port) { - s_port = port; - memset(&s_current_job, 0, sizeof(s_current_job)); - memset(&s_stats, 0, sizeof(s_stats)); - s_running = true; - - BaseType_t ret = xTaskCreate(proxy_server_task, "stratum_proxy", 4096, NULL, 4, &s_task_handle); - if (ret != pdPASS) { - ESP_LOGE(TAG, "Failed to create proxy task"); - s_running = false; - return ESP_FAIL; - } - - ESP_LOGI(TAG, "Stratum proxy initialized on port %u", (unsigned)port); - return ESP_OK; + return tollgate_core_stratum_proxy_init(port); } void stratum_proxy_set_job(const stratum_job_t *job) { - if (job) { - memcpy(&s_current_job, job, sizeof(stratum_job_t)); - s_stats.nbits = job->nbits; - s_stats.current_hashprice = mining_get_current_hashprice(); - } + tollgate_core_stratum_proxy_set_job((const tollgate_stratum_job_t *)job); } const stratum_job_t *stratum_proxy_get_current_job(void) { - return &s_current_job; + return (const stratum_job_t *)tollgate_core_stratum_proxy_get_current_job(); } void stratum_proxy_get_stats(stratum_proxy_stats_t *stats) { - if (stats) { - *stats = s_stats; - stats->current_hashprice = mining_get_current_hashprice(); - } + tollgate_core_stratum_proxy_get_stats((tollgate_stratum_proxy_stats_t *)stats); } void stratum_proxy_stop(void) { - s_running = false; - if (s_server_fd >= 0) { - close(s_server_fd); - s_server_fd = -1; - } - if (s_task_handle) { - vTaskDelay(pdMS_TO_TICKS(500)); - s_task_handle = NULL; - } + tollgate_core_stratum_proxy_stop(); } diff --git a/tests/unit/test_firewall_sandbox b/tests/unit/test_firewall_sandbox index 3e2895b..7e5aa6d 100755 Binary files a/tests/unit/test_firewall_sandbox and b/tests/unit/test_firewall_sandbox differ diff --git a/tests/unit/test_mining_payment b/tests/unit/test_mining_payment index d38bf9d..dd4e781 100755 Binary files a/tests/unit/test_mining_payment and b/tests/unit/test_mining_payment differ diff --git a/tests/unit/test_session_payment_method b/tests/unit/test_session_payment_method index 950a72f..44cafd3 100755 Binary files a/tests/unit/test_session_payment_method and b/tests/unit/test_session_payment_method differ diff --git a/tests/unit/test_stratum_proxy b/tests/unit/test_stratum_proxy index 963df67..542d82f 100755 Binary files a/tests/unit/test_stratum_proxy and b/tests/unit/test_stratum_proxy differ diff --git a/tollgate_core/CMakeLists.txt b/tollgate_core/CMakeLists.txt deleted file mode 100644 index 988167f..0000000 --- a/tollgate_core/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -cmake_minimum_required(VERSION 3.16) -project(tollgate_core C) - -set(TG_CORE_SOURCES - src/tollgate_core.c - src/tollgate_cashu.c - src/tollgate_session.c - src/tollgate_mining.c -) - -add_library(tollgate_core STATIC ${TG_CORE_SOURCES}) - -target_include_directories(tollgate_core PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include - ${CMAKE_CURRENT_SOURCE_DIR}/src -) - -find_package(PkgConfig REQUIRED) -pkg_check_modules(CJSON REQUIRED libcjson) - -target_include_directories(tollgate_core PRIVATE - ${CJSON_INCLUDE_DIRS} - /usr/include -) - -target_link_libraries(tollgate_core PUBLIC mbedcrypto cjson m) - -target_compile_options(tollgate_core PRIVATE -Wall -Wextra -Wno-unused-parameter) diff --git a/tollgate_core/include/tollgate_core.h b/tollgate_core/include/tollgate_core.h deleted file mode 100644 index bbae7cf..0000000 --- a/tollgate_core/include/tollgate_core.h +++ /dev/null @@ -1,90 +0,0 @@ -#ifndef TOLLGATE_CORE_H -#define TOLLGATE_CORE_H - -#include "tollgate_platform.h" -#include -#include - -int tollgate_core_init(const tollgate_platform_t *platform, uint32_t ap_ip); -void tollgate_core_tick(void); - -int tollgate_core_dns_start(uint32_t upstream_dns); -void tollgate_core_dns_stop(void); - -int tollgate_core_process_payment(uint32_t client_ip, const char *token_str); -int tollgate_core_process_share(uint32_t client_ip, const char *job_id, - const char *nonce, const char *ntime, const char *version); - -void tollgate_core_client_connected(const uint8_t *mac, uint32_t client_ip); -void tollgate_core_client_disconnected(const uint8_t *mac); - -bool tollgate_core_is_client_allowed(uint32_t client_ip); -bool tollgate_core_is_dns_running(void); - -char *tollgate_core_get_status_json(void); -char *tollgate_core_get_config_json(void); - -int tollgate_core_active_session_count(void); -int tollgate_core_allowed_client_count(void); -int tollgate_core_firewall_revoke_all(void); -void tollgate_core_firewall_set_mining_port(uint16_t port); -void tollgate_core_firewall_set_sandbox_mint_access(bool enable); - -bool tollgate_core_is_owner(uint32_t client_ip); -bool tollgate_core_is_owner_connected(void); - -double tollgate_core_get_hashprice(void); -void tollgate_core_set_nbits(uint32_t nbits); -const void *tollgate_core_get_current_job(void); -void tollgate_core_set_job(const void *job); - -int tollgate_core_stratum_client_start(void); -void tollgate_core_stratum_client_stop(void); - -int tollgate_core_stratum_proxy_init(uint16_t port); -void tollgate_core_stratum_proxy_get_stats(void *out); - -void tollgate_core_mining_init(void); - -void tollgate_core_beacon_start(void); - -void tollgate_core_market_init(void); -void tollgate_core_market_on_scan_result(const void *ie_data, int ie_len, - const uint8_t *bssid, int rssi); - -const void *tollgate_core_get_sessions_array(void); -int tollgate_core_get_sessions_array_size(void); -void *tollgate_core_find_session_by_ip(uint32_t ip); -void *tollgate_core_find_session_by_mac(const char *mac); -void *tollgate_core_session_create(uint32_t client_ip, uint64_t allotment_ms); -void *tollgate_core_session_create_bytes(uint32_t client_ip, uint64_t allotment_bytes); -void tollgate_core_session_extend(void *session, uint64_t additional_ms); -void tollgate_core_session_revoke(void *session); -int tollgate_core_session_add_bytes(uint32_t client_ip, uint64_t bytes); -bool tollgate_core_session_is_expired(const void *session); - -void tollgate_core_firewall_grant(uint32_t client_ip); -void tollgate_core_firewall_revoke(uint32_t client_ip); -int tollgate_core_firewall_get_mac_for_ip(uint32_t client_ip, char *mac_out, int mac_out_size); - -int tollgate_core_cashu_decode(const char *token_str, void *out); -int tollgate_core_cashu_check_states(const char *mint_url, const void *token, - void *states, int *state_count); -uint64_t tollgate_core_cashu_allotment(uint64_t amount, uint64_t price, uint64_t step_size); -bool tollgate_core_cashu_is_mint_accepted(const char *mint_url); -const char *tollgate_core_cashu_token_mint(const void *token); -uint64_t tollgate_core_cashu_token_amount(const void *token); - -void tollgate_core_mining_update_hashrate(uint32_t client_ip, bool accepted); -const void *tollgate_core_mining_get_client_stats(uint32_t client_ip); -double tollgate_core_mining_get_hashprice(void); -uint64_t tollgate_core_mining_shares_to_allotment_ms(double hashrate, double hashprice, - int price, int step_ms); -uint64_t tollgate_core_mining_shares_to_allotment_bytes(double hashrate, double hashprice, - int price, int step_bytes); -void tollgate_core_mining_set_nbits(uint32_t nbits); - -const tollgate_platform_t *tollgate_core_get_platform(void); -uint32_t tollgate_core_get_ap_ip(void); - -#endif diff --git a/tollgate_core/include/tollgate_platform.h b/tollgate_core/include/tollgate_platform.h deleted file mode 100644 index b553a83..0000000 --- a/tollgate_core/include/tollgate_platform.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef TOLLGATE_PLATFORM_H -#define TOLLGATE_PLATFORM_H - -#include -#include -#include - -typedef struct { - uint16_t (*get_price_sats)(void); - int32_t (*get_step_ms)(void); - int64_t (*get_step_bytes)(void); - const char* (*get_mint_url)(void); - const char* (*get_metric)(void); - - int64_t (*get_time_ms)(void); - - void (*log_info)(const char *tag, const char *fmt, ...); - void (*log_warn)(const char *tag, const char *fmt, ...); - void (*log_error)(const char *tag, const char *fmt, ...); - - bool (*wallet_receive)(const char *token); - bool (*wallet_send)(uint64_t amount, char *buf, size_t buf_len); - uint64_t (*wallet_balance)(void); - - int (*http_post)(const char *url, const char *headers, - const char *body, int body_len, - char *resp, int resp_len); - - bool (*create_task)(void (*fn)(void*), void *arg, - const char *name, int stack_bytes, int priority); - - int (*socket_udp)(void); - int (*socket_tcp)(void); - int (*socket_bind)(int fd, uint32_t ip, uint16_t port); - int (*socket_listen)(int fd, int backlog); - int (*socket_accept)(int fd, uint32_t *client_ip, uint16_t *client_port); - int (*socket_recvfrom)(int fd, void *buf, int len, - uint32_t *src_ip, uint16_t *src_port); - int (*socket_sendto)(int fd, const void *buf, int len, - uint32_t dest_ip, uint16_t dest_port); - int (*socket_read)(int fd, void *buf, int len); - int (*socket_write)(int fd, const void *buf, int len); - void (*socket_close)(int fd); - void (*socket_set_recv_timeout)(int fd, int ms); - - bool (*get_sta_mac_ip_list)(void *list_out, int max, int *count_out); - bool (*set_vendor_ie)(bool enable, const void *ie_data, int ie_len); - int (*arp_get_mac)(uint32_t ip, uint8_t *mac_out); - void (*napt_enable)(uint32_t ip, bool enable); - - bool (*mining_enabled)(void); - const char* (*get_stratum_host)(void); - uint16_t (*get_stratum_port)(void); - const char* (*get_stratum_user)(void); - const char* (*get_stratum_pass)(void); - uint16_t (*get_mining_port)(void); - uint64_t (*get_hashprice_override)(void); - - void (*fill_random)(void *buf, int len); - - int (*get_accepted_mint_count)(void); - const char* (*get_accepted_mint)(int index); - bool (*is_mint_reachable)(const char *mint_url); - bool (*mac_for_ip)(uint32_t ip, char *mac_out, int mac_out_size); - -} tollgate_platform_t; - -#endif diff --git a/tollgate_core/src/tollgate_cashu.c b/tollgate_core/src/tollgate_cashu.c deleted file mode 100644 index 55f4953..0000000 --- a/tollgate_core/src/tollgate_cashu.c +++ /dev/null @@ -1,253 +0,0 @@ -#include "tollgate_cashu.h" -#include "tollgate_core.h" -#include "tollgate_platform.h" -#include -#include -#include -#include -#include -#include - -static const char *TAG = "tg_cashu"; - -static const char V3_PREFIX[] = "cashuA"; -static const size_t V3_PREFIX_LEN = 6; - -static int b64url_decode(const char *input, size_t input_len, char *out, size_t out_size, size_t *out_len) -{ - char *b64 = malloc(input_len + 4); - if (!b64) return -1; - size_t b64_len = input_len; - memcpy(b64, input, b64_len); - b64[b64_len] = '\0'; - - for (size_t i = 0; i < b64_len; i++) { - if (b64[i] == '-') b64[i] = '+'; - else if (b64[i] == '_') b64[i] = '/'; - } - while (b64_len % 4 != 0) { - b64[b64_len++] = '='; - } - b64[b64_len] = '\0'; - - size_t olen = 0; - int ret = mbedtls_base64_decode((unsigned char *)out, out_size, &olen, - (const unsigned char *)b64, b64_len); - free(b64); - if (ret != 0) return -1; - *out_len = olen; - return 0; -} - -static int parse_proofs_array(cJSON *arr, tg_cashu_token_t *out) -{ - if (!cJSON_IsArray(arr)) return -1; - int count = cJSON_GetArraySize(arr); - if (count > TG_CASHU_MAX_PROOFS) return -1; - - out->proof_count = 0; - out->total_amount = 0; - for (int i = 0; i < count; i++) { - cJSON *proof = cJSON_GetArrayItem(arr, i); - cJSON *amt = cJSON_GetObjectItemCaseSensitive(proof, "amount"); - cJSON *id = cJSON_GetObjectItemCaseSensitive(proof, "id"); - cJSON *secret = cJSON_GetObjectItemCaseSensitive(proof, "secret"); - cJSON *c = cJSON_GetObjectItemCaseSensitive(proof, "C"); - - if (!amt || !cJSON_IsNumber(amt)) return -1; - - out->proofs[i].amount = (uint64_t)amt->valuedouble; - out->total_amount += out->proofs[i].amount; - - if (id && cJSON_IsString(id)) { - strncpy(out->proofs[i].id, id->valuestring, sizeof(out->proofs[i].id) - 1); - } - if (secret && cJSON_IsString(secret)) { - strncpy(out->proofs[i].secret, secret->valuestring, sizeof(out->proofs[i].secret) - 1); - } - if (c && cJSON_IsString(c)) { - strncpy(out->proofs[i].c, c->valuestring, sizeof(out->proofs[i].c) - 1); - } - out->proof_count++; - } - return 0; -} - -int tg_cashu_decode_token(const char *token_str, tg_cashu_token_t *out) -{ - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (!token_str || !out) return -1; - memset(out, 0, sizeof(*out)); - - size_t len = strlen(token_str); - char *nl = strchr(token_str, '\n'); - if (nl) len = nl - token_str; - char *cr = strchr(token_str, '\r'); - if (cr && (cr - token_str) < (int)len) len = cr - token_str; - if (len <= V3_PREFIX_LEN) { - if (p && p->log_error) p->log_error(TAG, "Token too short"); - return -1; - } - if (strncmp(token_str, V3_PREFIX, V3_PREFIX_LEN) != 0) { - if (p && p->log_error) p->log_error(TAG, "Token missing cashuA prefix"); - return -1; - } - - size_t b64_len = len - V3_PREFIX_LEN; - size_t decoded_size = (b64_len * 3) / 4 + 4; - char *json_buf = malloc(decoded_size); - if (!json_buf) return -1; - size_t json_len = 0; - if (b64url_decode(token_str + V3_PREFIX_LEN, b64_len, - json_buf, decoded_size - 1, &json_len) != 0) { - if (p && p->log_error) p->log_error(TAG, "Base64url decode failed"); - free(json_buf); - return -1; - } - json_buf[json_len] = '\0'; - - cJSON *root = cJSON_Parse(json_buf); - free(json_buf); - if (!root) { - if (p && p->log_error) p->log_error(TAG, "JSON parse failed"); - return -1; - } - - cJSON *token_arr = cJSON_GetObjectItemCaseSensitive(root, "token"); - if (token_arr && cJSON_IsArray(token_arr)) { - cJSON *first = cJSON_GetArrayItem(token_arr, 0); - if (!first) { cJSON_Delete(root); return -1; } - - cJSON *mint = cJSON_GetObjectItemCaseSensitive(first, "mint"); - if (mint && cJSON_IsString(mint)) { - strncpy(out->mint_url, mint->valuestring, sizeof(out->mint_url) - 1); - } - - cJSON *proofs = cJSON_GetObjectItemCaseSensitive(first, "proofs"); - if (proofs) { - if (parse_proofs_array(proofs, out) != 0) { cJSON_Delete(root); return -1; } - } - } else { - cJSON *mint = cJSON_GetObjectItemCaseSensitive(root, "mint"); - if (mint && cJSON_IsString(mint)) { - strncpy(out->mint_url, mint->valuestring, sizeof(out->mint_url) - 1); - } - - cJSON *proofs = cJSON_GetObjectItemCaseSensitive(root, "proofs"); - if (proofs) { - if (parse_proofs_array(proofs, out) != 0) { cJSON_Delete(root); return -1; } - } - } - - cJSON_Delete(root); - - if (out->proof_count == 0) { - if (p && p->log_error) p->log_error(TAG, "No proofs in token"); - return -1; - } - - if (p && p->log_info) p->log_info(TAG, "Decoded token: %d proofs, total=%llu, mint=%s", - out->proof_count, (unsigned long long)out->total_amount, out->mint_url); - return 0; -} - -static void sha256_hex(const char *data, size_t data_len, char *hex_out) -{ - unsigned char hash[32]; - mbedtls_sha256((const unsigned char *)data, data_len, hash, 0); - for (int i = 0; i < 32; i++) { - sprintf(hex_out + i * 2, "%02x", hash[i]); - } - hex_out[64] = '\0'; -} - -int tg_cashu_check_proof_states(const char *mint_url, const tg_cashu_token_t *token, - tg_cashu_proof_state_t *states, int *state_count) -{ - const tollgate_platform_t *p = tollgate_core_get_platform(); - - cJSON *ys_arr = cJSON_CreateArray(); - for (int i = 0; i < token->proof_count; i++) { - char y_hex[65]; - sha256_hex(token->proofs[i].secret, strlen(token->proofs[i].secret), y_hex); - cJSON_AddItemToArray(ys_arr, cJSON_CreateString(y_hex)); - strncpy(states[i].y_hex, y_hex, sizeof(states[i].y_hex) - 1); - states[i].spent = false; - } - *state_count = token->proof_count; - - char *ys_json = cJSON_PrintUnformatted(ys_arr); - cJSON_Delete(ys_arr); - - char *post_body = malloc(4096); - if (!post_body) { cJSON_free(ys_json); return -1; } - snprintf(post_body, 4096, "{\"Ys\":%s}", ys_json); - cJSON_free(ys_json); - - char url[512]; - snprintf(url, sizeof(url), "%s/v1/checkstate", mint_url); - - if (!p || !p->http_post) { - free(post_body); - return -1; - } - - char *resp_buf = malloc(8192); - if (!resp_buf) { free(post_body); return -1; } - - int resp_len = p->http_post(url, "Content-Type: application/json", - post_body, (int)strlen(post_body), - resp_buf, 8191); - free(post_body); - - if (resp_len <= 0) { - if (p && p->log_error) p->log_error(TAG, "checkstate HTTP failed: resp_len=%d", resp_len); - free(resp_buf); - return -1; - } - resp_buf[resp_len] = '\0'; - - cJSON *root = cJSON_Parse(resp_buf); - free(resp_buf); - if (!root) return -1; - - cJSON *states_arr = cJSON_GetObjectItemCaseSensitive(root, "states"); - if (!states_arr || !cJSON_IsArray(states_arr)) { - cJSON_Delete(root); - return -1; - } - - int n = cJSON_GetArraySize(states_arr); - for (int i = 0; i < n && i < token->proof_count; i++) { - cJSON *s = cJSON_GetArrayItem(states_arr, i); - cJSON *state = cJSON_GetObjectItemCaseSensitive(s, "state"); - if (state && cJSON_IsString(state)) { - states[i].spent = (strcmp(state->valuestring, "SPENT") == 0); - } - } - - cJSON_Delete(root); - return 0; -} - -uint64_t tg_cashu_calculate_allotment_ms(uint64_t token_amount, uint64_t price_per_step, - uint64_t step_size_ms) -{ - if (price_per_step == 0) return 0; - return (token_amount / price_per_step) * step_size_ms; -} - -uint64_t tg_cashu_calculate_allotment(uint64_t token_amount, uint64_t price_per_step, - uint64_t step_size) -{ - if (price_per_step == 0) return 0; - return (token_amount / price_per_step) * step_size; -} - -bool tg_cashu_is_mint_accepted(const char *mint_url, const char *accepted_mint_url) -{ - if (!mint_url || mint_url[0] == '\0') return false; - if (!accepted_mint_url || accepted_mint_url[0] == '\0') return false; - return (strstr(mint_url, accepted_mint_url) != NULL || - strcmp(mint_url, accepted_mint_url) == 0); -} diff --git a/tollgate_core/src/tollgate_cashu.h b/tollgate_core/src/tollgate_cashu.h deleted file mode 100644 index 9785e98..0000000 --- a/tollgate_core/src/tollgate_cashu.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef TOLLGATE_CORE_CASHU_H -#define TOLLGATE_CORE_CASHU_H - -#include -#include - -#define TG_CASHU_MAX_PROOFS 10 -#define TG_CASHU_MAX_SECRET_LEN 128 -#define TG_CASHU_MAX_ID_LEN 68 -#define TG_CASHU_MAX_C_LEN 128 - -typedef struct { - uint64_t amount; - char id[TG_CASHU_MAX_ID_LEN]; - char secret[TG_CASHU_MAX_SECRET_LEN]; - char c[TG_CASHU_MAX_C_LEN]; -} tg_cashu_proof_t; - -typedef struct { - tg_cashu_proof_t proofs[TG_CASHU_MAX_PROOFS]; - int proof_count; - char mint_url[256]; - uint64_t total_amount; -} tg_cashu_token_t; - -typedef struct { - char y_hex[65]; - bool spent; -} tg_cashu_proof_state_t; - -int tg_cashu_decode_token(const char *token_str, tg_cashu_token_t *out); -int tg_cashu_check_proof_states(const char *mint_url, const tg_cashu_token_t *token, - tg_cashu_proof_state_t *states, int *state_count); -uint64_t tg_cashu_calculate_allotment_ms(uint64_t token_amount, uint64_t price_per_step, - uint64_t step_size_ms); -uint64_t tg_cashu_calculate_allotment(uint64_t token_amount, uint64_t price_per_step, - uint64_t step_size); -bool tg_cashu_is_mint_accepted(const char *mint_url, const char *accepted_mint_url); - -#endif diff --git a/tollgate_core/src/tollgate_core.c b/tollgate_core/src/tollgate_core.c deleted file mode 100644 index c7c2902..0000000 --- a/tollgate_core/src/tollgate_core.c +++ /dev/null @@ -1,466 +0,0 @@ -#include "tollgate_core.h" -#include "tollgate_platform.h" -#include "tollgate_cashu.h" -#include "tollgate_session.h" -#include "tollgate_firewall.h" -#include "tollgate_mining.h" -#include -#include -#include - -static const char *TAG = "tg_core"; -static const tollgate_platform_t *s_platform; -static uint32_t s_ap_ip; - -static uint32_t s_owner_ip; -static uint8_t s_owner_mac[6]; -static bool s_owner_connected; - -const tollgate_platform_t *tollgate_core_get_platform(void) -{ - return s_platform; -} - -uint32_t tollgate_core_get_ap_ip(void) -{ - return s_ap_ip; -} - -int tollgate_core_init(const tollgate_platform_t *platform, uint32_t ap_ip) -{ - if (!platform) return -1; - - s_platform = platform; - s_ap_ip = ap_ip; - s_owner_connected = false; - memset(s_owner_mac, 0, sizeof(s_owner_mac)); - - tg_session_init(); - tg_firewall_init(ap_ip); - tg_mining_init(); - - if (platform->log_info) { - char ip_str[16]; - snprintf(ip_str, sizeof(ip_str), "%d.%d.%d.%d", - (int)((ap_ip >> 0) & 0xFF), (int)((ap_ip >> 8) & 0xFF), - (int)((ap_ip >> 16) & 0xFF), (int)((ap_ip >> 24) & 0xFF)); - platform->log_info(TAG, "TollGate core initialized, AP IP=%s", ip_str); - } - return 0; -} - -void tollgate_core_tick(void) -{ - tg_session_tick(); -} - -int tollgate_core_process_payment(uint32_t client_ip, const char *token_str) -{ - if (!s_platform || !token_str) return -1; - - const char *accepted_mint = s_platform->get_mint_url ? s_platform->get_mint_url() : NULL; - if (!accepted_mint || accepted_mint[0] == '\0') { - if (s_platform->log_error) s_platform->log_error(TAG, "No mint URL configured"); - return -1; - } - - tg_cashu_token_t token; - if (tg_cashu_decode_token(token_str, &token) != 0) { - if (s_platform->log_error) s_platform->log_error(TAG, "Token decode failed"); - return -1; - } - - bool mint_ok = false; - if (s_platform->get_accepted_mint_count && s_platform->get_accepted_mint) { - int count = s_platform->get_accepted_mint_count(); - for (int i = 0; i < count; i++) { - if (tg_cashu_is_mint_accepted(token.mint_url, s_platform->get_accepted_mint(i))) { - mint_ok = true; - break; - } - } - } else { - mint_ok = tg_cashu_is_mint_accepted(token.mint_url, accepted_mint); - } - if (!mint_ok) { - if (s_platform->log_error) s_platform->log_error(TAG, "Token mint not accepted"); - return -1; - } - - tg_cashu_proof_state_t states[TG_CASHU_MAX_PROOFS]; - int state_count = 0; - if (tg_cashu_check_proof_states(token.mint_url, &token, states, &state_count) != 0) { - if (s_platform->log_error) s_platform->log_error(TAG, "Proof state check failed (continuing)"); - } else { - for (int i = 0; i < state_count; i++) { - if (states[i].spent) { - if (s_platform->log_error) s_platform->log_error(TAG, "Proof %d is SPENT", i); - return -1; - } - } - } - - if (s_platform->wallet_receive) { - if (!s_platform->wallet_receive(token_str)) { - if (s_platform->log_error) s_platform->log_error(TAG, "wallet_receive rejected token"); - return -1; - } - } - - const char *metric = (s_platform->get_metric) ? s_platform->get_metric() : "milliseconds"; - uint64_t price = (s_platform->get_price_sats) ? s_platform->get_price_sats() : 21; - uint64_t step_size; - - if (strcmp(metric, "bytes") == 0) { - step_size = (s_platform->get_step_bytes) ? (uint64_t)s_platform->get_step_bytes() : 22020096; - } else { - step_size = (s_platform->get_step_ms) ? (uint64_t)s_platform->get_step_ms() : 60000; - } - - uint64_t allotment = tg_cashu_calculate_allotment(token.total_amount, price, step_size); - if (allotment == 0) { - if (s_platform->log_error) s_platform->log_error(TAG, "Token amount too small"); - return -1; - } - - if (strcmp(metric, "bytes") == 0) { - if (!tg_session_create_bytes(client_ip, allotment)) return -1; - } else { - if (!tg_session_create(client_ip, allotment)) return -1; - } - - if (s_platform->log_info) s_platform->log_info(TAG, "Payment: %llu sats -> %llu %s", - (unsigned long long)token.total_amount, (unsigned long long)allotment, metric); - return 0; -} - -int tollgate_core_process_share(uint32_t client_ip, const char *job_id, - const char *nonce, const char *ntime, const char *version) -{ - (void)job_id; (void)nonce; (void)ntime; (void)version; - if (!s_platform) return -1; - - tg_mining_update_hashrate(client_ip, true); - const tg_mining_client_stats_t *stats = tg_mining_get_client_stats(client_ip); - if (!stats) return -1; - - double hashprice = tg_mining_get_current_hashprice(); - uint64_t override = (s_platform->get_hashprice_override) ? s_platform->get_hashprice_override() : 0; - if (override > 0) hashprice = tg_mining_calculate_hashprice_override(override); - - const char *metric = (s_platform->get_metric) ? s_platform->get_metric() : "milliseconds"; - int price = (s_platform->get_price_sats) ? s_platform->get_price_sats() : 21; - - tg_session_t *existing = tg_session_find_by_ip(client_ip); - if (existing && existing->payment_method == TG_PAYMENT_MINING) { - uint64_t allotment; - if (strcmp(metric, "bytes") == 0) { - int step_bytes = (s_platform->get_step_bytes) ? (int)s_platform->get_step_bytes() : 22020096; - allotment = tg_mining_shares_to_allotment_bytes(stats->hashrate_ghs, hashprice, price, step_bytes); - existing->allotment_bytes += allotment; - } else { - int step_ms = (s_platform->get_step_ms) ? s_platform->get_step_ms() : 60000; - allotment = tg_mining_shares_to_allotment_ms(stats->hashrate_ghs, hashprice, price, step_ms); - tg_session_extend(existing, allotment); - } - return 0; - } - - uint64_t allotment; - if (strcmp(metric, "bytes") == 0) { - int step_bytes = (s_platform->get_step_bytes) ? (int)s_platform->get_step_bytes() : 22020096; - allotment = tg_mining_shares_to_allotment_bytes(stats->hashrate_ghs, hashprice, price, step_bytes); - tg_session_t *s = tg_session_create_bytes(client_ip, allotment); - if (s) s->payment_method = TG_PAYMENT_MINING; - } else { - int step_ms = (s_platform->get_step_ms) ? s_platform->get_step_ms() : 60000; - allotment = tg_mining_shares_to_allotment_ms(stats->hashrate_ghs, hashprice, price, step_ms); - tg_session_t *s = tg_session_create(client_ip, allotment); - if (s) s->payment_method = TG_PAYMENT_MINING; - } - - return 0; -} - -void tollgate_core_client_connected(const uint8_t *mac, uint32_t client_ip) -{ - if (!s_owner_connected) { - s_owner_connected = true; - s_owner_ip = client_ip; - if (mac) memcpy(s_owner_mac, mac, 6); - if (s_platform && s_platform->log_info) { - char ip_str[16]; - snprintf(ip_str, sizeof(ip_str), "%d.%d.%d.%d", - (int)((client_ip >> 0) & 0xFF), (int)((client_ip >> 8) & 0xFF), - (int)((client_ip >> 16) & 0xFF), (int)((client_ip >> 24) & 0xFF)); - s_platform->log_info(TAG, "First client = owner: %s", ip_str); - } - return; - } - if (s_platform && s_platform->log_info) s_platform->log_info(TAG, "Client connected (non-owner)"); -} - -void tollgate_core_client_disconnected(const uint8_t *mac) -{ - if (!s_owner_connected) return; - if (mac && memcmp(s_owner_mac, mac, 6) == 0) { - s_owner_connected = false; - memset(s_owner_mac, 0, sizeof(s_owner_mac)); - if (s_platform && s_platform->log_info) s_platform->log_info(TAG, "Owner disconnected"); - } -} - -bool tollgate_core_is_client_allowed(uint32_t client_ip) -{ - return tg_firewall_is_allowed(client_ip); -} - -bool tollgate_core_is_dns_running(void) -{ - return false; -} - -char *tollgate_core_get_status_json(void) -{ - const int BUFSIZE = 512; - char *json = malloc(BUFSIZE); - if (!json) return NULL; - snprintf(json, BUFSIZE, - "{\"ownerConnected\":%s,\"activeSessions\":%d,\"allowedClients\":%d,\"dnsRunning\":%s}", - s_owner_connected ? "true" : "false", - tg_session_active_count(), - tg_firewall_client_count(), - tollgate_core_is_dns_running() ? "true" : "false"); - return json; -} - -char *tollgate_core_get_config_json(void) -{ - const int BUFSIZE = 512; - char *json = malloc(BUFSIZE); - if (!json) return NULL; - int pos = 0; - pos += snprintf(json + pos, BUFSIZE - pos, "{"); - if (s_platform) { - if (s_platform->get_price_sats) - pos += snprintf(json + pos, BUFSIZE - pos, "\"priceSats\":%d,", (int)s_platform->get_price_sats()); - if (s_platform->get_step_ms) - pos += snprintf(json + pos, BUFSIZE - pos, "\"stepMs\":%d,", (int)s_platform->get_step_ms()); - if (s_platform->get_mint_url) - pos += snprintf(json + pos, BUFSIZE - pos, "\"mintUrl\":\"%s\",", s_platform->get_mint_url()); - if (s_platform->get_metric) - pos += snprintf(json + pos, BUFSIZE - pos, "\"metric\":\"%s\"", s_platform->get_metric()); - } - pos += snprintf(json + pos, BUFSIZE - pos, "}"); - return json; -} - -int tollgate_core_active_session_count(void) -{ - return tg_session_active_count(); -} - -int tollgate_core_allowed_client_count(void) -{ - return tg_firewall_client_count(); -} - -int tollgate_core_firewall_revoke_all(void) -{ - tg_session_revoke_all(); - return tg_firewall_revoke_all(); -} - -void tollgate_core_firewall_set_mining_port(uint16_t port) -{ - tg_firewall_set_mining_port(port); -} - -void tollgate_core_firewall_set_sandbox_mint_access(bool enable) -{ - tg_firewall_set_sandbox_mint_access(enable); -} - -bool tollgate_core_is_owner(uint32_t client_ip) -{ - return s_owner_connected && s_owner_ip == client_ip; -} - -bool tollgate_core_is_owner_connected(void) -{ - return s_owner_connected; -} - -double tollgate_core_get_hashprice(void) -{ - return tg_mining_get_current_hashprice(); -} - -void tollgate_core_set_nbits(uint32_t nbits) -{ - tg_mining_set_current_nbits(nbits); -} - -const void *tollgate_core_get_current_job(void) { return NULL; } -void tollgate_core_set_job(const void *job) { (void)job; } -int tollgate_core_stratum_client_start(void) { return -1; } -void tollgate_core_stratum_client_stop(void) { } -int tollgate_core_stratum_proxy_init(uint16_t port) { (void)port; return -1; } -void tollgate_core_stratum_proxy_get_stats(void *out) { (void)out; } -void tollgate_core_beacon_start(void) { } -void tollgate_core_market_init(void) { } -void tollgate_core_market_on_scan_result(const void *ie_data, int ie_len, const uint8_t *bssid, int rssi) -{ - (void)ie_data; (void)ie_len; (void)bssid; (void)rssi; -} - -const void *tollgate_core_get_sessions_array(void) -{ - return tg_session_get_array(); -} - -int tollgate_core_get_sessions_array_size(void) -{ - return tg_session_get_array_size(); -} - -void *tollgate_core_find_session_by_ip(uint32_t ip) -{ - return tg_session_find_by_ip(ip); -} - -void *tollgate_core_find_session_by_mac(const char *mac) -{ - return tg_session_find_by_mac(mac); -} - -void tollgate_core_session_extend(void *session, uint64_t additional_ms) -{ - tg_session_extend((tg_session_t *)session, additional_ms); -} - -int tollgate_core_session_add_bytes(uint32_t client_ip, uint64_t bytes) -{ - tg_session_add_bytes(client_ip, bytes); - return 0; -} - -void *tollgate_core_session_create(uint32_t client_ip, uint64_t allotment_ms) -{ - return tg_session_create(client_ip, allotment_ms); -} - -void *tollgate_core_session_create_bytes(uint32_t client_ip, uint64_t allotment_bytes) -{ - return tg_session_create_bytes(client_ip, allotment_bytes); -} - -void tollgate_core_session_revoke(void *session) -{ - tg_session_revoke((tg_session_t *)session); -} - -bool tollgate_core_session_is_expired(const void *session) -{ - return tg_session_is_expired((const tg_session_t *)session); -} - -void tollgate_core_firewall_grant(uint32_t client_ip) -{ - tg_firewall_grant(client_ip); -} - -void tollgate_core_firewall_revoke(uint32_t client_ip) -{ - tg_firewall_revoke(client_ip); -} - -int tollgate_core_firewall_get_mac_for_ip(uint32_t client_ip, char *mac_out, int mac_out_size) -{ - return tg_firewall_get_mac_for_ip(client_ip, mac_out, mac_out_size); -} - -int tollgate_core_cashu_decode(const char *token_str, void *out) -{ - return tg_cashu_decode_token(token_str, (tg_cashu_token_t *)out); -} - -int tollgate_core_cashu_check_states(const char *mint_url, const void *token, - void *states, int *state_count) -{ - return tg_cashu_check_proof_states(mint_url, (const tg_cashu_token_t *)token, - (tg_cashu_proof_state_t *)states, state_count); -} - -uint64_t tollgate_core_cashu_allotment(uint64_t amount, uint64_t price, uint64_t step_size) -{ - return tg_cashu_calculate_allotment(amount, price, step_size); -} - -bool tollgate_core_cashu_is_mint_accepted(const char *mint_url) -{ - if (!s_platform) return false; - const char *accepted = s_platform->get_mint_url ? s_platform->get_mint_url() : NULL; - if (!accepted) return false; - if (s_platform->get_accepted_mint_count && s_platform->get_accepted_mint) { - int count = s_platform->get_accepted_mint_count(); - for (int i = 0; i < count; i++) { - if (tg_cashu_is_mint_accepted(mint_url, s_platform->get_accepted_mint(i))) - return true; - } - return false; - } - return tg_cashu_is_mint_accepted(mint_url, accepted); -} - -const char *tollgate_core_cashu_token_mint(const void *token) -{ - const tg_cashu_token_t *t = (const tg_cashu_token_t *)token; - return t->mint_url; -} - -uint64_t tollgate_core_cashu_token_amount(const void *token) -{ - const tg_cashu_token_t *t = (const tg_cashu_token_t *)token; - return t->total_amount; -} - -void tollgate_core_mining_update_hashrate(uint32_t client_ip, bool accepted) -{ - tg_mining_update_hashrate(client_ip, accepted); -} - -const void *tollgate_core_mining_get_client_stats(uint32_t client_ip) -{ - return tg_mining_get_client_stats(client_ip); -} - -double tollgate_core_mining_get_hashprice(void) -{ - return tg_mining_get_current_hashprice(); -} - -uint64_t tollgate_core_mining_shares_to_allotment_ms(double hashrate, double hashprice, - int price, int step_ms) -{ - return tg_mining_shares_to_allotment_ms(hashrate, hashprice, price, step_ms); -} - -uint64_t tollgate_core_mining_shares_to_allotment_bytes(double hashrate, double hashprice, - int price, int step_bytes) -{ - return tg_mining_shares_to_allotment_bytes(hashrate, hashprice, price, step_bytes); -} - -void tollgate_core_mining_set_nbits(uint32_t nbits) -{ - tg_mining_set_current_nbits(nbits); -} - -int tollgate_core_dns_start(uint32_t upstream_dns) -{ - (void)upstream_dns; - return -1; -} - -void tollgate_core_dns_stop(void) { } diff --git a/tollgate_core/src/tollgate_firewall.c b/tollgate_core/src/tollgate_firewall.c deleted file mode 100644 index 8111be8..0000000 --- a/tollgate_core/src/tollgate_firewall.c +++ /dev/null @@ -1,166 +0,0 @@ -#include "tollgate_firewall.h" -#include "tollgate_core.h" -#include "tollgate_platform.h" -#include -#include - -#define FW_MAX_CLIENTS 10 - -static const char *TAG = "tg_fw"; -static uint32_t s_ap_ip; -static uint16_t s_mining_port; -static bool s_sandbox_mint; - -typedef struct { - uint32_t ip; - char mac[TG_FW_MAX_MAC_LEN]; -} fw_client_t; - -static fw_client_t s_clients[FW_MAX_CLIENTS]; -static int s_client_count = 0; - -static void log_fw(const char *verb, uint32_t client_ip, const char *mac) -{ - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->log_info) { - char ip_str[16]; - snprintf(ip_str, sizeof(ip_str), "%d.%d.%d.%d", - (int)((client_ip >> 0) & 0xFF), (int)((client_ip >> 8) & 0xFF), - (int)((client_ip >> 16) & 0xFF), (int)((client_ip >> 24) & 0xFF)); - p->log_info(TAG, "%s %s mac=%s", verb, ip_str, mac ? mac : "unknown"); - } -} - -int tg_firewall_get_mac_for_ip(uint32_t client_ip, char *mac_out, int mac_out_size) -{ - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (!p) return -1; - - if (p->mac_for_ip) { - if (p->mac_for_ip(client_ip, mac_out, mac_out_size)) { - return 0; - } - } - return -1; -} - -int tg_firewall_init(uint32_t ap_ip) -{ - s_ap_ip = ap_ip; - memset(s_clients, 0, sizeof(s_clients)); - s_client_count = 0; - s_mining_port = 0; - s_sandbox_mint = false; - - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->napt_enable) p->napt_enable(ap_ip, true); - - if (p && p->log_info) { - char ip_str[16]; - snprintf(ip_str, sizeof(ip_str), "%d.%d.%d.%d", - (int)((ap_ip >> 0) & 0xFF), (int)((ap_ip >> 8) & 0xFF), - (int)((ap_ip >> 16) & 0xFF), (int)((ap_ip >> 24) & 0xFF)); - p->log_info(TAG, "Firewall initialized AP=%s NAT on, per-client filter", ip_str); - } - return 0; -} - -static fw_client_t *find_client_by_ip(uint32_t client_ip) -{ - for (int i = 0; i < s_client_count; i++) { - if (s_clients[i].ip == client_ip) return &s_clients[i]; - } - return NULL; -} - -static fw_client_t *find_client_by_mac(const char *mac) -{ - for (int i = 0; i < s_client_count; i++) { - if (s_clients[i].mac[0] != '\0' && strcmp(s_clients[i].mac, mac) == 0) { - return &s_clients[i]; - } - } - return NULL; -} - -void tg_firewall_grant(uint32_t client_ip) -{ - fw_client_t *existing = find_client_by_ip(client_ip); - if (existing) return; - - if (s_client_count >= FW_MAX_CLIENTS) { - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->log_warn) p->log_warn(TAG, "Max clients, cannot grant"); - return; - } - - fw_client_t *c = &s_clients[s_client_count]; - c->ip = client_ip; - c->mac[0] = '\0'; - tg_firewall_get_mac_for_ip(client_ip, c->mac, sizeof(c->mac)); - s_client_count++; - - log_fw("granted", client_ip, c->mac[0] ? c->mac : "unknown"); -} - -void tg_firewall_revoke(uint32_t client_ip) -{ - for (int i = 0; i < s_client_count; i++) { - if (s_clients[i].ip == client_ip) { - log_fw("revoked", client_ip, s_clients[i].mac[0] ? s_clients[i].mac : "unknown"); - s_clients[i] = s_clients[s_client_count - 1]; - s_client_count--; - return; - } - } -} - -int tg_firewall_revoke_all(void) -{ - s_client_count = 0; - memset(s_clients, 0, sizeof(s_clients)); - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->log_info) p->log_info(TAG, "All clients revoked"); - return 0; -} - -bool tg_firewall_is_allowed(uint32_t client_ip) -{ - return find_client_by_ip(client_ip) != NULL; -} - -bool tg_firewall_is_mac_allowed(const char *mac) -{ - return find_client_by_mac(mac) != NULL; -} - -int tg_firewall_client_count(void) -{ - return s_client_count; -} - -void tg_firewall_set_mining_port(uint16_t port) -{ - s_mining_port = port; -} - -void tg_firewall_set_sandbox_mint_access(bool enable) -{ - s_sandbox_mint = enable; -} - -int tg_firewall_filter_packet(const uint8_t *payload, int payload_len) -{ - if (payload_len < 20) return -1; - - uint32_t src_ip = (uint32_t)payload[12] | ((uint32_t)payload[13] << 8) | - ((uint32_t)payload[14] << 16) | ((uint32_t)payload[15] << 24); - - uint32_t ap_subnet = s_ap_ip & 0x00FFFFFF; - uint32_t src_subnet = src_ip & 0x00FFFFFF; - if (src_subnet != ap_subnet) return 1; - - if (tg_firewall_is_allowed(src_ip)) return 1; - - return 0; -} diff --git a/tollgate_core/src/tollgate_firewall.h b/tollgate_core/src/tollgate_firewall.h deleted file mode 100644 index 7df8a45..0000000 --- a/tollgate_core/src/tollgate_firewall.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef TOLLGATE_CORE_FIREWALL_H -#define TOLLGATE_CORE_FIREWALL_H - -#include -#include - -#define TG_FW_MAX_MAC_LEN 18 - -int tg_firewall_init(uint32_t ap_ip); -void tg_firewall_grant(uint32_t client_ip); -void tg_firewall_revoke(uint32_t client_ip); -int tg_firewall_revoke_all(void); -bool tg_firewall_is_allowed(uint32_t client_ip); -bool tg_firewall_is_mac_allowed(const char *mac); -int tg_firewall_client_count(void); -int tg_firewall_get_mac_for_ip(uint32_t client_ip, char *mac_out, int mac_out_size); -void tg_firewall_set_mining_port(uint16_t port); -void tg_firewall_set_sandbox_mint_access(bool enable); -int tg_firewall_filter_packet(const uint8_t *payload, int payload_len); - -#endif diff --git a/tollgate_core/src/tollgate_mining.c b/tollgate_core/src/tollgate_mining.c deleted file mode 100644 index 8a4a778..0000000 --- a/tollgate_core/src/tollgate_mining.c +++ /dev/null @@ -1,171 +0,0 @@ -#include "tollgate_mining.h" -#include "tollgate_core.h" -#include "tollgate_platform.h" -#include -#include - -static const char *TAG = "tg_mining"; - -static tg_mining_client_stats_t s_clients[TG_MINING_MAX_CLIENTS]; -static int s_client_count = 0; -static double s_current_hashprice = 0.0; -static uint32_t s_current_nbits = 0; -static uint64_t s_current_difficulty = 1; - -static int64_t get_time_ms(void) -{ - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->get_time_ms) return p->get_time_ms(); - return 0; -} - -uint64_t tg_mining_nbits_to_difficulty(uint32_t nbits) -{ - if (nbits == 0) return (uint64_t)-1; - - uint32_t exponent = (nbits >> 24) & 0xFF; - uint32_t mantissa = nbits & 0x007FFFFF; - - if (exponent <= 3) { - mantissa >>= (8 * (3 - exponent)); - if (mantissa == 0) return (uint64_t)-1; - return 0x00000000FFFF0000ULL / mantissa; - } - - uint64_t target = (uint64_t)mantissa << (8 * (exponent - 3)); - if (target == 0) return (uint64_t)-1; - - uint64_t pdiff = 0x00000000FFFF0000ULL; - uint64_t diff = pdiff / target; - if (diff == 0) diff = 1; - return diff; -} - -double tg_mining_calculate_hashprice(uint32_t nbits) -{ - uint64_t diff = tg_mining_nbits_to_difficulty(nbits); - if (diff == 0 || diff == (uint64_t)-1) return 0.0; - - double network_hashrate_th = (double)diff * 4294967296.0 / 1e12; - double daily_sats = (double)TG_MINING_BLOCK_SUBSIDY_SATS * (double)TG_MINING_BLOCKS_PER_DAY; - double sats_per_th_day = daily_sats / network_hashrate_th; - return sats_per_th_day / 1000.0; -} - -double tg_mining_calculate_hashprice_override(uint64_t sats_per_ghs_day) -{ - return (double)sats_per_ghs_day; -} - -int tg_mining_validate_share(const uint8_t *header80, uint32_t nonce, const uint8_t *target, int target_len) -{ - (void)header80; - (void)nonce; - (void)target; - (void)target_len; - return 0; -} - -uint64_t tg_mining_shares_to_allotment_ms(double hashrate_ghs, double hashprice_sats_per_ghs_s, - int price_per_step, int step_size_ms) -{ - if (hashrate_ghs <= 0.0 || hashprice_sats_per_ghs_s <= 0.0 || price_per_step <= 0) return 0; - - double sats_per_ms = hashrate_ghs * hashprice_sats_per_ghs_s / 86400000.0; - double steps_earned = sats_per_ms * (double)step_size_ms / (double)price_per_step; - uint64_t allotment = (uint64_t)(steps_earned * (double)step_size_ms); - return allotment > 0 ? allotment : 1; -} - -uint64_t tg_mining_shares_to_allotment_bytes(double hashrate_ghs, double hashprice_sats_per_ghs_s, - int price_per_step, int step_size_bytes) -{ - if (hashrate_ghs <= 0.0 || hashprice_sats_per_ghs_s <= 0.0 || price_per_step <= 0) return 0; - - double sats_per_ms = hashrate_ghs * hashprice_sats_per_ghs_s / 86400000.0; - double steps_earned = sats_per_ms * 1000.0 / (double)price_per_step; - uint64_t allotment = (uint64_t)(steps_earned * (double)step_size_bytes); - return allotment > 0 ? allotment : 1; -} - -tg_mining_client_stats_t *tg_mining_get_or_create_client(uint32_t client_ip) -{ - for (int i = 0; i < s_client_count; i++) { - if (s_clients[i].ip == client_ip) return &s_clients[i]; - } - - if (s_client_count >= TG_MINING_MAX_CLIENTS) { - for (int i = 0; i < TG_MINING_MAX_CLIENTS; i++) { - int64_t age = get_time_ms() - s_clients[i].last_share_time_ms; - if (age > TG_MINING_SHARE_WINDOW_S * 2000) { - memset(&s_clients[i], 0, sizeof(tg_mining_client_stats_t)); - s_clients[i].ip = client_ip; - s_clients[i].first_share_time_ms = get_time_ms(); - return &s_clients[i]; - } - } - return NULL; - } - - tg_mining_client_stats_t *c = &s_clients[s_client_count]; - memset(c, 0, sizeof(tg_mining_client_stats_t)); - c->ip = client_ip; - c->first_share_time_ms = get_time_ms(); - s_client_count++; - return c; -} - -void tg_mining_update_hashrate(uint32_t client_ip, bool accepted) -{ - tg_mining_client_stats_t *stats = tg_mining_get_or_create_client(client_ip); - if (!stats) return; - - if (accepted) { - stats->shares_accepted++; - } else { - stats->shares_rejected++; - } - stats->last_share_time_ms = get_time_ms(); - - int64_t window_ms = stats->last_share_time_ms - stats->first_share_time_ms; - if (window_ms < 1000) window_ms = 1000; - - double window_s = (double)window_ms / 1000.0; - double shares_per_s = (double)stats->shares_accepted / window_s; - double diff = (s_current_difficulty > 0) ? (double)s_current_difficulty : 1.0; - stats->hashrate_ghs = shares_per_s * diff * 4294967296.0 / 1e9; -} - -const tg_mining_client_stats_t *tg_mining_get_client_stats(uint32_t client_ip) -{ - for (int i = 0; i < s_client_count; i++) { - if (s_clients[i].ip == client_ip) return &s_clients[i]; - } - return NULL; -} - -double tg_mining_get_current_hashprice(void) -{ - return s_current_hashprice; -} - -void tg_mining_set_current_nbits(uint32_t nbits) -{ - s_current_nbits = nbits; - s_current_difficulty = tg_mining_nbits_to_difficulty(nbits); - s_current_hashprice = tg_mining_calculate_hashprice(nbits); - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->log_info) p->log_info(TAG, "nbits: 0x%08lx, diff=%llu, hashprice=%.6f sat/GH/s/day", - (unsigned long)nbits, (unsigned long long)s_current_difficulty, s_current_hashprice); -} - -void tg_mining_init(void) -{ - memset(s_clients, 0, sizeof(s_clients)); - s_client_count = 0; - s_current_hashprice = 0.0; - s_current_nbits = 0; - s_current_difficulty = 1; - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->log_info) p->log_info(TAG, "Mining payment initialized"); -} diff --git a/tollgate_core/src/tollgate_mining.h b/tollgate_core/src/tollgate_mining.h deleted file mode 100644 index 39681a5..0000000 --- a/tollgate_core/src/tollgate_mining.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef TOLLGATE_CORE_MINING_H -#define TOLLGATE_CORE_MINING_H - -#include -#include - -#define TG_MINING_SHARE_WINDOW_S 30 -#define TG_MINING_BLOCK_SUBSIDY_SATS 312500000ULL -#define TG_MINING_BLOCKS_PER_DAY 144ULL -#define TG_MINING_MAX_CLIENTS 10 - -typedef struct { - uint32_t ip; - uint64_t shares_accepted; - uint64_t shares_rejected; - int64_t first_share_time_ms; - int64_t last_share_time_ms; - double hashrate_ghs; -} tg_mining_client_stats_t; - -uint64_t tg_mining_nbits_to_difficulty(uint32_t nbits); -double tg_mining_calculate_hashprice(uint32_t nbits); -double tg_mining_calculate_hashprice_override(uint64_t sats_per_ghs_day); -int tg_mining_validate_share(const uint8_t *header80, uint32_t nonce, const uint8_t *target, int target_len); -uint64_t tg_mining_shares_to_allotment_ms(double hashrate_ghs, double hashprice, int price, int step_ms); -uint64_t tg_mining_shares_to_allotment_bytes(double hashrate_ghs, double hashprice, int price, int step_bytes); -tg_mining_client_stats_t *tg_mining_get_or_create_client(uint32_t client_ip); -void tg_mining_update_hashrate(uint32_t client_ip, bool accepted); -const tg_mining_client_stats_t *tg_mining_get_client_stats(uint32_t client_ip); -double tg_mining_get_current_hashprice(void); -void tg_mining_set_current_nbits(uint32_t nbits); -void tg_mining_init(void); - -#endif diff --git a/tollgate_core/src/tollgate_session.c b/tollgate_core/src/tollgate_session.c deleted file mode 100644 index 667dbd0..0000000 --- a/tollgate_core/src/tollgate_session.c +++ /dev/null @@ -1,220 +0,0 @@ -#include "tollgate_session.h" -#include "tollgate_core.h" -#include "tollgate_platform.h" -#include "tollgate_firewall.h" -#include -#include - -static const char *TAG = "tg_session"; -static tg_session_t s_sessions[TG_SESSION_MAX_CLIENTS]; -static int s_session_count = 0; - -static void format_ip(uint32_t ip, char *buf, int buf_len) -{ - snprintf(buf, buf_len, "%d.%d.%d.%d", - (int)((ip >> 0) & 0xFF), (int)((ip >> 8) & 0xFF), - (int)((ip >> 16) & 0xFF), (int)((ip >> 24) & 0xFF)); -} - -static int64_t get_time_ms(void) -{ - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->get_time_ms) return p->get_time_ms(); - return 0; -} - -static void log_session(const char *verb, uint32_t client_ip, const char *mac, const char *detail) -{ - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->log_info) { - char ip_str[16]; - format_ip(client_ip, ip_str, sizeof(ip_str)); - p->log_info(TAG, "%s: %s mac=%s %s", verb, ip_str, mac ? mac : "unknown", detail ? detail : ""); - } -} - -int tg_session_init(void) -{ - memset(s_sessions, 0, sizeof(s_sessions)); - s_session_count = 0; - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->log_info) p->log_info(TAG, "Session manager initialized"); - return 0; -} - -static void populate_mac(tg_session_t *session, uint32_t client_ip) -{ - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->mac_for_ip) { - if (!p->mac_for_ip(client_ip, session->mac, sizeof(session->mac))) { - session->mac[0] = '\0'; - } - } else { - session->mac[0] = '\0'; - } -} - -tg_session_t *tg_session_create(uint32_t client_ip, uint64_t allotment_ms) -{ - tg_session_t *existing = tg_session_find_by_ip(client_ip); - if (existing) { - tg_session_extend(existing, allotment_ms); - return existing; - } - - if (s_session_count >= TG_SESSION_MAX_CLIENTS) { - for (int i = 0; i < TG_SESSION_MAX_CLIENTS; i++) { - if (!s_sessions[i].active || tg_session_is_expired(&s_sessions[i])) { - tg_session_revoke(&s_sessions[i]); - break; - } - } - } - - for (int i = 0; i < TG_SESSION_MAX_CLIENTS; i++) { - if (!s_sessions[i].active) { - s_sessions[i].client_ip = client_ip; - s_sessions[i].allotment_ms = allotment_ms; - s_sessions[i].start_time_ms = get_time_ms(); - s_sessions[i].active = true; - s_sessions[i].payment_method = TG_PAYMENT_CASHU; - populate_mac(&s_sessions[i], client_ip); - - s_session_count++; - tg_firewall_grant(client_ip); - - char detail[64]; - snprintf(detail, sizeof(detail), "allotment=%llums", (unsigned long long)allotment_ms); - log_session("created", client_ip, - s_sessions[i].mac[0] ? s_sessions[i].mac : "unknown", detail); - return &s_sessions[i]; - } - } - - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->log_warn) p->log_warn(TAG, "No free session slots"); - return NULL; -} - -tg_session_t *tg_session_create_bytes(uint32_t client_ip, uint64_t allotment_bytes) -{ - tg_session_t *s = tg_session_create(client_ip, 0); - if (s) { - s->allotment_bytes = allotment_bytes; - s->bytes_consumed = 0; - s->allotment_ms = (uint64_t)-1; - s->payment_method = TG_PAYMENT_BYTES; - char detail[64]; - snprintf(detail, sizeof(detail), "allotment=%llu bytes", (unsigned long long)allotment_bytes); - log_session("bytes session", client_ip, s->mac[0] ? s->mac : "unknown", detail); - } - return s; -} - -void tg_session_add_bytes(uint32_t client_ip, uint64_t bytes) -{ - tg_session_t *s = tg_session_find_by_ip(client_ip); - if (s && s->active) { - s->bytes_consumed += bytes; - } -} - -tg_session_t *tg_session_find_by_ip(uint32_t client_ip) -{ - for (int i = 0; i < TG_SESSION_MAX_CLIENTS; i++) { - if (s_sessions[i].active && s_sessions[i].client_ip == client_ip) { - return &s_sessions[i]; - } - } - return NULL; -} - -tg_session_t *tg_session_find_by_mac(const char *mac) -{ - for (int i = 0; i < TG_SESSION_MAX_CLIENTS; i++) { - if (s_sessions[i].active && s_sessions[i].mac[0] != '\0' && - strcmp(s_sessions[i].mac, mac) == 0) { - return &s_sessions[i]; - } - } - return NULL; -} - -void tg_session_extend(tg_session_t *session, uint64_t additional_ms) -{ - if (!session || !session->active) return; - session->allotment_ms += additional_ms; - char detail[64]; - snprintf(detail, sizeof(detail), "+%llums (total=%llu)", - (unsigned long long)additional_ms, (unsigned long long)session->allotment_ms); - log_session("extended", session->client_ip, - session->mac[0] ? session->mac : "unknown", detail); -} - -bool tg_session_is_expired(const tg_session_t *session) -{ - if (!session || !session->active) return true; - - const tollgate_platform_t *p = tollgate_core_get_platform(); - if (p && p->get_metric) { - const char *metric = p->get_metric(); - if (metric && strcmp(metric, "bytes") == 0) { - return session->bytes_consumed >= session->allotment_bytes; - } - } - - int64_t elapsed = get_time_ms() - session->start_time_ms; - return elapsed >= (int64_t)session->allotment_ms; -} - -static void check_expiry(void) -{ - for (int i = 0; i < TG_SESSION_MAX_CLIENTS; i++) { - if (s_sessions[i].active && tg_session_is_expired(&s_sessions[i])) { - log_session("expired", s_sessions[i].client_ip, - s_sessions[i].mac[0] ? s_sessions[i].mac : "unknown", NULL); - tg_session_revoke(&s_sessions[i]); - } - } -} - -void tg_session_revoke(tg_session_t *session) -{ - if (!session || !session->active) return; - tg_firewall_revoke(session->client_ip); - session->active = false; - s_session_count--; -} - -void tg_session_revoke_all(void) -{ - for (int i = 0; i < TG_SESSION_MAX_CLIENTS; i++) { - if (s_sessions[i].active) { - tg_session_revoke(&s_sessions[i]); - } - } -} - -int tg_session_active_count(void) -{ - int count = 0; - for (int i = 0; i < TG_SESSION_MAX_CLIENTS; i++) { - if (s_sessions[i].active) count++; - } - return count; -} - -void tg_session_tick(void) -{ - check_expiry(); -} - -tg_session_t *tg_session_get_array(void) -{ - return s_sessions; -} - -int tg_session_get_array_size(void) -{ - return TG_SESSION_MAX_CLIENTS; -} diff --git a/tollgate_core/src/tollgate_session.h b/tollgate_core/src/tollgate_session.h deleted file mode 100644 index 4008b24..0000000 --- a/tollgate_core/src/tollgate_session.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef TOLLGATE_CORE_SESSION_H -#define TOLLGATE_CORE_SESSION_H - -#include -#include - -#define TG_SESSION_MAX_CLIENTS 10 -#define TG_SESSION_MAX_MAC_LEN 18 - -typedef enum { - TG_PAYMENT_CASHU, - TG_PAYMENT_MINING, - TG_PAYMENT_BYTES -} tg_payment_method_t; - -typedef struct { - uint32_t client_ip; - char mac[TG_SESSION_MAX_MAC_LEN]; - uint64_t allotment_ms; - int64_t start_time_ms; - uint64_t allotment_bytes; - uint64_t bytes_consumed; - tg_payment_method_t payment_method; - bool active; -} tg_session_t; - -int tg_session_init(void); -tg_session_t *tg_session_create(uint32_t client_ip, uint64_t allotment_ms); -tg_session_t *tg_session_create_bytes(uint32_t client_ip, uint64_t allotment_bytes); -void tg_session_add_bytes(uint32_t client_ip, uint64_t bytes); -tg_session_t *tg_session_find_by_ip(uint32_t client_ip); -tg_session_t *tg_session_find_by_mac(const char *mac); -void tg_session_extend(tg_session_t *session, uint64_t additional_ms); -bool tg_session_is_expired(const tg_session_t *session); -void tg_session_revoke(tg_session_t *session); -void tg_session_revoke_all(void); -int tg_session_active_count(void); -void tg_session_tick(void); -tg_session_t *tg_session_get_array(void); -int tg_session_get_array_size(void); - -#endif -- cgit v1.2.3