| 1 | package Net::Nostr::Relay; | ||
| 2 | |||
| 3 | 2 | ▶ | use strictures 2; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | |||
| 5 | our $VERSION = '1.001001'; | ||
| 6 | |||
| 7 | 2 | ▶ | use Net::Nostr::_ConstructorArgs (); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | |||
| 9 | 2 | ▶ | use AnyEvent (); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 10 | 2 | ▶ | use Carp qw(croak); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 11 | 2 | ▶ | use Net::Nostr::Message; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 12 | use Net::Nostr::Filter; | ||
| 13 | use Net::Nostr::Deletion; | ||
| 14 | |||
| 15 | use AnyEvent::Socket qw(tcp_server); | ||
| 16 | use AnyEvent::WebSocket::Server; | ||
| 17 | use Crypt::PK::ECC; | ||
| 18 | use Crypt::PK::ECC::Schnorr; | ||
| 19 | use Crypt::PRNG qw(random_bytes); | ||
| 20 | use Digest::SHA qw(sha256_hex); | ||
| 21 | use JSON (); | ||
| 22 | use Socket qw(MSG_PEEK); | ||
| 23 | |||
| 24 | use Net::Nostr::Negentropy; | ||
| 25 | use Net::Nostr::RelayInfo; | ||
| 26 | |||
| 27 | use Net::Nostr::RelayStore; | ||
| 28 | |||
| 29 | use Class::Tiny qw( | ||
| 30 | _server | ||
| 31 | _connections | ||
| 32 | _subscriptions | ||
| 33 | store | ||
| 34 | _guard | ||
| 35 | verify_signatures | ||
| 36 | max_connections_per_ip | ||
| 37 | max_events | ||
| 38 | event_rate_limit | ||
| 39 | relay_url | ||
| 40 | relay_info | ||
| 41 | _conn_count_by_ip | ||
| 42 | _run_cv | ||
| 43 | _challenges | ||
| 44 | _authenticated | ||
| 45 | _nip11_watchers | ||
| 46 | min_pow_difficulty | ||
| 47 | _rate_state | ||
| 48 | max_subscriptions | ||
| 49 | max_filters | ||
| 50 | max_content_length | ||
| 51 | max_event_tags | ||
| 52 | max_limit | ||
| 53 | default_limit | ||
| 54 | created_at_lower_limit | ||
| 55 | created_at_upper_limit | ||
| 56 | max_message_length | ||
| 57 | on_event | ||
| 58 | idle_timeout | ||
| 59 | shutdown_timeout | ||
| 60 | ssl_cert_file | ||
| 61 | ssl_key_file | ||
| 62 | _idle_timers | ||
| 63 | _sub_by_kind | ||
| 64 | _sub_no_kind | ||
| 65 | _neg_sessions | ||
| 66 | ); | ||
| 67 | |||
| 68 | sub connections { | ||
| 69 | my ($self) = @_; | ||
| 70 | return { %{$self->_connections || {}} }; | ||
| 71 | } | ||
| 72 | |||
| 73 | sub subscriptions { | ||
| 74 | my ($self) = @_; | ||
| 75 | my $internal = $self->_subscriptions || {}; | ||
| 76 | return { map { $_ => { %{$internal->{$_}} } } keys %$internal }; | ||
| 77 | } | ||
| 78 | |||
| 79 | sub new { | ||
| 80 | my $class = shift; | ||
| 81 | my $self = bless { Net::Nostr::_ConstructorArgs::normalize(@_) }, $class; | ||
| 82 | my %known; @known{Class::Tiny->get_all_attributes_for($class)} = (); | ||
| 83 | my @unknown = grep { !exists $known{$_} } keys %$self; | ||
| 84 | croak "unknown argument(s): " . join(', ', sort @unknown) if @unknown; | ||
| 85 | $self->verify_signatures(1) unless defined $self->verify_signatures; | ||
| 86 | |||
| 87 | # Validate event_rate_limit format | ||
| 88 | if (defined $self->event_rate_limit) { | ||
| 89 | croak "event_rate_limit must be 'count/seconds' (e.g. '10/60')" | ||
| 90 | unless $self->event_rate_limit =~ m{^(\d+)/(\d+)$} && $1 > 0 && $2 > 0; | ||
| 91 | } | ||
| 92 | |||
| 93 | # Validate positive integer options | ||
| 94 | for my $opt (qw(max_subscriptions max_filters max_content_length | ||
| 95 | max_event_tags max_limit default_limit | ||
| 96 | created_at_lower_limit created_at_upper_limit | ||
| 97 | max_message_length)) { | ||
| 98 | if (defined $self->$opt) { | ||
| 99 | croak "$opt must be a positive integer" | ||
| 100 | unless $self->$opt =~ /^\d+$/ && $self->$opt > 0; | ||
| 101 | } | ||
| 102 | } | ||
| 103 | |||
| 104 | # Validate on_event callback | ||
| 105 | if (defined $self->on_event) { | ||
| 106 | croak "on_event must be a code reference" | ||
| 107 | unless ref($self->on_event) eq 'CODE'; | ||
| 108 | } | ||
| 109 | |||
| 110 | if (defined $self->ssl_key_file && !defined $self->ssl_cert_file) { | ||
| 111 | croak "ssl_key_file requires ssl_cert_file"; | ||
| 112 | } | ||
| 113 | |||
| 114 | # Initialize store: use provided store, or build default | ||
| 115 | if (!$self->store) { | ||
| 116 | my %store_args; | ||
| 117 | $store_args{max_events} = $self->max_events if defined $self->max_events; | ||
| 118 | $self->store(Net::Nostr::RelayStore->new(%store_args)); | ||
| 119 | } | ||
| 120 | |||
| 121 | # Validate idle_timeout and shutdown_timeout | ||
| 122 | for my $opt (qw(idle_timeout shutdown_timeout)) { | ||
| 123 | if (defined $self->$opt) { | ||
| 124 | croak "$opt must be a positive integer" | ||
| 125 | unless $self->$opt =~ /^\d+$/ && $self->$opt > 0; | ||
| 126 | } | ||
| 127 | } | ||
| 128 | |||
| 129 | $self->_rate_state({}); | ||
| 130 | $self->_idle_timers({}); | ||
| 131 | $self->_sub_by_kind({}); | ||
| 132 | $self->_sub_no_kind({}); | ||
| 133 | $self->_server(AnyEvent::WebSocket::Server->new( | ||
| 134 | handshake => sub { | ||
| 135 | my ($req, $res) = @_; | ||
| 136 | my $resource = $req->resource_name // '/'; | ||
| 137 | my ($path) = split /\?/, $resource, 2; | ||
| 138 | $path = '/' unless defined $path && length $path; | ||
| 139 | die "invalid relay endpoint path\n" unless $path eq $self->_websocket_path; | ||
| 140 | return $res; | ||
| 141 | }, | ||
| 142 | (defined $self->ssl_cert_file ? (ssl_cert_file => $self->ssl_cert_file) : ()), | ||
| 143 | (defined $self->ssl_key_file ? (ssl_key_file => $self->ssl_key_file) : ()), | ||
| 144 | )); | ||
| 145 | return $self; | ||
| 146 | } | ||
| 147 | |||
| 148 | sub _websocket_path { | ||
| 149 | my ($self) = @_; | ||
| 150 | return '/' unless defined $self->relay_url; | ||
| 151 | return $1 if $self->relay_url =~ m{\A[^:]+://[^/?#]+([^?#]*)} && length $1; | ||
| 152 | return '/'; | ||
| 153 | } | ||
| 154 | |||
| 155 | sub events { | ||
| 156 | my ($self, @args) = @_; | ||
| 157 | if (@args) { | ||
| 158 | # Setter: clear store and re-populate (backward compat) | ||
| 159 | $self->store->clear; | ||
| 160 | my $events = $args[0] // []; | ||
| 161 | $self->store->store($_) for @$events; | ||
| 162 | return $events; | ||
| 163 | } | ||
| 164 | return $self->store->all_events; | ||
| 165 | } | ||
| 166 | |||
| 167 | sub inject_event { | ||
| 168 | my ($self, $event) = @_; | ||
| 169 | $self->store->store($event); | ||
| 170 | } | ||
| 171 | |||
| 172 | sub start { | ||
| 173 | my ($self, $host, $port) = @_; | ||
| 174 | $self->_conn_count_by_ip({}); | ||
| 175 | $self->_nip11_watchers({}); | ||
| 176 | $self->_guard(tcp_server($host, $port, sub { | ||
| 177 | my ($fh, $peer_host) = @_; | ||
| 178 | if (defined $self->max_connections_per_ip) { | ||
| 179 | my $count = $self->_conn_count_by_ip->{$peer_host} || 0; | ||
| 180 | if ($count >= $self->max_connections_per_ip) { | ||
| 181 | close $fh; | ||
| 182 | return; | ||
| 183 | } | ||
| 184 | } | ||
| 185 | $self->_conn_count_by_ip->{$peer_host}++; | ||
| 186 | |||
| 187 | if (defined $self->ssl_cert_file || defined $self->ssl_key_file) { | ||
| 188 | $self->_establish_ws($fh, $peer_host); | ||
| 189 | } elsif ($self->relay_info) { | ||
| 190 | $self->_handle_nip11_or_ws($fh, $peer_host); | ||
| 191 | } else { | ||
| 192 | $self->_establish_ws($fh, $peer_host); | ||
| 193 | } | ||
| 194 | })); | ||
| 195 | } | ||
| 196 | |||
| 197 | sub _establish_ws { | ||
| 198 | my ($self, $fh, $peer_host) = @_; | ||
| 199 | $self->_server->establish($fh)->cb(sub { | ||
| 200 | my $conn = eval { shift->recv }; | ||
| 201 | if ($@) { | ||
| 202 | $self->_conn_count_by_ip->{$peer_host}--; | ||
| 203 | warn "WebSocket handshake failed: $@\n"; | ||
| 204 | return; | ||
| 205 | } | ||
| 206 | $self->_on_connection($conn, $peer_host); | ||
| 207 | }); | ||
| 208 | } | ||
| 209 | |||
| 210 | sub _write_all { | ||
| 211 | my ($writer, $data) = @_; | ||
| 212 | my $off = 0; | ||
| 213 | while ($off < length $data) { | ||
| 214 | my $n = $writer->($data, $off); | ||
| 215 | last unless defined $n && $n > 0; | ||
| 216 | $off += $n; | ||
| 217 | } | ||
| 218 | return $off; | ||
| 219 | } | ||
| 220 | |||
| 221 | sub _syswrite_all { | ||
| 222 | my ($fh, $data) = @_; | ||
| 223 | return _write_all(sub { | ||
| 224 | my ($buf, $off) = @_; | ||
| 225 | return syswrite($fh, $buf, length($buf) - $off, $off); | ||
| 226 | }, $data); | ||
| 227 | } | ||
| 228 | |||
| 229 | sub _handle_nip11_or_ws { | ||
| 230 | my ($self, $fh, $peer_host) = @_; | ||
| 231 | my $fileno = fileno($fh); | ||
| 232 | my $buf = ''; | ||
| 233 | my ($w, $timer); | ||
| 234 | |||
| 235 | my $cleanup = sub { | ||
| 236 | undef $w; | ||
| 237 | undef $timer; | ||
| 238 | delete $self->_nip11_watchers->{$fileno}; | ||
| 239 | }; | ||
| 240 | |||
| 241 | my $dispatch = sub { | ||
| 242 | if ($buf =~ /^OPTIONS\s/i) { | ||
| 243 | sysread($fh, my $discard, 8192); | ||
| 244 | _syswrite_all($fh, Net::Nostr::RelayInfo->cors_preflight_response); | ||
| 245 | close $fh; | ||
| 246 | $self->_conn_count_by_ip->{$peer_host}--; | ||
| 247 | return; | ||
| 248 | } | ||
| 249 | |||
| 250 | if ($buf =~ /Accept:\s*application\/nostr\+json/i | ||
| 251 | && $buf !~ /Upgrade:\s*websocket/i) { | ||
| 252 | sysread($fh, my $discard, 8192); | ||
| 253 | _syswrite_all($fh, $self->relay_info->to_http_response); | ||
| 254 | close $fh; | ||
| 255 | $self->_conn_count_by_ip->{$peer_host}--; | ||
| 256 | return; | ||
| 257 | } | ||
| 258 | |||
| 259 | $self->_establish_ws($fh, $peer_host); | ||
| 260 | }; | ||
| 261 | |||
| 262 | $w = AnyEvent->io(fh => $fh, poll => 'r', cb => sub { | ||
| 263 | my $chunk = ''; | ||
| 264 | recv($fh, $chunk, 8192, MSG_PEEK); | ||
| 265 | $buf = $chunk; # MSG_PEEK returns the full buffer each time | ||
| 266 | |||
| 267 | if ($buf =~ /\r\n\r\n/ || length($buf) >= 8192) { | ||
| 268 | $cleanup->(); | ||
| 269 | $dispatch->(); | ||
| 270 | } | ||
| 271 | }); | ||
| 272 | |||
| 273 | $timer = AnyEvent->timer(after => 5, cb => sub { | ||
| 274 | $cleanup->(); | ||
| 275 | # Timed out waiting for headers -- fall through to WebSocket | ||
| 276 | $self->_establish_ws($fh, $peer_host); | ||
| 277 | }); | ||
| 278 | |||
| 279 | $self->_nip11_watchers->{$fileno} = [$w, $timer]; | ||
| 280 | } | ||
| 281 | |||
| 282 | sub run { | ||
| 283 | my ($self, $host, $port) = @_; | ||
| 284 | $self->start($host, $port); | ||
| 285 | $self->_run_cv(AnyEvent->condvar); | ||
| 286 | $self->_run_cv->recv; | ||
| 287 | $self->_run_cv(undef); | ||
| 288 | $self->_stop_cleanup; | ||
| 289 | } | ||
| 290 | |||
| 291 | sub stop { | ||
| 292 | my ($self) = @_; | ||
| 293 | if ($self->_run_cv) { | ||
| 294 | $self->_run_cv->send; | ||
| 295 | return; | ||
| 296 | } | ||
| 297 | $self->_stop_cleanup; | ||
| 298 | } | ||
| 299 | |||
| 300 | sub graceful_stop { | ||
| 301 | my ($self) = @_; | ||
| 302 | |||
| 303 | # Stop accepting new connections immediately | ||
| 304 | $self->_guard(undef); | ||
| 305 | |||
| 306 | # Send NOTICE to all connected clients | ||
| 307 | my $notice = Net::Nostr::Message->new( | ||
| 308 | type => 'NOTICE', | ||
| 309 | message => 'shutting down', | ||
| 310 | )->serialize; | ||
| 311 | for my $conn (values %{$self->_connections || {}}) { | ||
| 312 | eval { $conn->send($notice) }; | ||
| 313 | } | ||
| 314 | |||
| 315 | my $timeout = $self->shutdown_timeout // 5; | ||
| 316 | my $t; $t = AnyEvent->timer(after => $timeout, cb => sub { | ||
| 317 | undef $t; | ||
| 318 | $self->stop; | ||
| 319 | }); | ||
| 320 | # Store the timer to prevent GC | ||
| 321 | $self->{_shutdown_timer} = $t; | ||
| 322 | } | ||
| 323 | |||
| 324 | sub authenticated_pubkeys { | ||
| 325 | my ($self) = @_; | ||
| 326 | my $internal = $self->_authenticated || {}; | ||
| 327 | return { map { $_ => { %{$internal->{$_}} } } keys %$internal }; | ||
| 328 | } | ||
| 329 | |||
| 330 | sub _stop_cleanup { | ||
| 331 | my ($self) = @_; | ||
| 332 | $self->_guard(undef); | ||
| 333 | for my $conn (values %{$self->_connections || {}}) { | ||
| 334 | $conn->close; | ||
| 335 | } | ||
| 336 | $self->_connections({}); | ||
| 337 | $self->_subscriptions({}); | ||
| 338 | $self->_conn_count_by_ip({}); | ||
| 339 | $self->_challenges({}); | ||
| 340 | $self->_authenticated({}); | ||
| 341 | $self->_nip11_watchers({}); | ||
| 342 | $self->_rate_state({}); | ||
| 343 | $self->_idle_timers({}); | ||
| 344 | $self->_sub_by_kind({}); | ||
| 345 | $self->_sub_no_kind({}); | ||
| 346 | $self->_neg_sessions({}); | ||
| 347 | } | ||
| 348 | |||
| 349 | sub broadcast { | ||
| 350 | my ($self, $event) = @_; | ||
| 351 | # NIP-40: Do not broadcast expired events | ||
| 352 | return if $event->is_expired; | ||
| 353 | |||
| 354 | # Collect candidate subscriptions from inverted index | ||
| 355 | my %candidates; # "$conn_id\0$sub_id" => [$conn_id, $sub_id] | ||
| 356 | |||
| 357 | # Subscriptions that filter on this event's kind | ||
| 358 | my $kind_subs = $self->_sub_by_kind->{$event->kind}; | ||
| 359 | if ($kind_subs) { | ||
| 360 | for my $key (keys %$kind_subs) { | ||
| 361 | $candidates{$key} = $kind_subs->{$key}; | ||
| 362 | } | ||
| 363 | } | ||
| 364 | |||
| 365 | # Subscriptions with no kind filter (match any kind) | ||
| 366 | my $no_kind = $self->_sub_no_kind; | ||
| 367 | for my $key (keys %$no_kind) { | ||
| 368 | $candidates{$key} = $no_kind->{$key}; | ||
| 369 | } | ||
| 370 | |||
| 371 | my $subs = $self->_subscriptions || {}; | ||
| 372 | for my $entry (values %candidates) { | ||
| 373 | my ($conn_id, $sub_id) = @$entry; | ||
| 374 | my $conn = $self->_connections->{$conn_id} or next; | ||
| 375 | my $filters = $subs->{$conn_id}{$sub_id} or next; | ||
| 376 | if (Net::Nostr::Filter->matches_any($event, @$filters)) { | ||
| 377 | $conn->send(Net::Nostr::Message->new(type => 'EVENT', subscription_id => $sub_id, event => $event)->serialize); | ||
| 378 | } | ||
| 379 | } | ||
| 380 | } | ||
| 381 | |||
| 382 | my $CONN_ID = 0; | ||
| 383 | |||
| 384 | sub _on_connection { | ||
| 385 | my ($self, $conn, $peer_host) = @_; | ||
| 386 | my $conn_id = ++$CONN_ID; | ||
| 387 | |||
| 388 | $self->_connections($self->_connections // {}); | ||
| 389 | $self->_subscriptions($self->_subscriptions // {}); | ||
| 390 | $self->_challenges($self->_challenges // {}); | ||
| 391 | $self->_authenticated($self->_authenticated // {}); | ||
| 392 | $self->_neg_sessions($self->_neg_sessions // {}); | ||
| 393 | |||
| 394 | $self->_connections->{$conn_id} = $conn; | ||
| 395 | |||
| 396 | # Initialize rate limiting state for this connection | ||
| 397 | if (defined $self->event_rate_limit) { | ||
| 398 | my ($count, $seconds) = $self->event_rate_limit =~ m{^(\d+)/(\d+)$}; | ||
| 399 | $self->_rate_state->{$conn_id} = { | ||
| 400 | tokens => $count, | ||
| 401 | max_tokens => $count, | ||
| 402 | last_refill => time(), | ||
| 403 | refill_seconds => $seconds, | ||
| 404 | }; | ||
| 405 | } | ||
| 406 | |||
| 407 | # Send AUTH challenge | ||
| 408 | my $challenge = unpack('H*', random_bytes(32)); | ||
| 409 | $self->_challenges->{$conn_id} = $challenge; | ||
| 410 | $self->_authenticated->{$conn_id} = {}; | ||
| 411 | $conn->send(Net::Nostr::Message->new(type => 'AUTH', challenge => $challenge)->serialize); | ||
| 412 | |||
| 413 | # Idle timeout: disconnect clients that send no messages | ||
| 414 | if (defined $self->idle_timeout) { | ||
| 415 | my $reset_idle = sub { | ||
| 416 | $self->_idle_timers->{$conn_id} = AnyEvent->timer( | ||
| 417 | after => $self->idle_timeout, | ||
| 418 | cb => sub { | ||
| 419 | my $c = $self->_connections->{$conn_id}; | ||
| 420 | $c->close if $c; | ||
| 421 | }, | ||
| 422 | ); | ||
| 423 | }; | ||
| 424 | $reset_idle->(); | ||
| 425 | $self->{_reset_idle}{$conn_id} = $reset_idle; | ||
| 426 | } | ||
| 427 | |||
| 428 | $conn->on(each_message => sub { | ||
| 429 | my ($conn, $message) = @_; | ||
| 430 | my $raw = $message->body; | ||
| 431 | |||
| 432 | # Reset idle timer on any activity | ||
| 433 | if ($self->{_reset_idle} && $self->{_reset_idle}{$conn_id}) { | ||
| 434 | $self->{_reset_idle}{$conn_id}->(); | ||
| 435 | } | ||
| 436 | |||
| 437 | AE::postpone { | ||
| 438 | return unless $self->_connections->{$conn_id}; | ||
| 439 | |||
| 440 | if (defined $self->max_message_length && length($raw) > $self->max_message_length) { | ||
| 441 | $conn->send(Net::Nostr::Message->new( | ||
| 442 | type => 'NOTICE', message => "error: message too large", | ||
| 443 | )->serialize); | ||
| 444 | return; | ||
| 445 | } | ||
| 446 | |||
| 447 | my $arr = eval { JSON::decode_json($raw) }; | ||
| 448 | return warn "bad message: $@\n" if $@ || ref($arr) ne 'ARRAY' || !@$arr; | ||
| 449 | |||
| 450 | my $type = $arr->[0]; | ||
| 451 | |||
| 452 | if ($type eq 'REQ') { | ||
| 453 | my $sub_id = $arr->[1] // ''; | ||
| 454 | my $msg = eval { Net::Nostr::Message->parse($raw) }; | ||
| 455 | if ($@) { | ||
| 456 | $conn->send(Net::Nostr::Message->new( | ||
| 457 | type => 'CLOSED', subscription_id => $sub_id, | ||
| 458 | message => "error: $@" | ||
| 459 | )->serialize); | ||
| 460 | return; | ||
| 461 | } | ||
| 462 | $self->_handle_req($conn_id, $msg->subscription_id, @{$msg->filters}); | ||
| 463 | return; | ||
| 464 | } | ||
| 465 | |||
| 466 | if ($type eq 'COUNT') { | ||
| 467 | my $sub_id = $arr->[1] // ''; | ||
| 468 | my $msg = eval { Net::Nostr::Message->parse($raw) }; | ||
| 469 | if ($@) { | ||
| 470 | $conn->send(Net::Nostr::Message->new( | ||
| 471 | type => 'CLOSED', subscription_id => $sub_id, | ||
| 472 | message => "error: $@" | ||
| 473 | )->serialize); | ||
| 474 | return; | ||
| 475 | } | ||
| 476 | $self->_handle_count($conn_id, $msg->subscription_id, @{$msg->filters}); | ||
| 477 | return; | ||
| 478 | } | ||
| 479 | |||
| 480 | if ($type eq 'NEG-OPEN') { | ||
| 481 | my $sub_id = $arr->[1] // ''; | ||
| 482 | my $msg = eval { Net::Nostr::Message->parse($raw) }; | ||
| 483 | if ($@) { | ||
| 484 | my $reason = $@; | ||
| 485 | $reason =~ s/\n\z//; | ||
| 486 | $conn->send(Net::Nostr::Message->new( | ||
| 487 | type => 'NEG-ERR', subscription_id => $sub_id, | ||
| 488 | message => "error: $reason", | ||
| 489 | )->serialize); | ||
| 490 | return; | ||
| 491 | } | ||
| 492 | $self->_handle_neg_open($conn_id, $msg); | ||
| 493 | return; | ||
| 494 | } | ||
| 495 | |||
| 496 | if ($type eq 'NEG-MSG') { | ||
| 497 | my $sub_id = $arr->[1] // ''; | ||
| 498 | my $msg = eval { Net::Nostr::Message->parse($raw) }; | ||
| 499 | if ($@) { | ||
| 500 | my $reason = $@; | ||
| 501 | $reason =~ s/\n\z//; | ||
| 502 | $conn->send(Net::Nostr::Message->new( | ||
| 503 | type => 'NEG-ERR', subscription_id => $sub_id, | ||
| 504 | message => "error: $reason", | ||
| 505 | )->serialize); | ||
| 506 | return; | ||
| 507 | } | ||
| 508 | $self->_handle_neg_msg($conn_id, $msg); | ||
| 509 | return; | ||
| 510 | } | ||
| 511 | |||
| 512 | if ($type eq 'NEG-CLOSE') { | ||
| 513 | $self->_handle_neg_close($conn_id, $arr->[1] // ''); | ||
| 514 | return; | ||
| 515 | } | ||
| 516 | |||
| 517 | my $msg = eval { Net::Nostr::Message->parse($raw) }; | ||
| 518 | if ($@) { | ||
| 519 | if ($type eq 'EVENT' || $type eq 'AUTH') { | ||
| 520 | my $raw_id = (ref($arr->[1]) eq 'HASH' ? $arr->[1]{id} : '') // ''; | ||
| 521 | my $event_id = $raw_id =~ /\A[0-9a-f]{64}\z/ ? $raw_id : ('0' x 64); | ||
| 522 | my $reason = $@; | ||
| 523 | $reason =~ s/\n\z//; | ||
| 524 | $conn->send(Net::Nostr::Message->new( | ||
| 525 | type => 'OK', event_id => $event_id, | ||
| 526 | accepted => 0, message => "invalid: $reason" | ||
| 527 | )->serialize); | ||
| 528 | } | ||
| 529 | return; | ||
| 530 | } | ||
| 531 | |||
| 532 | if ($msg->type eq 'EVENT') { | ||
| 533 | $self->_handle_event($conn_id, $msg->event); | ||
| 534 | } elsif ($msg->type eq 'CLOSE') { | ||
| 535 | $self->_handle_close($conn_id, $msg->subscription_id); | ||
| 536 | } elsif ($msg->type eq 'AUTH') { | ||
| 537 | $self->_handle_auth($conn_id, $msg->event); | ||
| 538 | } | ||
| 539 | }; | ||
| 540 | }); | ||
| 541 | |||
| 542 | $conn->on(finish => sub { | ||
| 543 | $self->_remove_all_sub_indexes($conn_id); | ||
| 544 | delete $self->_connections->{$conn_id}; | ||
| 545 | delete $self->_subscriptions->{$conn_id}; | ||
| 546 | delete $self->_challenges->{$conn_id}; | ||
| 547 | delete $self->_authenticated->{$conn_id}; | ||
| 548 | delete $self->_rate_state->{$conn_id}; | ||
| 549 | delete $self->_idle_timers->{$conn_id}; | ||
| 550 | delete $self->{_reset_idle}{$conn_id} if $self->{_reset_idle}; | ||
| 551 | delete $self->_neg_sessions->{$conn_id}; | ||
| 552 | $self->_conn_count_by_ip->{$peer_host}-- if defined $peer_host; | ||
| 553 | }); | ||
| 554 | } | ||
| 555 | |||
| 556 | sub _relay_host_matches { | ||
| 557 | my ($expected, $got) = @_; | ||
| 558 | my $host_re = qr{ ( \[ [^\]]+ \] | [^:/]+ ) }x; | ||
| 559 | my ($es, $eh, $ep, $epath) = $expected =~ m{^(wss?)://$host_re(?::(\d+))?(/.*)?\z}i; | ||
| 560 | my ($gs, $gh, $gp, $gpath) = $got =~ m{^(wss?)://$host_re(?::(\d+))?(/.*)?\z}i; | ||
| 561 | return 0 unless defined $es && defined $gs; | ||
| 562 | return 0 unless lc($es) eq lc($gs); | ||
| 563 | return 0 unless lc($eh) eq lc($gh); | ||
| 564 | my %defaults = (wss => 443, ws => 80); | ||
| 565 | $ep //= $defaults{lc $es}; | ||
| 566 | $gp //= $defaults{lc $gs}; | ||
| 567 | return 0 unless $ep == $gp; | ||
| 568 | $epath = '/' unless defined $epath && length $epath; | ||
| 569 | $gpath = '/' unless defined $gpath && length $gpath; | ||
| 570 | return $epath eq $gpath; | ||
| 571 | } | ||
| 572 | |||
| 573 | my $HEX64 = qr/\A[0-9a-f]{64}\z/; | ||
| 574 | my $HEX128 = qr/\A[0-9a-f]{128}\z/; | ||
| 575 | |||
| 576 | sub _validate_event { | ||
| 577 | my ($self, $event) = @_; | ||
| 578 | return 'invalid: bad id format' unless defined $event->id && $event->id =~ $HEX64; | ||
| 579 | return 'invalid: bad pubkey format' unless defined $event->pubkey && $event->pubkey =~ $HEX64; | ||
| 580 | return 'invalid: bad sig format' unless defined $event->sig && $event->sig =~ $HEX128; | ||
| 581 | |||
| 582 | my $expected_id = sha256_hex($event->json_serialize); | ||
| 583 | return 'invalid: id does not match hash' unless $event->id eq $expected_id; | ||
| 584 | |||
| 585 | if ($self->verify_signatures) { | ||
| 586 | my $sig_valid = eval { | ||
| 587 | my $pubkey_raw = pack('H*', $event->pubkey); | ||
| 588 | # BIP-340 x-only pubkey: prepend 02 prefix for compressed point | ||
| 589 | my $compressed = "\x02" . $pubkey_raw; | ||
| 590 | my $pk = Crypt::PK::ECC->new; | ||
| 591 | $pk->import_key_raw($compressed, 'secp256k1'); | ||
| 592 | my $verifier = Crypt::PK::ECC::Schnorr->new(\$pk->export_key_der('public')); | ||
| 593 | my $sig_raw = pack('H*', $event->sig); | ||
| 594 | $verifier->verify_message(pack('H*', $event->id), $sig_raw); | ||
| 595 | }; | ||
| 596 | return 'invalid: bad signature' unless $sig_valid; | ||
| 597 | } | ||
| 598 | |||
| 599 | return undef; | ||
| 600 | } | ||
| 601 | |||
| 602 | sub _is_newer { | ||
| 603 | my ($new, $existing) = @_; | ||
| 604 | return 1 if $new->created_at > $existing->created_at; | ||
| 605 | return 1 if $new->created_at == $existing->created_at && $new->id lt $existing->id; | ||
| 606 | return 0; | ||
| 607 | } | ||
| 608 | |||
| 609 | sub _check_rate_limit { | ||
| 610 | my ($self, $conn_id) = @_; | ||
| 611 | return 1 unless defined $self->event_rate_limit; | ||
| 612 | my $state = $self->_rate_state->{$conn_id} or return 1; | ||
| 613 | |||
| 614 | my $now = time(); | ||
| 615 | my $elapsed = $now - $state->{last_refill}; | ||
| 616 | if ($elapsed >= $state->{refill_seconds}) { | ||
| 617 | $state->{tokens} = $state->{max_tokens}; | ||
| 618 | $state->{last_refill} = $now; | ||
| 619 | } | ||
| 620 | |||
| 621 | if ($state->{tokens} > 0) { | ||
| 622 | $state->{tokens}--; | ||
| 623 | return 1; | ||
| 624 | } | ||
| 625 | return 0; | ||
| 626 | } | ||
| 627 | |||
| 628 | sub _handle_event { | ||
| 629 | my ($self, $conn_id, $event) = @_; | ||
| 630 | my $conn = $self->_connections->{$conn_id}; | ||
| 631 | |||
| 632 | my $error = $self->_validate_event($event); | ||
| 633 | if ($error) { | ||
| 634 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => ($event->id // ''), accepted => 0, message => $error)->serialize); | ||
| 635 | return; | ||
| 636 | } | ||
| 637 | |||
| 638 | # Content length limit | ||
| 639 | if (defined $self->max_content_length && length($event->content) > $self->max_content_length) { | ||
| 640 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'invalid: content too long')->serialize); | ||
| 641 | return; | ||
| 642 | } | ||
| 643 | |||
| 644 | # Tag count limit | ||
| 645 | if (defined $self->max_event_tags && scalar(@{$event->_tags}) > $self->max_event_tags) { | ||
| 646 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'invalid: too many tags')->serialize); | ||
| 647 | return; | ||
| 648 | } | ||
| 649 | |||
| 650 | # created_at lower bound (reject events too far in the past) | ||
| 651 | if (defined $self->created_at_lower_limit) { | ||
| 652 | if ($event->created_at < time() - $self->created_at_lower_limit) { | ||
| 653 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'invalid: event too old')->serialize); | ||
| 654 | return; | ||
| 655 | } | ||
| 656 | } | ||
| 657 | |||
| 658 | # created_at upper bound (reject events too far in the future) | ||
| 659 | if (defined $self->created_at_upper_limit) { | ||
| 660 | if ($event->created_at > time() + $self->created_at_upper_limit) { | ||
| 661 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'invalid: event too far in the future')->serialize); | ||
| 662 | return; | ||
| 663 | } | ||
| 664 | } | ||
| 665 | |||
| 666 | # Policy callback | ||
| 667 | if ($self->on_event) { | ||
| 668 | my ($ok, $msg) = $self->on_event->($event); | ||
| 669 | unless ($ok) { | ||
| 670 | $msg = 'blocked: rejected by policy' unless defined $msg && length $msg; | ||
| 671 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => $msg)->serialize); | ||
| 672 | return; | ||
| 673 | } | ||
| 674 | } | ||
| 675 | |||
| 676 | # Rate limiting check | ||
| 677 | unless ($self->_check_rate_limit($conn_id)) { | ||
| 678 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'rate-limited: slow down')->serialize); | ||
| 679 | return; | ||
| 680 | } | ||
| 681 | |||
| 682 | # NIP-13: Proof of Work check | ||
| 683 | if (defined $self->min_pow_difficulty) { | ||
| 684 | my $min = $self->min_pow_difficulty; | ||
| 685 | my $committed = $event->committed_target_difficulty; | ||
| 686 | if (!defined $committed || $committed < $min) { | ||
| 687 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => "pow: difficulty commitment below required $min")->serialize); | ||
| 688 | return; | ||
| 689 | } | ||
| 690 | if ($event->difficulty < $min) { | ||
| 691 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => "pow: insufficient proof of work (need $min bits)")->serialize); | ||
| 692 | return; | ||
| 693 | } | ||
| 694 | } | ||
| 695 | |||
| 696 | # NIP-40: Relays SHOULD drop expired events on publish | ||
| 697 | # (expiration does not affect ephemeral events) | ||
| 698 | if ($event->is_expired && !$event->is_ephemeral) { | ||
| 699 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'invalid: event has expired')->serialize); | ||
| 700 | return; | ||
| 701 | } | ||
| 702 | |||
| 703 | # NIP-70: default behavior MUST reject events with ["-"] tag | ||
| 704 | if ($event->is_protected) { | ||
| 705 | my $authed = $self->_authenticated->{$conn_id} || {}; | ||
| 706 | unless ($authed->{$event->pubkey}) { | ||
| 707 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'auth-required: this event may only be published by its author')->serialize); | ||
| 708 | return; | ||
| 709 | } | ||
| 710 | } | ||
| 711 | |||
| 712 | # Relays MUST exclude kind 22242 events from being broadcasted (NIP-42) | ||
| 713 | if ($event->kind == 22242) { | ||
| 714 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'invalid: auth events should use AUTH message')->serialize); | ||
| 715 | return; | ||
| 716 | } | ||
| 717 | |||
| 718 | # duplicate detection | ||
| 719 | if ($self->store->get_by_id($event->id)) { | ||
| 720 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 1, message => 'duplicate: already have this event')->serialize); | ||
| 721 | return; | ||
| 722 | } | ||
| 723 | |||
| 724 | # ephemeral events: broadcast but don't store | ||
| 725 | if ($event->is_ephemeral) { | ||
| 726 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 1, message => '')->serialize); | ||
| 727 | $self->broadcast($event); | ||
| 728 | return; | ||
| 729 | } | ||
| 730 | |||
| 731 | # replaceable events: keep only latest per pubkey+kind | ||
| 732 | if ($event->is_replaceable) { | ||
| 733 | my $existing = $self->store->find_replaceable($event->pubkey, $event->kind); | ||
| 734 | if ($existing) { | ||
| 735 | if (_is_newer($event, $existing)) { | ||
| 736 | $self->store->delete_by_id($existing->id); | ||
| 737 | } else { | ||
| 738 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 1, message => 'duplicate: have a newer version')->serialize); | ||
| 739 | return; | ||
| 740 | } | ||
| 741 | } | ||
| 742 | } | ||
| 743 | |||
| 744 | # addressable events: keep only latest per pubkey+kind+d_tag | ||
| 745 | if ($event->is_addressable) { | ||
| 746 | my $existing = $self->store->find_addressable($event->pubkey, $event->kind, $event->d_tag); | ||
| 747 | if ($existing) { | ||
| 748 | if (_is_newer($event, $existing)) { | ||
| 749 | $self->store->delete_by_id($existing->id); | ||
| 750 | } else { | ||
| 751 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 1, message => 'duplicate: have a newer version')->serialize); | ||
| 752 | return; | ||
| 753 | } | ||
| 754 | } | ||
| 755 | } | ||
| 756 | |||
| 757 | # deletion requests: remove matching events, but not other kind 5 events | ||
| 758 | if ($event->kind == 5) { | ||
| 759 | $self->_handle_deletion($event); | ||
| 760 | } | ||
| 761 | |||
| 762 | $self->store->store($event); | ||
| 763 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 1, message => '')->serialize); | ||
| 764 | $self->broadcast($event); | ||
| 765 | } | ||
| 766 | |||
| 767 | sub _handle_deletion { | ||
| 768 | my ($self, $del_event) = @_; | ||
| 769 | my $del = Net::Nostr::Deletion->from_event($del_event); | ||
| 770 | $self->store->delete_matching( | ||
| 771 | $del_event->pubkey, | ||
| 772 | $del->event_ids, | ||
| 773 | $del->addresses, | ||
| 774 | $del_event->created_at, | ||
| 775 | ); | ||
| 776 | } | ||
| 777 | |||
| 778 | sub _handle_auth { | ||
| 779 | my ($self, $conn_id, $event) = @_; | ||
| 780 | my $conn = $self->_connections->{$conn_id}; | ||
| 781 | |||
| 782 | # Validate the event structure first | ||
| 783 | my $error = $self->_validate_event($event); | ||
| 784 | if ($error) { | ||
| 785 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => ($event->id // ''), accepted => 0, message => $error)->serialize); | ||
| 786 | return; | ||
| 787 | } | ||
| 788 | |||
| 789 | # Kind must be 22242 | ||
| 790 | unless ($event->kind == 22242) { | ||
| 791 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'invalid: auth event must be kind 22242')->serialize); | ||
| 792 | return; | ||
| 793 | } | ||
| 794 | |||
| 795 | # created_at must be within ~10 minutes | ||
| 796 | my $now = time(); | ||
| 797 | unless (abs($event->created_at - $now) <= 600) { | ||
| 798 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'invalid: auth event timestamp too far from current time')->serialize); | ||
| 799 | return; | ||
| 800 | } | ||
| 801 | |||
| 802 | # Relay tag must match (if relay_url is configured) | ||
| 803 | if (defined $self->relay_url) { | ||
| 804 | my $got_relay; | ||
| 805 | for my $tag (@{$event->_tags}) { | ||
| 806 | if ($tag->[0] eq 'relay') { | ||
| 807 | $got_relay = $tag->[1]; | ||
| 808 | last; | ||
| 809 | } | ||
| 810 | } | ||
| 811 | unless (defined $got_relay && _relay_host_matches($self->relay_url, $got_relay)) { | ||
| 812 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'invalid: relay URL does not match')->serialize); | ||
| 813 | return; | ||
| 814 | } | ||
| 815 | } | ||
| 816 | |||
| 817 | # Challenge tag must match | ||
| 818 | my $expected_challenge = $self->_challenges->{$conn_id}; | ||
| 819 | my $got_challenge; | ||
| 820 | for my $tag (@{$event->_tags}) { | ||
| 821 | if ($tag->[0] eq 'challenge') { | ||
| 822 | $got_challenge = $tag->[1]; | ||
| 823 | last; | ||
| 824 | } | ||
| 825 | } | ||
| 826 | unless (defined $got_challenge && $got_challenge eq $expected_challenge) { | ||
| 827 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 0, message => 'invalid: challenge does not match')->serialize); | ||
| 828 | return; | ||
| 829 | } | ||
| 830 | |||
| 831 | # Track the authenticated pubkey for this connection | ||
| 832 | $self->_authenticated->{$conn_id}{$event->pubkey} = 1; | ||
| 833 | |||
| 834 | $conn->send(Net::Nostr::Message->new(type => 'OK', event_id => $event->id, accepted => 1, message => '')->serialize); | ||
| 835 | } | ||
| 836 | |||
| 837 | sub _handle_req { | ||
| 838 | my ($self, $conn_id, $sub_id, @filters) = @_; | ||
| 839 | my $conn = $self->_connections->{$conn_id}; | ||
| 840 | |||
| 841 | # Max filters per REQ | ||
| 842 | if (defined $self->max_filters && @filters > $self->max_filters) { | ||
| 843 | $conn->send(Net::Nostr::Message->new( | ||
| 844 | type => 'CLOSED', subscription_id => $sub_id, | ||
| 845 | message => "error: too many filters", | ||
| 846 | )->serialize); | ||
| 847 | return; | ||
| 848 | } | ||
| 849 | |||
| 850 | # Max subscriptions per connection (new subs only, replacing is free) | ||
| 851 | if (defined $self->max_subscriptions) { | ||
| 852 | my $existing = $self->_subscriptions->{$conn_id} // {}; | ||
| 853 | if (!exists $existing->{$sub_id} | ||
| 854 | && scalar(keys %$existing) >= $self->max_subscriptions) { | ||
| 855 | $conn->send(Net::Nostr::Message->new( | ||
| 856 | type => 'CLOSED', subscription_id => $sub_id, | ||
| 857 | message => "error: too many subscriptions", | ||
| 858 | )->serialize); | ||
| 859 | return; | ||
| 860 | } | ||
| 861 | } | ||
| 862 | |||
| 863 | # Cap filter limits | ||
| 864 | for my $f (@filters) { | ||
| 865 | if (defined $self->default_limit && !defined $f->limit) { | ||
| 866 | $f->limit($self->default_limit); | ||
| 867 | } | ||
| 868 | if (defined $self->max_limit) { | ||
| 869 | if (!defined $f->limit || $f->limit > $self->max_limit) { | ||
| 870 | $f->limit($self->max_limit); | ||
| 871 | } | ||
| 872 | } | ||
| 873 | } | ||
| 874 | |||
| 875 | $self->_subscriptions->{$conn_id} //= {}; | ||
| 876 | # Remove old index entries if replacing an existing subscription | ||
| 877 | my $old_filters = $self->_subscriptions->{$conn_id}{$sub_id}; | ||
| 878 | $self->_remove_from_sub_index($conn_id, $sub_id, $old_filters) if $old_filters; | ||
| 879 | $self->_subscriptions->{$conn_id}{$sub_id} = \@filters; | ||
| 880 | $self->_add_to_sub_index($conn_id, $sub_id, \@filters); | ||
| 881 | |||
| 882 | my $results = $self->store->query(\@filters); | ||
| 883 | |||
| 884 | for my $event (@$results) { | ||
| 885 | $conn->send(Net::Nostr::Message->new(type => 'EVENT', subscription_id => $sub_id, event => $event)->serialize); | ||
| 886 | } | ||
| 887 | |||
| 888 | $conn->send(Net::Nostr::Message->new(type => 'EOSE', subscription_id => $sub_id)->serialize); | ||
| 889 | } | ||
| 890 | |||
| 891 | sub _handle_count { | ||
| 892 | my ($self, $conn_id, $sub_id, @filters) = @_; | ||
| 893 | my $conn = $self->_connections->{$conn_id}; | ||
| 894 | |||
| 895 | if (defined $self->max_filters && @filters > $self->max_filters) { | ||
| 896 | $conn->send(Net::Nostr::Message->new( | ||
| 897 | type => 'CLOSED', subscription_id => $sub_id, | ||
| 898 | message => "error: too many filters", | ||
| 899 | )->serialize); | ||
| 900 | return; | ||
| 901 | } | ||
| 902 | |||
| 903 | my $count = $self->store->count(\@filters); | ||
| 904 | |||
| 905 | $conn->send(Net::Nostr::Message->new( | ||
| 906 | type => 'COUNT', subscription_id => $sub_id, count => $count, | ||
| 907 | )->serialize); | ||
| 908 | } | ||
| 909 | |||
| 910 | sub _handle_close { | ||
| 911 | my ($self, $conn_id, $sub_id) = @_; | ||
| 912 | if ($self->_subscriptions->{$conn_id}) { | ||
| 913 | my $filters = $self->_subscriptions->{$conn_id}{$sub_id}; | ||
| 914 | $self->_remove_from_sub_index($conn_id, $sub_id, $filters) if $filters; | ||
| 915 | delete $self->_subscriptions->{$conn_id}{$sub_id}; | ||
| 916 | } | ||
| 917 | } | ||
| 918 | |||
| 919 | sub _handle_neg_open { | ||
| 920 | my ($self, $conn_id, $msg) = @_; | ||
| 921 | my $conn = $self->_connections->{$conn_id}; | ||
| 922 | my $sub_id = $msg->subscription_id; | ||
| 923 | |||
| 924 | # Per spec: if NEG-OPEN is issued for a currently open subscription ID, | ||
| 925 | # the existing subscription is first closed. | ||
| 926 | delete $self->_neg_sessions->{$conn_id}{$sub_id}; | ||
| 927 | |||
| 928 | # Build server-side Negentropy from ALL matching events. | ||
| 929 | # Negentropy requires the complete set, so strip any limit from the filter. | ||
| 930 | my $filter_hash = $msg->filter->to_hash; | ||
| 931 | delete $filter_hash->{limit}; | ||
| 932 | my $unlimited_filter = Net::Nostr::Filter->new(%$filter_hash); | ||
| 933 | |||
| 934 | my $ne = Net::Nostr::Negentropy->new; | ||
| 935 | my $events = $self->store->query([$unlimited_filter]); | ||
| 936 | for my $ev (@$events) { | ||
| 937 | $ne->add_item($ev->created_at, $ev->id); | ||
| 938 | } | ||
| 939 | $ne->seal; | ||
| 940 | |||
| 941 | my ($response, $have, $need) = eval { $ne->reconcile($msg->neg_msg) }; | ||
| 942 | if ($@) { | ||
| 943 | my $reason = $@; | ||
| 944 | $reason =~ s/\n\z//; | ||
| 945 | $conn->send(Net::Nostr::Message->new( | ||
| 946 | type => 'NEG-ERR', subscription_id => $sub_id, | ||
| 947 | message => "error: $reason", | ||
| 948 | )->serialize); | ||
| 949 | return; | ||
| 950 | } | ||
| 951 | |||
| 952 | if (defined $response) { | ||
| 953 | $self->_neg_sessions->{$conn_id}{$sub_id} = $ne; | ||
| 954 | $conn->send(Net::Nostr::Message->new( | ||
| 955 | type => 'NEG-MSG', subscription_id => $sub_id, | ||
| 956 | neg_msg => $response, | ||
| 957 | )->serialize); | ||
| 958 | } else { | ||
| 959 | # Protocol complete in one round — send empty NEG-MSG | ||
| 960 | # (response is undef when all ranges match) | ||
| 961 | $conn->send(Net::Nostr::Message->new( | ||
| 962 | type => 'NEG-MSG', subscription_id => $sub_id, | ||
| 963 | neg_msg => $response // _empty_neg_msg(), | ||
| 964 | )->serialize); | ||
| 965 | } | ||
| 966 | } | ||
| 967 | |||
| 968 | sub _handle_neg_msg { | ||
| 969 | my ($self, $conn_id, $msg) = @_; | ||
| 970 | my $conn = $self->_connections->{$conn_id}; | ||
| 971 | my $sub_id = $msg->subscription_id; | ||
| 972 | |||
| 973 | my $ne = $self->_neg_sessions->{$conn_id}{$sub_id}; | ||
| 974 | unless ($ne) { | ||
| 975 | $conn->send(Net::Nostr::Message->new( | ||
| 976 | type => 'NEG-ERR', subscription_id => $sub_id, | ||
| 977 | message => "closed: no open negentropy session", | ||
| 978 | )->serialize); | ||
| 979 | return; | ||
| 980 | } | ||
| 981 | |||
| 982 | my ($response, $have, $need) = eval { $ne->reconcile($msg->neg_msg) }; | ||
| 983 | if ($@) { | ||
| 984 | my $reason = $@; | ||
| 985 | $reason =~ s/\n\z//; | ||
| 986 | delete $self->_neg_sessions->{$conn_id}{$sub_id}; | ||
| 987 | $conn->send(Net::Nostr::Message->new( | ||
| 988 | type => 'NEG-ERR', subscription_id => $sub_id, | ||
| 989 | message => "error: $reason", | ||
| 990 | )->serialize); | ||
| 991 | return; | ||
| 992 | } | ||
| 993 | |||
| 994 | if (defined $response) { | ||
| 995 | $conn->send(Net::Nostr::Message->new( | ||
| 996 | type => 'NEG-MSG', subscription_id => $sub_id, | ||
| 997 | neg_msg => $response, | ||
| 998 | )->serialize); | ||
| 999 | } else { | ||
| 1000 | delete $self->_neg_sessions->{$conn_id}{$sub_id}; | ||
| 1001 | } | ||
| 1002 | } | ||
| 1003 | |||
| 1004 | sub _handle_neg_close { | ||
| 1005 | my ($self, $conn_id, $sub_id) = @_; | ||
| 1006 | delete $self->_neg_sessions->{$conn_id}{$sub_id} | ||
| 1007 | if $self->_neg_sessions->{$conn_id}; | ||
| 1008 | } | ||
| 1009 | |||
| 1010 | # Minimal valid negentropy message: version byte + no ranges (all skip) | ||
| 1011 | sub _empty_neg_msg { | ||
| 1012 | return '61'; | ||
| 1013 | } | ||
| 1014 | |||
| 1015 | sub _add_to_sub_index { | ||
| 1016 | my ($self, $conn_id, $sub_id, $filters) = @_; | ||
| 1017 | my $key = "$conn_id\0$sub_id"; | ||
| 1018 | my $entry = [$conn_id, $sub_id]; | ||
| 1019 | my $all_have_kinds = 1; | ||
| 1020 | for my $f (@$filters) { | ||
| 1021 | if ($f->kinds) { | ||
| 1022 | for my $k (@{$f->kinds}) { | ||
| 1023 | $self->_sub_by_kind->{$k}{$key} = $entry; | ||
| 1024 | } | ||
| 1025 | } else { | ||
| 1026 | $all_have_kinds = 0; | ||
| 1027 | } | ||
| 1028 | } | ||
| 1029 | unless ($all_have_kinds) { | ||
| 1030 | $self->_sub_no_kind->{$key} = $entry; | ||
| 1031 | } | ||
| 1032 | } | ||
| 1033 | |||
| 1034 | sub _remove_from_sub_index { | ||
| 1035 | my ($self, $conn_id, $sub_id, $filters) = @_; | ||
| 1036 | my $key = "$conn_id\0$sub_id"; | ||
| 1037 | if ($filters) { | ||
| 1038 | for my $f (@$filters) { | ||
| 1039 | if ($f->kinds) { | ||
| 1040 | for my $k (@{$f->kinds}) { | ||
| 1041 | delete $self->_sub_by_kind->{$k}{$key}; | ||
| 1042 | } | ||
| 1043 | } | ||
| 1044 | } | ||
| 1045 | } | ||
| 1046 | delete $self->_sub_no_kind->{$key}; | ||
| 1047 | } | ||
| 1048 | |||
| 1049 | sub _remove_all_sub_indexes { | ||
| 1050 | my ($self, $conn_id) = @_; | ||
| 1051 | my $conn_subs = $self->_subscriptions->{$conn_id} || {}; | ||
| 1052 | for my $sub_id (keys %$conn_subs) { | ||
| 1053 | $self->_remove_from_sub_index($conn_id, $sub_id, $conn_subs->{$sub_id}); | ||
| 1054 | } | ||
| 1055 | } | ||
| 1056 | |||
| 1057 | 1; | ||
| 1058 | |||
| 1059 | __END__ | ||