Crypto/Block.pm

filter: Statementstmt 85.4% 135 / 158 Branchbran 67.6% 23 / 34 Conditioncond 40.0% 8 / 20 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 96.3% 26 / 27 Podpod 88.8% 8 / 9 totaltotal 77.2% 200 / 259 CC 30 SCAR 17.2
CC
30
Cov
78%
dump
12.0
from_serialized
11.3
_build_height
10.6
CRAP 5.6
« Crypto/Script/Tree.pm ↑ Summary Crypto/Script/Runner.pm »
1 package Bitcoin::Crypto::Block;
2 8 $Bitcoin::Crypto::Block::VERSION = '4.006';
3 8 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 8 ▶use Mooish::Base -standard;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 8 ▶use Types::Common -sigs;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 8 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 8 ▶use Feature::Compat::Try;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 8 ▶use Bitcoin::Crypto qw(btc_transaction);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 8 ▶use Bitcoin::Crypto::Util::Internal qw(pack_compactsize unpack_compactsize hash256 to_format);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 8 ▶use Bitcoin::Crypto::Script::Runner;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 8 ▶use Bitcoin::Crypto::Types -types;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 8 ▶use Bitcoin::Crypto::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 # Block header fields
18 8 has param 'version' => (
19 isa => IntMaxBits [32],
20 default => 1,
21 writer => 1,
22 );
23  
24 8 has option 'prev_block_hash' => (
25 coerce => ByteStr,
26 writer => 1,
27 );
28  
29 8 has field 'merkle_root' => (
30 isa => ByteStr,
31 lazy => 1,
32 clearer => 1,
33 );
34  
35 has param 'timestamp' => (
36 isa => PositiveInt,
37 22 ▶ default => sub { scalar time },
Subroutine __ANON__: called CC=1 SCAR=0.0
38 8 writer => 1,
39 );
40  
41 8 has param 'bits' => (
42 isa => IntMaxBits [32],
43 default => 0x207fffff, # Difficulty bits
44 writer => 1,
45 );
46  
47 8 has param 'nonce' => (
48 isa => IntMaxBits [32],
49 default => 0,
50 writer => 1,
51 );
52  
53 8 has param 'height' => (
54 isa => Maybe [PositiveOrZeroInt],
55 writer => 1,
56 lazy => 1,
57 required => 0,
58 clearer => 1,
59 );
60  
61 8 has option 'previous' => (
62 isa => InstanceOf ['Bitcoin::Crypto::Block'],
63 writer => 1,
64 trigger => 1,
65 );
66  
67 has field 'transactions' => (
68 isa => ArrayRef [InstanceOf ['Bitcoin::Crypto::Transaction']],
69 69 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
70 8 );
71  
72 sub has_transactions
73 24 ▶{
Subroutine has_transactions: called CC=1 SCAR=0.0
Pod documented
74 24 my ($self) = @_;
75  
76 24 return @{$self->transactions} > 0;
77 }
78  
79 # need this written manually because height can be lazy-built conditionally
80 # (when block version is 2 or above and we have transactions, we can get it
81 # from coinbase)
82 sub has_height
83 21 ▶{
Subroutine has_height: called CC=1 SCAR=0.0
Pod undocumented
84 21 return defined $_[0]->height;
85 }
86  
87 sub _build_height
88 5 ▶{
Subroutine _build_height: called CC=8 SCAR=23.6
89 5 my ($self) = @_;
90  
91 5 ▶ return undef unless $self->version >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->version >= 2 1 4 5
92 4 ▶ return undef unless $self->has_transactions;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_transactions 0 4 4
93  
94 4 my $tx = $self->transactions->[0];
95 4 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
unless $tx->is_coinbase 0 4 4
96 'first transaction is not coinbase'
97 ) unless $tx->is_coinbase;
98  
99 # TODO: check if height is minimally encoded?
100 4 my $full_script = $tx->inputs->[0]->signature_script->to_serialized;
101 4 my $size = unpack 'C', substr $full_script, 0, 1;
102 4 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
unless $size and $size == 3 || $size == 5 and length $full_script > $size 0 4 4
Condition33%3/9
$size and $size == 3 || $size == 5 and length $full_script > $size
!ll&&!rl&&r
004
$size and $size == 3 || $size == 5
!ll&&!rl&&r
004
$size == 3 or $size == 5
l!l&&r!l&&!r
400
MC/DC0%0/4
$size and $size == 3 || $size == 5 and length $full_script > $size
$size $size == 3 $size == 5 length $full_script > $size
Truth table16%1/6
A and B or C and D
A= $sizeB= $size == 3C= $size == 5D= length $full_script > $size
ABCDresult
0XXX0
100X0
11X00
10100
11X11
10111
103 'invalid height in coinbase transaction'
104 ) unless $size && ($size == 3 || $size == 5) && length $full_script > $size;
105  
106 4 try {
107 4 my $result = Bitcoin::Crypto::Script::Runner
108 ->to_int(substr $full_script, 1, $size);
109  
110 # numify if bigint
111 4 return "$result";
112 }
113 catch ($e) {
114 0 return undef;
115 }
116 }
117  
118 sub add_transaction
119 1 ▶{
Subroutine add_transaction: called CC=4 SCAR=14.7
Pod documented
120 1 my ($self, @data) = @_;
121  
122 1 my $tx;
123 1 ▶ if (@data == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@data == 1) { } 1 0 1
124 1 $tx = $data[0];
125  
126 1 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($tx) and $tx->isa("Bitcoin::Crypto::Transaction") 0 1 1
Condition33%1/3
builtin::blessed($tx) and $tx->isa("Bitcoin::Crypto::Transaction")
!ll&&!rl&&r
001
MC/DC0%0/2
builtin::blessed($tx) and $tx->isa("Bitcoin::Crypto::Transaction")
builtin::blessed($tx) $tx->isa("Bitcoin::Crypto::Transaction")
Truth table33%1/3
A and B
A= builtin::blessed($tx)B= $tx->isa("Bitcoin::Crypto::Transaction")
ABresult
0X0
100
111
127 'expected a transaction object'
128 ) unless blessed $tx && $tx->isa('Bitcoin::Crypto::Transaction');
129 }
130 else {
131 0 $tx = btc_transaction->new(@data);
132 }
133  
134 1 $tx->set_block($self);
135 1 push @{$self->transactions}, $tx;
136  
137 # Clear cached merkle root if set
138 1 $self->clear_merkle_root;
139  
140 1 return $self;
141 }
142  
143 8 signature_for to_serialized => (
144 method => !!1,
145 named => [
146 witness => Bool,
147 {default => 1},
148 ],
149 bless => !!0,
150 );
151  
152 sub to_serialized
153 20 ▶{
Subroutine to_serialized: called CC=2 SCAR=6.9
154 20 my ($self, $args) = @_;
155  
156 # Bitcoin block serialization format:
157 # - Block header (80 bytes)
158 # - Transaction count (VarInt)
159 # - Transactions (variable length)
160  
161 20 my $serialized = $self->get_header;
162  
163 # Transaction count
164 20 $serialized .= pack_compactsize(scalar @{$self->transactions});
165  
166 # Transactions
167 20 foreach my $tx (@{$self->transactions}) {
168 152 $serialized .= $tx->to_serialized(witness => $args->{witness});
169 }
170  
171 20 return $serialized;
172 }
173  
174 8 signature_for from_serialized => (
175 method => !!1,
176 head => [ByteStr],
177 named => [
178 pos => Maybe [ScalarRef [PositiveOrZeroInt]],
179 {default => undef},
180 ],
181 bless => !!0,
182 );
183  
184 sub from_serialized
185 9 ▶{
Subroutine from_serialized: called CC=11 SCAR=24.3
186 9 my ($class, $serialized, $args) = @_;
187 9 my $partial = !!$args->{pos};
188 9 ▶ my $pos = $partial ? ${$args->{pos}} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$partial ? : 3 6 9
189  
190 # optimization - no need to keep checking bytestrings on every level. It
191 # has already been checked.
192 9 local $Bitcoin::Crypto::Types::CHECK_BYTESTRINGS = !!0;
193  
194 9 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
if length $serialized < 80 1 8 9
195 'serialized block data too short for header'
196 ) if length($serialized) < 80;
197  
198 # Parse block header (80 bytes)
199 8 my ($version, $prev_block_hash, $merkle_root, $timestamp, $bits, $nonce)
200 = unpack "\@$pos Va32a32VVV", $serialized;
201 8 $pos += 80;
202  
203 8 $prev_block_hash = reverse $prev_block_hash;
204 8 $merkle_root = reverse $merkle_root;
205  
206 # Parse transaction count
207 8 my $tx_count = unpack_compactsize $serialized, \$pos;
208  
209 8 my @transactions;
210  
211 # Parse transactions
212 8 for my $tx_index (1 .. $tx_count) {
213 47 push @transactions, btc_transaction->from_serialized(
214 $serialized, pos => \$pos
215 );
216 }
217  
218 Bitcoin::Crypto::Exception::Block->raise(
219 8 ▶ 'serialized block data is corrupted'
Branch: 1 branch
BranchTrueFalseTotal
if not $partial and $pos != length $serialized 0 8 8
Condition66%2/3
not $partial and $pos != length $serialized
!ll&&!rl&&r
350
MC/DC0%0/2
not $partial and $pos != length $serialized
not $partial $pos != length $serialized
Truth table66%2/3
not(A) and B
A= not $partialB= $pos != length $serialized
ABresult
0X0
100
111
220 ) if !$partial && $pos != length $serialized;
221  
222 8 ▶ ${$args->{pos}} = $pos
Branch: 1 branch
BranchTrueFalseTotal
if $partial 3 5 8
223 if $partial;
224  
225 8 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
unless @transactions > 0 and $transactions[0]->is_coinbase 0 8 8
Condition33%1/3
@transactions > 0 and $transactions[0]->is_coinbase
!ll&&!rl&&r
008
MC/DC0%0/2
@transactions > 0 and $transactions[0]->is_coinbase
@transactions > 0 $transactions[0]->is_coinbase
Truth table33%1/3
A and B
A= @transactions > 0B= $transactions[0]->is_coinbase
ABresult
0X0
100
111
226 'block requires a coinbase transaction'
227 ) unless @transactions > 0 && $transactions[0]->is_coinbase;
228  
229 8 my $block = $class->new(
230 version => $version,
231 prev_block_hash => $prev_block_hash,
232 timestamp => $timestamp,
233 bits => $bits,
234 nonce => $nonce,
235 );
236  
237 8 @{$block->transactions} = @transactions;
238  
239 8 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
if $block->merkle_root ne $merkle_root 0 8 8
240 'serialized block merkle root is incorrect'
241 ) if $block->merkle_root ne $merkle_root;
242  
243 8 foreach my $tx (@transactions) {
244 47 $tx->set_block($block);
245 }
246  
247 8 return $block;
248 }
249  
250 sub get_hash
251 9 ▶{
Subroutine get_hash: called CC=1 SCAR=0.0
Pod documented
252 9 my ($self) = @_;
253 9 return scalar reverse hash256($self->get_header);
254 }
255  
256 sub get_header
257 29 ▶{
Subroutine get_header: called CC=2 SCAR=7.2
Pod documented
258 29 my ($self) = @_;
259  
260 # - version (4 bytes)
261 # - prev_block_hash (32 bytes)
262 # - merkle_root (32 bytes)
263 # - timestamp (4 bytes)
264 # - bits (4 bytes)
265 # - nonce (4 bytes)
266  
267 29 ▶ return pack 'Va32a32VVV',
Condition50%1/2
$self->prev_block_hash // "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
l!l
290
MC/DC0%0/1
$self->prev_block_hash // "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
$self->prev_block_hash
Truth table50%1/2
A
A= $self->prev_block_hash
Aresult
11
00
268 $self->version,
269 scalar(reverse($self->prev_block_hash // ("\x00" x 32))),
270 scalar(reverse $self->merkle_root),
271 $self->timestamp,
272 $self->bits,
273 $self->nonce,
274 ;
275 }
276  
277 sub _trigger_previous
278 20 ▶{
Subroutine _trigger_previous: called CC=2 SCAR=8.1
279 20 my ($self) = @_;
280  
281 20 ▶ return unless $self->previous->has_transactions;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->previous->has_transactions 20 0 20
282  
283 0 $self->set_prev_block_hash($self->previous->get_hash);
284 }
285  
286 sub _build_merkle_root
287 10 ▶{
Subroutine _build_merkle_root: called CC=2 SCAR=6.9
288 10 my ($self) = @_;
289  
290 10 my @txs = map { $_->to_serialized(witness => 0) } @{$self->transactions};
291  
292 10 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
unless @txs > 0 1 9 10
293 'cannot calculate merkle root for empty block'
294 ) unless @txs > 0;
295  
296 9 return scalar reverse Bitcoin::Crypto::Util::Internal::merkle_root(\@txs);
297 }
298  
299 sub median_time_past
300 14 ▶{
Subroutine median_time_past: called CC=4 SCAR=13.9
Pod documented
301 14 my ($self) = @_;
302  
303 14 my @stamps;
304  
305 14 my $current = $self;
306 14 for my $count (1 .. 11) {
307  
308 # NOTE: since we do not expect full blockchain to be available, exit
309 # the loop early if we didn't get full 11 blocks required for MTP. Same
310 # would happen if we had a full blockchain, but were using very early
311 # blocks
312 29 ▶ last unless $current->has_previous;
Branch: 1 branch
BranchTrueFalseTotal
unless $current->has_previous 13 16 29
313 16 $current = $current->previous;
314  
315 16 push @stamps, $current->timestamp;
316 }
317  
318 14 ▶ return $self->timestamp unless @stamps;
Branch: 1 branch
BranchTrueFalseTotal
unless @stamps 12 2 14
319 2 @stamps = sort { $a <=> $b } @stamps;
320 2 return $stamps[int(@stamps / 2)];
321 }
322  
323 sub size
324 5 ▶{
Subroutine size: called CC=1 SCAR=0.0
Pod documented
325 5 my ($self) = @_;
326 5 return length $self->to_serialized;
327 }
328  
329 sub weight
330 5 ▶{
Subroutine weight: called CC=1 SCAR=0.0
Pod documented
331 5 my ($self) = @_;
332  
333 5 my $base_size = length $self->to_serialized(witness => 0);
334 5 my $total_size = length $self->to_serialized(witness => 1);
335  
336 # non-witness data is 4 times heavier than witness data
337 5 return $base_size * 3 + $total_size;
338 }
339  
340 8 signature_for verify => (
341 method => !!1,
342 named => [
343 ],
344 bless => !!0,
345 );
346  
347 # TODO: placeholder for actual block verification method. Not very usable and
348 # not documented yet.
349 sub verify
350 {
351 my ($self, $args) = @_;
352  
353 # TODO: version 2 blocks with no coinbase height are only invalid if version 2
354 # blocks are super-majority. There should be a consensus class to track that
355 if ($self->version >= 2) {
356 $self->clear_height;
357 Bitcoin::Crypto::Exception::Block->raise(
358 'coinbase transaction of version 2 block should contain height'
359 ) unless $self->has_height;
360 }
361  
362 # TODO: to verify:
363 # - block version
364 # - block hex vs difficulty
365 # - each transaction
366 # - block subsidy
367 # - BIP141 commitment structure in coinbase transaction
368 # - probably more
369 #
370 # these verifications only make sense in full chain context though
371 }
372  
373 sub dump
374 0 ▶{
Subroutine dump: not called CC=3 SCAR=24.8
Pod documented
375 0 my ($self) = @_;
376  
377 0 ▶ my $height_str = $self->has_height ? $self->height : 'unknown';
Branch: 1 branch
BranchTrueFalseTotal
$self->has_height ? : 0 0 0
378  
379 0 my @result;
380 0 push @result, 'Block ' . to_format [hex => $self->get_hash];
381 0 push @result, 'height: ' . $height_str;
382 0 push @result, 'version: ' . $self->version;
383 0 push @result, 'previous: ' . to_format [hex => $self->prev_block_hash];
384 0 push @result, 'merkle root: ' . to_format [hex => $self->merkle_root];
385 0 push @result, 'timestamp: ' . $self->timestamp . ' (' . scalar(localtime($self->timestamp)) . ')';
386 0 push @result, 'bits: 0x' . sprintf('%08x', $self->bits);
387 0 push @result, 'nonce: ' . $self->nonce;
388 0 push @result, 'size: ' . $self->size . ' bytes, ' . $self->weight . ' WU';
389 0 push @result, '';
390  
391 0 push @result, @{$self->transactions} . ' transactions:';
392 0 foreach my $tx (@{$self->transactions}) {
393 0 push @result, $tx->dump;
394 0 push @result, '';
395 }
396  
397 0 return join "\n", @result;
398 }
399  
400 8 1;
401  
402 __END__
« Crypto/Script/Tree.pm ↑ Summary Crypto/Script/Runner.pm »