Event.pm

filter: Statementstmt 91.6% 22 / 24 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.7% 30 / 32 CC 1 SCAR 0.4
CC
1
Cov
92%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« HttpAuth.pm ↑ Summary Group.pm »
1 package Net::Nostr::Event;
2  
3 83 ▶use strictures 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 83 ▶use Net::Nostr::_ConstructorArgs ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 83 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 83 ▶use JSON ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 83 ▶use Digest::SHA qw(sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 83 ▶use Storable ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 83 ▶use Crypt::PK::ECC;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 0 ▶use Crypt::PK::ECC::Schnorr;
Subroutine BEGIN: called CC=1 SCAR=2.6
13  
14 # Pre-declare read-only accessors so Class::Tiny registers them as
15 # attributes but does not generate read-write setters.
16 use subs qw(id pubkey created_at kind tags content sig);
17  
18 use Class::Tiny qw(
19 id
20 pubkey
21 created_at
22 kind
23 tags
24 content
25 sig
26 );
27  
28 # Read-only accessors for body fields (affect event ID).
29 # Mutation after construction would silently invalidate the ID and any
30 # signature, so setters are intentionally forbidden.
31 for my $field (qw(id pubkey created_at kind tags content)) {
32 no strict 'refs';
33 *$field = sub {
34 my $self = shift;
35 croak "$field is read-only after construction" if @_;
36 return $field eq 'tags'
37 ? Storable::dclone($self->{$field})
38 : $self->{$field};
39 };
40 }
41 my $HEX64 = qr/\A[0-9a-f]{64}\z/;
42 my $HEX128 = qr/\A[0-9a-f]{128}\z/;
43 my $JSON = JSON->new->utf8;
44  
45 # sig is the only writable field -- it does not participate in the event
46 # ID computation, so mutating it (e.g. after signing) is safe.
47 # Validates format on set; accepts undef to clear before signing.
48 sub sig {
49 my $self = shift;
50 if (@_) {
51 my $val = $_[0];
52 croak "sig must be 128-char lowercase hex"
53 if defined $val && $val !~ $HEX128;
54 $self->{sig} = $val;
55 return $val;
56 }
57 return $self->{sig};
58 }
59  
60 sub new {
61 my $class = shift;
62 my $self = bless { Net::Nostr::_ConstructorArgs::normalize(@_) }, $class;
63  
64 my %known; @known{Class::Tiny->get_all_attributes_for($class)} = ();
65 my @unknown = grep { !exists $known{$_} } keys %$self;
66 croak "unknown argument(s): " . join(', ', sort @unknown) if @unknown;
67  
68 croak "pubkey is required"
69 unless defined $self->{pubkey};
70 croak "pubkey must be 64-char lowercase hex"
71 unless $self->{pubkey} =~ $HEX64;
72  
73 croak "kind is required"
74 unless defined $self->{kind};
75 croak "kind must be an integer between 0 and 65535"
76 unless $self->{kind} =~ /\A\d+\z/ && $self->{kind} >= 0 && $self->{kind} <= 65535;
77  
78 croak "content is required"
79 unless defined $self->{content};
80 croak "content must be a string"
81 if ref $self->{content};
82  
83 croak "sig must be 128-char lowercase hex"
84 if defined $self->{sig} && $self->{sig} !~ $HEX128;
85  
86 croak "id must be 64-char lowercase hex"
87 if defined $self->{id} && $self->{id} !~ $HEX64;
88  
89 # created_at must be a non-negative integer (unix timestamp)
90 if (defined $self->{created_at}) {
91 croak "created_at must be a non-negative integer"
92 unless $self->{created_at} =~ /\A\d+\z/;
93 }
94  
95 $self->{created_at} = time() unless defined $self->{created_at};
96  
97 # tags must be an arrayref of arrayrefs of defined strings
98 if (defined $self->{tags}) {
99 croak "tags must be an arrayref"
100 unless ref($self->{tags}) eq 'ARRAY';
101 for my $tag (@{$self->{tags}}) {
102 croak "each tag must be an arrayref of strings"
103 unless ref($tag) eq 'ARRAY';
104 for my $elem (@$tag) {
105 croak "tag elements must be defined strings"
106 unless defined $elem && !ref($elem);
107 }
108 }
109 }
110 $self->{tags} = defined $self->{tags} ? Storable::dclone($self->{tags}) : [];
111 $self->{id} = $self->_calc_id unless $self->{id};
112 return $self;
113 }
114  
115 sub from_wire {
116 my ($class, $hash) = @_;
117 croak "from_wire requires a hashref" unless ref($hash) eq 'HASH';
118  
119 for my $field (qw(id pubkey created_at kind tags content sig)) {
120 croak "$field is required"
121 unless defined $hash->{$field};
122 }
123  
124 return $class->new(%$hash);
125 }
126  
127 sub json_serialize {
128 my ($self) = @_;
129 return $JSON->encode([
130 0,
131 $self->pubkey . '',
132 $self->created_at + 0,
133 $self->kind + 0,
134 $self->{tags},
135 $self->content . ''
136 ]);
137 }
138  
139  
140 sub to_hash {
141 my ($self) = @_;
142 return {
143 id => $self->id,
144 pubkey => $self->pubkey,
145 created_at => $self->created_at,
146 kind => $self->kind,
147 tags => Storable::dclone($self->{tags}),
148 content => $self->content,
149 sig => $self->sig,
150 };
151 }
152  
153 sub is_regular {
154 my $k = shift->kind;
155 return ($k == 1 || $k == 2 || ($k >= 4 && $k < 45) || $k == 78 || ($k >= 1000 && $k < 10000));
156 }
157  
158 sub is_replaceable {
159 my $k = shift->kind;
160 return ($k == 0 || $k == 3 || ($k >= 10000 && $k < 20000));
161 }
162  
163 sub is_ephemeral {
164 my $k = shift->kind;
165 return ($k >= 20000 && $k < 30000);
166 }
167  
168 sub is_addressable {
169 my $k = shift->kind;
170 return ($k >= 30000 && $k < 40000);
171 }
172  
173 sub difficulty {
174 my ($self) = @_;
175 my $id = $self->id;
176 my $count = 0;
177 for my $i (0 .. length($id) - 1) {
178 my $nibble = hex(substr($id, $i, 1));
179 if ($nibble == 0) {
180 $count += 4;
181 } else {
182 # count leading zero bits in this nibble (4-bit value)
183 my $bits = 0;
184 for my $shift (3, 2, 1, 0) {
185 last if $nibble & (1 << $shift);
186 $bits++;
187 }
188 $count += $bits;
189 last;
190 }
191 }
192 return $count;
193 }
194  
195 sub committed_target_difficulty {
196 my ($self) = @_;
197 for my $tag (@{$self->{tags}}) {
198 if ($tag->[0] eq 'nonce' && defined $tag->[2]) {
199 return $tag->[2] + 0;
200 }
201 }
202 return undef;
203 }
204  
205 sub mine {
206 my ($self, $target) = @_;
207 croak "target difficulty required" unless defined $target;
208  
209 # Build tags: replace existing nonce tag or add one
210 my @tags = grep { $_->[0] ne 'nonce' } @{$self->{tags}};
211  
212 my $nonce = 0;
213 while (1) {
214 my $candidate = Net::Nostr::Event->new(
215 pubkey => $self->pubkey,
216 kind => $self->kind,
217 content => $self->content,
218 tags => [@tags, ['nonce', "$nonce", "$target"]],
219 created_at => time(),
220 );
221 if ($candidate->difficulty >= $target) {
222 return $candidate;
223 }
224 $nonce++;
225 }
226 }
227  
228 sub d_tag {
229 my ($self) = @_;
230 for my $tag (@{$self->{tags}}) {
231 return ($tag->[1] // '') if $tag->[0] eq 'd';
232 }
233 return '';
234 }
235  
236 sub expiration {
237 my ($self) = @_;
238 for my $tag (@{$self->{tags}}) {
239 return $tag->[1] + 0 if $tag->[0] eq 'expiration';
240 }
241 return undef;
242 }
243  
244 sub is_expired {
245 my ($self, $now) = @_;
246 my $exp = $self->expiration;
247 return 0 unless defined $exp;
248 $now //= time();
249 return $now > $exp;
250 }
251  
252 sub _tags { $_[0]->{tags} }
253  
254 sub is_protected {
255 my ($self) = @_;
256 for my $tag (@{$self->{tags}}) {
257 return 1 if $tag->[0] eq '-' && @$tag == 1;
258 }
259 return 0;
260 }
261  
262 sub content_warning {
263 my ($self) = @_;
264 for my $tag (@{$self->{tags}}) {
265 return ($tag->[1] // '') if $tag->[0] eq 'content-warning';
266 }
267 return undef;
268 }
269  
270 sub has_content_warning {
271 my ($self) = @_;
272 return defined $self->content_warning;
273 }
274  
275 sub content_warning_tag {
276 my ($class, $reason) = @_;
277 return defined $reason && $reason ne ''
278 ? ['content-warning', $reason]
279 : ['content-warning'];
280 }
281  
282 sub verify_sig {
283 my ($self, $key) = @_;
284 croak "pubkey does not match event pubkey"
285 unless $key->pubkey_hex eq $self->pubkey;
286 my $sig_raw = pack 'H*', $self->sig;
287 my $verifier = Crypt::PK::ECC::Schnorr->new(\$key->pubkey_der);
288 return $verifier->verify_message(pack('H*', $self->id), $sig_raw);
289 }
290  
291 sub validate {
292 my ($self) = @_;
293 croak "sig is required for validation"
294 unless defined $self->sig && length $self->sig;
295  
296 my $expected_id = sha256_hex($self->json_serialize);
297 croak "id does not match event hash"
298 unless $self->id eq $expected_id;
299  
300 my $pubkey_raw = pack 'H*', $self->pubkey;
301 my $pk = Crypt::PK::ECC->new;
302 $pk->import_key_raw("\x02" . $pubkey_raw, 'secp256k1');
303 my $verifier = Crypt::PK::ECC::Schnorr->new(\$pk->export_key_der('public'));
304 my $sig_raw = pack 'H*', $self->sig;
305 croak "signature is invalid"
306 unless $verifier->verify_message(pack('H*', $self->id), $sig_raw);
307  
308 return 1;
309 }
310  
311 sub _calc_id {
312 my ($self) = @_;
313 my $id = sha256_hex($self->json_serialize);
314 return $id;
315 }
316  
317 1;
318  
319 __END__
« HttpAuth.pm ↑ Summary Group.pm »