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
|
// Copyright (c) 2026 Bitflash developers
// Distributed under the MIT/X11 software license.
//
// Bitflash `.btf` self-certifying addresses + service descriptors.
// Ported from the Itzal hidden.rs design. See btfaddr.h.
#include "btfaddr.h"
#include <openssl/sha.h>
// See the note in nostr.cpp: the makefiles pass -DSECP256K1_STATIC too.
#ifndef SECP256K1_STATIC
#define SECP256K1_STATIC
#endif
#include <secp256k1.h>
#include <secp256k1_schnorrsig.h>
#include <secp256k1_extrakeys.h>
#include <nlohmann/json.hpp>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cstdlib>
using json = nlohmann::json;
namespace btf
{
const char* TLD = ".btf";
static const char* B32 = "abcdefghijklmnopqrstuvwxyz234567";
std::string Base32Encode(const unsigned char* data, size_t n)
{
std::string out;
out.reserve(n * 8 / 5 + 1);
uint64_t buf = 0;
uint32_t bits = 0;
for (size_t i = 0; i < n; i++)
{
buf = (buf << 8) | data[i];
bits += 8;
while (bits >= 5)
{
bits -= 5;
out.push_back(B32[(buf >> bits) & 0x1f]);
}
buf &= (bits == 0) ? 0 : ((1ULL << bits) - 1);
}
if (bits > 0)
out.push_back(B32[(buf << (5 - bits)) & 0x1f]);
return out;
}
bool Base32Decode(const std::string& s, std::vector<unsigned char>& out)
{
out.clear();
out.reserve(s.size() * 5 / 8);
uint64_t buf = 0;
uint32_t bits = 0;
for (unsigned char c : s)
{
uint64_t val;
if (c >= 'a' && c <= 'z') val = c - 'a';
else if (c >= 'A' && c <= 'Z') val = c - 'A';
else if (c >= '2' && c <= '7') val = c - '2' + 26;
else return false;
buf = (buf << 5) | val;
bits += 5;
if (bits >= 8)
{
bits -= 8;
out.push_back((unsigned char)((buf >> bits) & 0xff));
}
buf &= (bits == 0) ? 0 : ((1ULL << bits) - 1);
}
return true;
}
static std::string ToLowerTrim(const std::string& in)
{
std::string s = in;
// trim whitespace
size_t a = s.find_first_not_of(" \t\r\n");
size_t b = s.find_last_not_of(" \t\r\n");
if (a == std::string::npos) return std::string();
s = s.substr(a, b - a + 1);
// strip trailing dots (fully-qualified hostname form)
while (!s.empty() && s.back() == '.') s.pop_back();
for (char& c : s) c = (char)std::tolower((unsigned char)c);
return s;
}
// Two-byte checksum, domain-separated so it can't collide with any other hash use.
static void Checksum(const unsigned char pubkey[32], unsigned char out[2])
{
static const char* DS = ".btf-checksum-v1";
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, (const unsigned char*)DS, strlen(DS));
SHA256_Update(&ctx, pubkey, 32);
unsigned char d[32];
SHA256_Final(d, &ctx);
out[0] = d[0];
out[1] = d[1];
}
std::string Address(const unsigned char pubkey[32])
{
unsigned char raw[34];
memcpy(raw, pubkey, 32);
Checksum(pubkey, raw + 32);
return Base32Encode(raw, 34) + TLD;
}
bool IsBtf(const std::string& host)
{
std::string s = ToLowerTrim(host);
std::string tld = TLD;
if (s.size() < tld.size()) return false;
return s.compare(s.size() - tld.size(), tld.size(), tld) == 0;
}
bool ParseAddress(const std::string& addr, unsigned char pubkeyOut[32])
{
std::string s = ToLowerTrim(addr);
std::string tld = TLD;
if (s.size() < tld.size()) return false;
if (s.compare(s.size() - tld.size(), tld.size(), tld) != 0) return false;
std::string label = s.substr(0, s.size() - tld.size());
std::vector<unsigned char> raw;
if (!Base32Decode(label, raw)) return false;
if (raw.size() < 34) return false;
unsigned char pk[32];
memcpy(pk, &raw[0], 32);
unsigned char sum[2];
Checksum(pk, sum);
if (raw[32] != sum[0] || raw[33] != sum[1]) return false;
memcpy(pubkeyOut, pk, 32);
return true;
}
// ---- descriptor ------------------------------------------------------------
static std::string HexEncode(const unsigned char* p, size_t n)
{
static const char* h = "0123456789abcdef";
std::string s;
s.reserve(n * 2);
for (size_t i = 0; i < n; i++) { s += h[p[i] >> 4]; s += h[p[i] & 0xf]; }
return s;
}
static bool HexDecode(const std::string& s, unsigned char* out, size_t n)
{
if (s.size() != n * 2) return false;
for (size_t i = 0; i < n; i++)
{
unsigned int b;
if (sscanf(s.c_str() + i * 2, "%2x", &b) != 1) return false;
out[i] = (unsigned char)b;
}
return true;
}
bool NormalizeOnionEndpoint(const std::string& in, std::string& out)
{
out.clear();
std::string s = ToLowerTrim(in);
size_t colon = s.rfind(':');
if (colon == std::string::npos || colon == 0 || colon + 1 >= s.size())
return false;
std::string host = s.substr(0, colon);
std::string port = s.substr(colon + 1);
while (!host.empty() && host.back() == '.') host.pop_back();
static const char* suffix = ".onion";
const size_t suffixLen = strlen(suffix);
if (host.size() != 56 + suffixLen)
return false;
if (host.compare(host.size() - suffixLen, suffixLen, suffix) != 0)
return false;
for (size_t i = 0; i < 56; i++)
{
char c = host[i];
if (!((c >= 'a' && c <= 'z') || (c >= '2' && c <= '7')))
return false;
}
for (size_t i = 0; i < port.size(); i++)
if (!isdigit((unsigned char)port[i]))
return false;
errno = 0;
char* end = NULL;
long nPort = strtol(port.c_str(), &end, 10);
if (errno == ERANGE || end == NULL || *end != '\0' || nPort <= 0 || nPort > 65535)
return false;
out = host + ":" + port;
return true;
}
// Digest signed over the descriptor fields (domain-separated).
static void DescriptorDigestV2(const unsigned char pubkey[32], const std::string& enc,
const std::string& meeting_node, uint64_t created,
unsigned char out[32])
{
static const char* DS = ".btf-descriptor-v2";
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, (const unsigned char*)DS, strlen(DS));
SHA256_Update(&ctx, pubkey, 32);
SHA256_Update(&ctx, (const unsigned char*)enc.data(), enc.size());
SHA256_Update(&ctx, (const unsigned char*)meeting_node.data(), meeting_node.size());
unsigned char be[8];
for (int i = 0; i < 8; i++) be[i] = (unsigned char)((created >> (8 * (7 - i))) & 0xff);
SHA256_Update(&ctx, be, 8);
SHA256_Final(out, &ctx);
}
static void DescriptorDigestV3(const unsigned char pubkey[32], const std::string& enc,
const std::string& meeting_node, const std::string& onion,
uint64_t created, unsigned char out[32])
{
static const char* DS = ".btf-descriptor-v3-onion";
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, (const unsigned char*)DS, strlen(DS));
SHA256_Update(&ctx, pubkey, 32);
SHA256_Update(&ctx, (const unsigned char*)enc.data(), enc.size());
SHA256_Update(&ctx, (const unsigned char*)meeting_node.data(), meeting_node.size());
SHA256_Update(&ctx, (const unsigned char*)onion.data(), onion.size());
unsigned char be[8];
for (int i = 0; i < 8; i++) be[i] = (unsigned char)((created >> (8 * (7 - i))) & 0xff);
SHA256_Update(&ctx, be, 8);
SHA256_Final(out, &ctx);
}
std::string SignDescriptor(void* ctxv, const unsigned char seckey[32],
const std::string& enc, const std::string& meeting_node,
uint64_t created, const std::string& onion)
{
secp256k1_context* ctx = (secp256k1_context*)ctxv;
secp256k1_keypair kp;
if (!secp256k1_keypair_create(ctx, &kp, seckey)) return std::string();
secp256k1_xonly_pubkey xpub;
if (!secp256k1_keypair_xonly_pub(ctx, &xpub, NULL, &kp)) return std::string();
unsigned char pubkey[32];
secp256k1_xonly_pubkey_serialize(ctx, pubkey, &xpub);
unsigned char digest[32];
DescriptorDigestV2(pubkey, enc, meeting_node, created, digest);
unsigned char sig[64];
// Deterministic signature (NULL aux_rand), matching Itzal's no-aux-rand signing.
if (!secp256k1_schnorrsig_sign32(ctx, sig, digest, &kp, NULL)) return std::string();
json v = json::object();
v["v"] = onion.empty() ? 2 : 3;
v["pubkey"] = HexEncode(pubkey, 32);
v["enc"] = enc;
v["meeting_node"] = meeting_node;
if (!onion.empty())
{
std::string onionNorm;
if (!NormalizeOnionEndpoint(onion, onionNorm)) return std::string();
unsigned char digest3[32];
DescriptorDigestV3(pubkey, enc, meeting_node, onionNorm, created, digest3);
unsigned char sig3[64];
if (!secp256k1_schnorrsig_sign32(ctx, sig3, digest3, &kp, NULL)) return std::string();
v["onion"] = onionNorm;
v["sig3"] = HexEncode(sig3, 64);
}
v["created"] = created;
v["sig"] = HexEncode(sig, 64);
return v.dump();
}
bool VerifyDescriptor(void* ctxv, const std::string& jsonStr,
const unsigned char expect_pubkey[32], Descriptor& out)
{
secp256k1_context* ctx = (secp256k1_context*)ctxv;
// Descriptors arrive from untrusted peers (via Nostr relays). Guard the whole
// parse: a malformed or wrong-typed field must be rejected, never throw.
try
{
json v = json::parse(jsonStr);
if (!v.is_object()) return false;
if (!v.contains("pubkey") || !v.contains("enc") || !v.contains("meeting_node")
|| !v.contains("created") || !v.contains("sig")) return false;
// Reject wrong field types before extracting (json::get would otherwise throw).
if (!v["pubkey"].is_string() || !v["enc"].is_string() ||
!v["meeting_node"].is_string() || !v["sig"].is_string() ||
!v["created"].is_number_unsigned()) return false;
unsigned char pubkey[32];
if (!HexDecode(v["pubkey"].get<std::string>(), pubkey, 32)) return false;
if (memcmp(pubkey, expect_pubkey, 32) != 0) return false; // descriptor is for a different key
std::string enc = v["enc"].get<std::string>();
std::string meeting_node = v["meeting_node"].get<std::string>();
uint64_t created = v["created"].get<uint64_t>();
unsigned char sig[64];
if (!HexDecode(v["sig"].get<std::string>(), sig, 64)) return false;
unsigned char digest[32];
DescriptorDigestV2(expect_pubkey, enc, meeting_node, created, digest);
secp256k1_xonly_pubkey xpub;
if (!secp256k1_xonly_pubkey_parse(ctx, &xpub, expect_pubkey)) return false;
if (!secp256k1_schnorrsig_verify(ctx, sig, digest, 32, &xpub)) return false;
std::string onion;
if (v.contains("onion"))
{
// A descriptor that carries an onion endpoint must prove it. The
// endpoint is covered by sig3 and only sig3, so any failure here --
// missing sig3, bad hex, unnormalised endpoint, bad signature --
// means the descriptor was tampered with, and a tampered
// descriptor is rejected outright. Upstream dropped just the onion
// and accepted the rest, which let any relay convert an onion
// descriptor into a rendezvous-only one by deleting a field.
//
// Residual, by design: removing BOTH "onion" and "sig3" still
// verifies, because the result is indistinguishable from a peer
// that never had an onion endpoint. Closing that requires binding
// the onion into the primary sig (the V2 digest), which every
// upstream 1.2.18/1.2.19 verifier would reject -- an upstream
// protocol change, not something this fork can do unilaterally.
if (!v["onion"].is_string()) return false;
if (!v.contains("sig3") || !v["sig3"].is_string()) return false;
std::string onionNorm;
std::string onionRaw = v["onion"].get<std::string>();
if (!NormalizeOnionEndpoint(onionRaw, onionNorm) || onionNorm != onionRaw)
return false;
unsigned char sig3[64];
unsigned char digest3[32];
DescriptorDigestV3(expect_pubkey, enc, meeting_node, onionNorm, created, digest3);
if (!HexDecode(v["sig3"].get<std::string>(), sig3, 64)) return false;
if (!secp256k1_schnorrsig_verify(ctx, sig3, digest3, 32, &xpub)) return false;
onion = onionNorm;
}
memcpy(out.pubkey, expect_pubkey, 32);
out.enc = enc;
out.meeting_node = meeting_node;
out.onion = onion;
out.created = created;
return true;
}
catch (...)
{
return false; // malformed / wrong-typed descriptor -> reject, don't crash
}
}
} // namespace btf
|