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 82 ▶use strictures 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 82 ▶use Net::Nostr::_ConstructorArgs ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 82 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 82 ▶use JSON ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 82 ▶use Digest::SHA qw(sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 82 ▶use Storable ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 82 ▶use Crypt::PK::ECC;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 82 ▶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  
81 croak "sig must be 128-char lowercase hex"
82 if defined $self->{sig} && $self->{sig} !~ $HEX128;
83  
84 croak "id must be 64-char lowercase hex"
85 if defined $self->{id} && $self->{id} !~ $HEX64;
86  
87 # created_at must be a non-negative integer (unix timestamp)
88 if (defined $self->{created_at}) {
89 croak "created_at must be a non-negative integer"
90 unless $self->{created_at} =~ /\A\d+\z/;
91 }
92  
93 $self->{created_at} = time() unless defined $self->{created_at};
94  
95 # tags must be an arrayref of arrayrefs of defined strings
96 if (defined $self->{tags}) {
97 croak "tags must be an arrayref"
98 unless ref($self->{tags}) eq 'ARRAY';
99 for my $tag (@{$self->{tags}}) {
100 croak "each tag must be an arrayref of strings"
101 unless ref($tag) eq 'ARRAY';
102 for my $elem (@$tag) {
103 croak "tag elements must be defined strings"
104 unless defined $elem && !ref($elem);
105 }
106 }
107 }
108 $self->{tags} = defined $self->{tags} ? Storable::dclone($self->{tags}) : [];
109 $self->{id} = $self->_calc_id unless $self->{id};
110 return $self;
111 }
112  
113 sub from_wire {
114 my ($class, $hash) = @_;
115 croak "from_wire requires a hashref" unless ref($hash) eq 'HASH';
116  
117 for my $field (qw(id pubkey created_at kind tags content sig)) {
118 croak "$field is required"
119 unless defined $hash->{$field};
120 }
121  
122 return $class->new(%$hash);
123 }
124  
125 sub json_serialize {
126 my ($self) = @_;
127 return $JSON->encode([
128 0,
129 $self->pubkey . '',
130 $self->created_at + 0,
131 $self->kind + 0,
132 $self->{tags},
133 $self->content . ''
134 ]);
135 }
136  
137  
138 sub to_hash {
139 my ($self) = @_;
140 return {
141 id => $self->id,
142 pubkey => $self->pubkey,
143 created_at => $self->created_at,
144 kind => $self->kind,
145 tags => Storable::dclone($self->{tags}),
146 content => $self->content,
147 sig => $self->sig,
148 };
149 }
150  
151 sub is_regular {
152 my $k = shift->kind;
153 return ($k == 1 || $k == 2 || ($k >= 4 && $k < 45) || $k == 78 || ($k >= 1000 && $k < 10000));
154 }
155  
156 sub is_replaceable {
157 my $k = shift->kind;
158 return ($k == 0 || $k == 3 || ($k >= 10000 && $k < 20000));
159 }
160  
161 sub is_ephemeral {
162 my $k = shift->kind;
163 return ($k >= 20000 && $k < 30000);
164 }
165  
166 sub is_addressable {
167 my $k = shift->kind;
168 return ($k >= 30000 && $k < 40000);
169 }
170  
171 sub difficulty {
172 my ($self) = @_;
173 my $id = $self->id;
174 my $count = 0;
175 for my $i (0 .. length($id) - 1) {
176 my $nibble = hex(substr($id, $i, 1));
177 if ($nibble == 0) {
178 $count += 4;
179 } else {
180 # count leading zero bits in this nibble (4-bit value)
181 my $bits = 0;
182 for my $shift (3, 2, 1, 0) {
183 last if $nibble & (1 << $shift);
184 $bits++;
185 }
186 $count += $bits;
187 last;
188 }
189 }
190 return $count;
191 }
192  
193 sub committed_target_difficulty {
194 my ($self) = @_;
195 for my $tag (@{$self->{tags}}) {
196 if ($tag->[0] eq 'nonce' && defined $tag->[2]) {
197 return $tag->[2] + 0;
198 }
199 }
200 return undef;
201 }
202  
203 sub mine {
204 my ($self, $target) = @_;
205 croak "target difficulty required" unless defined $target;
206  
207 # Build tags: replace existing nonce tag or add one
208 my @tags = grep { $_->[0] ne 'nonce' } @{$self->{tags}};
209  
210 my $nonce = 0;
211 while (1) {
212 my $candidate = Net::Nostr::Event->new(
213 pubkey => $self->pubkey,
214 kind => $self->kind,
215 content => $self->content,
216 tags => [@tags, ['nonce', "$nonce", "$target"]],
217 created_at => time(),
218 );
219 if ($candidate->difficulty >= $target) {
220 return $candidate;
221 }
222 $nonce++;
223 }
224 }
225  
226 sub d_tag {
227 my ($self) = @_;
228 for my $tag (@{$self->{tags}}) {
229 return ($tag->[1] // '') if $tag->[0] eq 'd';
230 }
231 return '';
232 }
233  
234 sub expiration {
235 my ($self) = @_;
236 for my $tag (@{$self->{tags}}) {
237 return $tag->[1] + 0 if $tag->[0] eq 'expiration';
238 }
239 return undef;
240 }
241  
242 sub is_expired {
243 my ($self, $now) = @_;
244 my $exp = $self->expiration;
245 return 0 unless defined $exp;
246 $now //= time();
247 return $now > $exp;
248 }
249  
250 sub _tags { $_[0]->{tags} }
251  
252 sub is_protected {
253 my ($self) = @_;
254 for my $tag (@{$self->{tags}}) {
255 return 1 if $tag->[0] eq '-' && @$tag == 1;
256 }
257 return 0;
258 }
259  
260 sub content_warning {
261 my ($self) = @_;
262 for my $tag (@{$self->{tags}}) {
263 return ($tag->[1] // '') if $tag->[0] eq 'content-warning';
264 }
265 return undef;
266 }
267  
268 sub has_content_warning {
269 my ($self) = @_;
270 return defined $self->content_warning;
271 }
272  
273 sub content_warning_tag {
274 my ($class, $reason) = @_;
275 return defined $reason && $reason ne ''
276 ? ['content-warning', $reason]
277 : ['content-warning'];
278 }
279  
280 sub verify_sig {
281 my ($self, $key) = @_;
282 croak "pubkey does not match event pubkey"
283 unless $key->pubkey_hex eq $self->pubkey;
284 my $sig_raw = pack 'H*', $self->sig;
285 my $verifier = Crypt::PK::ECC::Schnorr->new(\$key->pubkey_der);
286 return $verifier->verify_message(pack('H*', $self->id), $sig_raw);
287 }
288  
289 sub validate {
290 my ($self) = @_;
291 croak "sig is required for validation"
292 unless defined $self->sig && length $self->sig;
293  
294 my $expected_id = sha256_hex($self->json_serialize);
295 croak "id does not match event hash"
296 unless $self->id eq $expected_id;
297  
298 my $pubkey_raw = pack 'H*', $self->pubkey;
299 my $pk = Crypt::PK::ECC->new;
300 $pk->import_key_raw("\x02" . $pubkey_raw, 'secp256k1');
301 my $verifier = Crypt::PK::ECC::Schnorr->new(\$pk->export_key_der('public'));
302 my $sig_raw = pack 'H*', $self->sig;
303 croak "signature is invalid"
304 unless $verifier->verify_message(pack('H*', $self->id), $sig_raw);
305  
306 return 1;
307 }
308  
309 sub _calc_id {
310 my ($self) = @_;
311 my $id = sha256_hex($self->json_serialize);
312 return $id;
313 }
314  
315 1;
316  
317 __END__
« HttpAuth.pm ↑ Summary Group.pm »