upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/main/tollgate_api.c
blob: 71056cf92c5bc3428e4d1fb4f0100ebdeb8bfdb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#include "tollgate_api.h"
#include "tollgate_core.h"
#include "tollgate_core_firewall.h"
#include "tollgate_core_session.h"
#include "tollgate_core_cashu.h"
#include "config.h"
#include "nucula_wallet.h"
#include "esp_log.h"
#include "cJSON.h"
#include "lwip/sockets.h"
#include "lwip/netdb.h"
#include "freertos/task.h"
#include <string.h>

static const char *TAG = "tollgate_api";
static httpd_handle_t s_api_server = NULL;

static const char *TOLLGATE_PUBKEY = "0000000000000000000000000000000000000000000000000000000000000000";

static esp_err_t get_client_ip(httpd_req_t *req, uint32_t *ip_out)
{
    int sockfd = httpd_req_to_sockfd(req);
    struct sockaddr_in addr;
    socklen_t addr_len = sizeof(addr);
    if (getpeername(sockfd, (struct sockaddr *)&addr, &addr_len) == 0) {
        *ip_out = addr.sin_addr.s_addr;
        return ESP_OK;
    }
    return ESP_FAIL;
}

static cJSON *create_notice(const char *level, const char *code, const char *content)
{
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "kind", 21023);
    cJSON_AddStringToObject(root, "pubkey", TOLLGATE_PUBKEY);
    cJSON *tags = cJSON_CreateArray();
    cJSON *level_tag = cJSON_CreateArray();
    cJSON_AddItemToArray(level_tag, cJSON_CreateString("level"));
    cJSON_AddItemToArray(level_tag, cJSON_CreateString(level));
    cJSON_AddItemToArray(tags, level_tag);
    cJSON *code_tag = cJSON_CreateArray();
    cJSON_AddItemToArray(code_tag, cJSON_CreateString("code"));
    cJSON_AddItemToArray(code_tag, cJSON_CreateString(code));
    cJSON_AddItemToArray(tags, code_tag);
    cJSON_AddItemToObject(root, "tags", tags);
    cJSON_AddStringToObject(root, "content", content);
    return root;
}

static cJSON *create_session_event(uint32_t client_ip, uint64_t allotment_ms)
{
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "kind", 1022);
    cJSON_AddStringToObject(root, "pubkey", TOLLGATE_PUBKEY);

    cJSON *tags = cJSON_CreateArray();

    cJSON *p_tag = cJSON_CreateArray();
    cJSON_AddItemToArray(p_tag, cJSON_CreateString("p"));
    cJSON_AddItemToArray(p_tag, cJSON_CreateString("unknown"));
    cJSON_AddItemToArray(tags, p_tag);

    esp_ip4_addr_t ip = { .addr = client_ip };
    char ip_str[16];
    snprintf(ip_str, sizeof(ip_str), IPSTR, IP2STR(&ip));
    cJSON *dev_tag = cJSON_CreateArray();
    cJSON_AddItemToArray(dev_tag, cJSON_CreateString("device-identifier"));
    cJSON_AddItemToArray(dev_tag, cJSON_CreateString("mac"));
    cJSON_AddItemToArray(dev_tag, cJSON_CreateString(ip_str));
    cJSON_AddItemToArray(tags, dev_tag);

    cJSON *allotment_tag = cJSON_CreateArray();
    cJSON_AddItemToArray(allotment_tag, cJSON_CreateString("allotment"));
    char allotment_str[32];
    snprintf(allotment_str, sizeof(allotment_str), "%llu", (unsigned long long)allotment_ms);
    cJSON_AddItemToArray(allotment_tag, cJSON_CreateString(allotment_str));
    cJSON_AddItemToArray(tags, allotment_tag);

    cJSON *metric_tag = cJSON_CreateArray();
    cJSON_AddItemToArray(metric_tag, cJSON_CreateString("metric"));
    const tollgate_config_t *mcfg = tollgate_config_get();
    cJSON_AddItemToArray(metric_tag, cJSON_CreateString(mcfg->metric[0] ? mcfg->metric : "milliseconds"));
    cJSON_AddItemToArray(tags, metric_tag);

    cJSON_AddItemToObject(root, "tags", tags);
    cJSON_AddStringToObject(root, "content", "");
    return root;
}

static esp_err_t api_get_discovery(httpd_req_t *req)
{
    const tollgate_config_t *cfg = tollgate_config_get();

    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "kind", 10021);
    cJSON_AddStringToObject(root, "pubkey", TOLLGATE_PUBKEY);

    cJSON *tags = cJSON_CreateArray();

    cJSON *metric_tag = cJSON_CreateArray();
    cJSON_AddItemToArray(metric_tag, cJSON_CreateString("metric"));
    cJSON_AddItemToArray(metric_tag, cJSON_CreateString(cfg->metric[0] ? cfg->metric : "milliseconds"));
    cJSON_AddItemToArray(tags, metric_tag);

    cJSON *step_tag = cJSON_CreateArray();
    cJSON_AddItemToArray(step_tag, cJSON_CreateString("step_size"));
    char step_str[32];
    bool is_bytes = (strcmp(cfg->metric, "bytes") == 0);
    snprintf(step_str, sizeof(step_str), "%d", is_bytes ? cfg->step_size_bytes : cfg->step_size_ms);
    cJSON_AddItemToArray(step_tag, cJSON_CreateString(step_str));
    cJSON_AddItemToArray(tags, step_tag);

    cJSON *price_tag = cJSON_CreateArray();
    cJSON_AddItemToArray(price_tag, cJSON_CreateString("price_per_step"));
    cJSON_AddItemToArray(price_tag, cJSON_CreateString("cashu"));
    char price_str[32];
    snprintf(price_str, sizeof(price_str), "%d", cfg->price_per_step);
    cJSON_AddItemToArray(price_tag, cJSON_CreateString(price_str));
    cJSON_AddItemToArray(price_tag, cJSON_CreateString("sat"));
    cJSON_AddItemToArray(price_tag, cJSON_CreateString(cfg->mint_url));
    cJSON_AddItemToArray(price_tag, cJSON_CreateString("1"));
    cJSON_AddItemToArray(tags, price_tag);

    cJSON *tips_tag = cJSON_CreateArray();
    cJSON_AddItemToArray(tips_tag, cJSON_CreateString("tips"));
    cJSON_AddItemToArray(tips_tag, cJSON_CreateString("1"));
    cJSON_AddItemToArray(tips_tag, cJSON_CreateString("2"));
    cJSON_AddItemToArray(tips_tag, cJSON_CreateString("5"));
    cJSON_AddItemToArray(tags, tips_tag);

    cJSON_AddItemToObject(root, "tags", tags);
    cJSON_AddStringToObject(root, "content", "");

    char *json = cJSON_PrintUnformatted(root);
    httpd_resp_set_type(req, "application/json");
    httpd_resp_send(req, json, strlen(json));
    cJSON_free(json);
    cJSON_Delete(root);
    return ESP_OK;
}

static esp_err_t api_post_payment(httpd_req_t *req)
{
    uint32_t client_ip = 0;
    get_client_ip(req, &client_ip);

    int content_len = req->content_len;
    if (content_len <= 0 || content_len > 16384) {
        cJSON *notice = create_notice("error", "payment-error-invalid", "Invalid request body");
        char *json = cJSON_PrintUnformatted(notice);
        httpd_resp_set_status(req, "400 Bad Request");
        httpd_resp_set_type(req, "application/json");
        httpd_resp_send(req, json, strlen(json));
        cJSON_free(json);
        cJSON_Delete(notice);
        return ESP_OK;
    }

    char *body = malloc(content_len + 1);
    if (!body) {
        cJSON *notice = create_notice("error", "session-error", "Out of memory");
        char *json = cJSON_PrintUnformatted(notice);
        httpd_resp_set_status(req, "503 Service Unavailable");
        httpd_resp_set_type(req, "application/json");
        httpd_resp_send(req, json, strlen(json));
        cJSON_free(json);
        cJSON_Delete(notice);
        return ESP_OK;
    }
    int received = 0;
    int total = 0;
    while (total < content_len) {
        received = httpd_req_recv(req, body + total, content_len - total);
        if (received <= 0) {
            free(body);
            httpd_resp_set_status(req, "400 Bad Request");
            httpd_resp_set_type(req, "text/plain");
            httpd_resp_send(req, "bad request", 11);
            return ESP_OK;
        }
        total += received;
    }
    body[total] = '\0';

    ESP_LOGI(TAG, "Payment received: %d bytes", total);

    esp_err_t err = tollgate_core_process_payment(client_ip, body);
    free(body);

    if (err != ESP_OK) {
        cJSON *notice = create_notice("error", "payment-error", "Payment processing failed");
        char *json = cJSON_PrintUnformatted(notice);
        httpd_resp_set_status(req, "402 Payment Required");
        httpd_resp_set_type(req, "application/json");
        httpd_resp_send(req, json, strlen(json));
        cJSON_free(json);
        cJSON_Delete(notice);
        return ESP_OK;
    }

    const tollgate_config_t *cfg = tollgate_config_get();
    uint64_t allotment = 0;
    cJSON *session_event = create_session_event(client_ip, allotment);
    char *json = cJSON_PrintUnformatted(session_event);
    httpd_resp_set_type(req, "application/json");
    httpd_resp_send(req, json, strlen(json));
    cJSON_free(json);
    cJSON_Delete(session_event);
    return ESP_OK;
}

static esp_err_t api_get_usage(httpd_req_t *req)
{
    uint32_t client_ip = 0;
    get_client_ip(req, &client_ip);

    char *status_json = tollgate_core_get_status_json();
    if (status_json) {
        httpd_resp_set_type(req, "application/json");
        httpd_resp_send(req, status_json, strlen(status_json));
        cJSON_free(status_json);
    } else {
        httpd_resp_set_type(req, "text/plain");
        httpd_resp_send(req, "{}", 2);
    }
    return ESP_OK;
}

static esp_err_t api_get_whoami(httpd_req_t *req)
{
    uint32_t client_ip = 0;
    char resp[96];
    if (get_client_ip(req, &client_ip) == ESP_OK) {
        esp_ip4_addr_t ip = { .addr = client_ip };
        snprintf(resp, sizeof(resp), "ip=" IPSTR, IP2STR(&ip));
    } else {
        snprintf(resp, sizeof(resp), "ip=unknown");
    }
    httpd_resp_set_type(req, "text/plain");
    httpd_resp_send(req, resp, strlen(resp));
    return ESP_OK;
}

static esp_err_t api_get_wallet(httpd_req_t *req)
{
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "balance", (double)nucula_wallet_balance());
    cJSON_AddNumberToObject(root, "proof_count", nucula_wallet_proof_count());

    char *proofs_json = nucula_wallet_proofs_json();
    if (proofs_json) {
        cJSON *proofs = cJSON_Parse(proofs_json);
        free(proofs_json);
        cJSON_AddItemToObject(root, "proofs", proofs);
    } else {
        cJSON_AddItemToObject(root, "proofs", cJSON_CreateArray());
    }

    char *json = cJSON_PrintUnformatted(root);
    httpd_resp_set_type(req, "application/json");
    httpd_resp_send(req, json, strlen(json));
    cJSON_free(json);
    cJSON_Delete(root);
    return ESP_OK;
}

static esp_err_t api_post_wallet_swap(httpd_req_t *req)
{
    if (nucula_wallet_balance() == 0) {
        httpd_resp_set_status(req, "400 Bad Request");
        httpd_resp_set_type(req, "application/json");
        httpd_resp_send(req, "{\"error\":\"no proofs to swap\"}", 27);
        return ESP_OK;
    }

    nucula_wallet_print_status();

    esp_err_t err = nucula_wallet_swap_all();
    if (err != ESP_OK) {
        httpd_resp_set_status(req, "502 Bad Gateway");
        httpd_resp_set_type(req, "application/json");
        httpd_resp_send(req, "{\"error\":\"swap failed\"}", 21);
        return ESP_OK;
    }

    nucula_wallet_print_status();

    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "balance", (double)nucula_wallet_balance());
    cJSON_AddNumberToObject(root, "proof_count", nucula_wallet_proof_count());
    char *json = cJSON_PrintUnformatted(root);
    httpd_resp_set_type(req, "application/json");
    httpd_resp_send(req, json, strlen(json));
    cJSON_free(json);
    cJSON_Delete(root);
    return ESP_OK;
}

static esp_err_t api_post_wallet_send(httpd_req_t *req)
{
    int content_len = req->content_len;
    if (content_len <= 0 || content_len > 32) {
        httpd_resp_set_status(req, "400 Bad Request");
        httpd_resp_send(req, "invalid amount", 14);
        return ESP_OK;
    }

    char body[32];
    int total = 0;
    while (total < content_len) {
        int r = httpd_req_recv(req, body + total, content_len - total);
        if (r <= 0) { httpd_resp_send_500(req); return ESP_OK; }
        total += r;
    }
    body[total] = '\0';

    uint64_t amount = strtoull(body, NULL, 10);
    if (amount == 0) {
        httpd_resp_set_status(req, "400 Bad Request");
        httpd_resp_send(req, "invalid amount", 14);
        return ESP_OK;
    }

    char token[4096];
    esp_err_t err = nucula_wallet_send(amount, token, sizeof(token));
    if (err != ESP_OK) {
        httpd_resp_set_status(req, "402 Payment Required");
        httpd_resp_set_type(req, "text/plain");
        httpd_resp_send(req, "insufficient balance", 20);
        return ESP_OK;
    }

    httpd_resp_set_type(req, "text/plain");
    httpd_resp_send(req, token, strlen(token));
    return ESP_OK;
}

static esp_err_t api_grant_access(httpd_req_t *req)
{
    uint32_t client_ip = 0;
    if (get_client_ip(req, &client_ip) == ESP_OK) {
        tollgate_core_fw_grant(client_ip);
    }
    httpd_resp_set_type(req, "application/json");
    httpd_resp_send(req, "{\"status\":\"granted\"}", 20);
    return ESP_OK;
}

static esp_err_t api_reset_auth(httpd_req_t *req)
{
    tollgate_core_session_revoke_all();
    tollgate_core_fw_revoke_all();
    httpd_resp_set_type(req, "application/json");
    httpd_resp_send(req, "{\"status\":\"reset\"}", 18);
    return ESP_OK;
}

static esp_err_t api_get_portal_config(httpd_req_t *req)
{
    char *cfg_json = tollgate_core_get_config_json();
    if (cfg_json) {
        httpd_resp_set_type(req, "application/json");
        httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
        httpd_resp_send(req, cfg_json, strlen(cfg_json));
        cJSON_free(cfg_json);
    } else {
        httpd_resp_set_type(req, "application/json");
        httpd_resp_send(req, "{}", 2);
    }
    return ESP_OK;
}

static const httpd_uri_t uri_discovery = { .uri = "/", .method = HTTP_GET, .handler = api_get_discovery };
static const httpd_uri_t uri_payment = { .uri = "/", .method = HTTP_POST, .handler = api_post_payment };
static const httpd_uri_t uri_usage = { .uri = "/usage", .method = HTTP_GET, .handler = api_get_usage };
static const httpd_uri_t uri_whoami = { .uri = "/whoami", .method = HTTP_GET, .handler = api_get_whoami };
static const httpd_uri_t uri_wallet = { .uri = "/wallet", .method = HTTP_GET, .handler = api_get_wallet };
static const httpd_uri_t uri_wallet_swap = { .uri = "/wallet/swap", .method = HTTP_POST, .handler = api_post_wallet_swap };
static const httpd_uri_t uri_wallet_send = { .uri = "/wallet/send", .method = HTTP_POST, .handler = api_post_wallet_send };
static const httpd_uri_t uri_grant = { .uri = "/grant_access", .method = HTTP_GET, .handler = api_grant_access };
static const httpd_uri_t uri_reset = { .uri = "/reset_authentication", .method = HTTP_GET, .handler = api_reset_auth };
static const httpd_uri_t uri_portal_config = { .uri = "/portal-config", .method = HTTP_GET, .handler = api_get_portal_config };

esp_err_t tollgate_api_start(void)
{
    if (s_api_server) return ESP_OK;

    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
    config.server_port = 2121;
    config.ctrl_port = 32769;
    config.max_uri_handlers = 16;
    config.stack_size = 16384;

    esp_err_t ret = httpd_start(&s_api_server, &config);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to start API server: %s", esp_err_to_name(ret));
        return ret;
    }

    ret = httpd_register_uri_handler(s_api_server, &uri_discovery);
    if (ret != ESP_OK) ESP_LOGE(TAG, "Failed to register discovery: %s", esp_err_to_name(ret));
    ret = httpd_register_uri_handler(s_api_server, &uri_payment);
    if (ret != ESP_OK) ESP_LOGE(TAG, "Failed to register payment: %s", esp_err_to_name(ret));
    ret = httpd_register_uri_handler(s_api_server, &uri_usage);
    if (ret != ESP_OK) ESP_LOGE(TAG, "Failed to register usage: %s", esp_err_to_name(ret));
    ret = httpd_register_uri_handler(s_api_server, &uri_whoami);
    if (ret != ESP_OK) ESP_LOGE(TAG, "Failed to register whoami: %s", esp_err_to_name(ret));
    ret = httpd_register_uri_handler(s_api_server, &uri_wallet);
    if (ret != ESP_OK) ESP_LOGE(TAG, "Failed to register wallet: %s", esp_err_to_name(ret));
    ret = httpd_register_uri_handler(s_api_server, &uri_wallet_swap);
    if (ret != ESP_OK) ESP_LOGE(TAG, "Failed to register wallet_swap: %s", esp_err_to_name(ret));
    ret = httpd_register_uri_handler(s_api_server, &uri_wallet_send);
    if (ret != ESP_OK) ESP_LOGE(TAG, "Failed to register wallet_send: %s", esp_err_to_name(ret));
    ret = httpd_register_uri_handler(s_api_server, &uri_grant);
    if (ret != ESP_OK) ESP_LOGE(TAG, "Failed to register grant: %s", esp_err_to_name(ret));
    ret = httpd_register_uri_handler(s_api_server, &uri_reset);
    if (ret != ESP_OK) ESP_LOGE(TAG, "Failed to register reset: %s", esp_err_to_name(ret));
    ret = httpd_register_uri_handler(s_api_server, &uri_portal_config);
    if (ret != ESP_OK) ESP_LOGE(TAG, "Failed to register portal_config: %s", esp_err_to_name(ret));

    ESP_LOGI(TAG, "TollGate API started on port 2121");
    return ESP_OK;
}

void tollgate_api_stop(void)
{
    if (s_api_server) {
        httpd_stop(s_api_server);
        s_api_server = NULL;
    }
}