Crypto/Block.pm

filter: Statementstmt 85.2% 133 / 156 Branchbran 63.3% 19 / 30 Conditioncond 38.8% 7 / 18 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 96.3% 26 / 27 Podpod 88.8% 8 / 9 totaltotal 77.2% 193 / 250 CC 27 SCAR 16.9
CC
27
Cov
78%
dump
12.0
from_serialized
11.3
_build_height
9.8
CRAP 5.4
« Crypto/Transaction/AutoSigner.pm ↑ Summary Crypto/Script/Runner.pm »
1 package Bitcoin::Crypto::Block;
2 8 $Bitcoin::Crypto::Block::VERSION = '4.005';
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 68 ▶ 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 4 ▶{
Subroutine _build_height: called CC=7 SCAR=22.8
89 4 my ($self) = @_;
90  
91 4 ▶ return undef unless $self->has_transactions;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_transactions 0 4 4
92  
93 4 my $tx = $self->transactions->[0];
94 4 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
unless $tx->is_coinbase 0 4 4
95 'first transaction is not coinbase'
96 ) unless $tx->is_coinbase;
97  
98 # TODO: check if height is minimally encoded?
99 4 my $full_script = $tx->inputs->[0]->signature_script->to_serialized;
100 4 my $size = unpack 'C', substr $full_script, 0, 1;
101 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
102 'invalid height in coinbase transaction'
103 ) unless $size && ($size == 3 || $size == 5) && length $full_script > $size;
104  
105 4 try {
106 4 my $result = Bitcoin::Crypto::Script::Runner
107 ->to_int(substr $full_script, 1, $size);
108  
109 # numify if bigint
110 4 return "$result";
111 }
112 catch ($e) {
113 0 return undef;
114 }
115 }
116  
117 sub add_transaction
118 1 ▶{
Subroutine add_transaction: called CC=4 SCAR=14.7
Pod documented
119 1 my ($self, @data) = @_;
120  
121 1 my $tx;
122 1 ▶ if (@data == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@data == 1) { } 1 0 1
123 1 $tx = $data[0];
124  
125 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
126 'expected a transaction object'
127 ) unless blessed $tx && $tx->isa('Bitcoin::Crypto::Transaction');
128 }
129 else {
130 0 $tx = btc_transaction->new(@data);
131 }
132  
133 1 $tx->set_block($self);
134 1 push @{$self->transactions}, $tx;
135  
136 # Clear cached merkle root if set
137 1 $self->clear_merkle_root;
138  
139 1 return $self;
140 }
141  
142 8 signature_for to_serialized => (
143 method => !!1,
144 named => [
145 witness => Bool,
146 {default => 1},
147 ],
148 bless => !!0,
149 );
150  
151 sub to_serialized
152 16 ▶{
Subroutine to_serialized: called CC=2 SCAR=6.9
153 16 my ($self, $args) = @_;
154  
155 # Bitcoin block serialization format:
156 # - Block header (80 bytes):
157 # - version (4 bytes)
158 # - prev_block_hash (32 bytes)
159 # - merkle_root (32 bytes)
160 # - timestamp (4 bytes)
161 # - bits (4 bytes)
162 # - nonce (4 bytes)
163 # - Transaction count (VarInt)
164 # - Transactions (variable length)
165  
166 16 my $serialized = $self->get_header;
167  
168 # Transaction count
169 16 $serialized .= pack_compactsize(scalar @{$self->transactions});
170  
171 # Transactions
172 16 foreach my $tx (@{$self->transactions}) {
173 148 $serialized .= $tx->to_serialized(witness => $args->{witness});
174 }
175  
176 16 return $serialized;
177 }
178  
179 8 signature_for from_serialized => (
180 method => !!1,
181 head => [ByteStr],
182 named => [
183 pos => Maybe [ScalarRef [PositiveOrZeroInt]],
184 {default => undef},
185 ],
186 bless => !!0,
187 );
188  
189 sub from_serialized
190 8 ▶{
Subroutine from_serialized: called CC=11 SCAR=24.3
191 8 my ($class, $serialized, $args) = @_;
192 8 my $partial = !!$args->{pos};
193 8 ▶ my $pos = $partial ? ${$args->{pos}} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$partial ? : 3 5 8
194  
195 # optimization - no need to keep checking bytestrings on every level. It
196 # has already been checked.
197 8 local $Bitcoin::Crypto::Types::CHECK_BYTESTRINGS = !!0;
198  
199 8 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
if length $serialized < 80 1 7 8
200 'serialized block data too short for header'
201 ) if length($serialized) < 80;
202  
203 # Parse block header (80 bytes)
204 7 my ($version, $prev_block_hash, $merkle_root, $timestamp, $bits, $nonce)
205 = unpack 'Va32a32VVV', $serialized;
206 7 $pos += 80;
207  
208 7 $prev_block_hash = reverse $prev_block_hash;
209 7 $merkle_root = reverse $merkle_root;
210  
211 # Parse transaction count
212 7 my $tx_count = unpack_compactsize $serialized, \$pos;
213  
214 7 my @transactions;
215  
216 # Parse transactions
217 7 for my $tx_index (1 .. $tx_count) {
218 46 push @transactions, btc_transaction->from_serialized(
219 $serialized, pos => \$pos
220 );
221 }
222  
223 Bitcoin::Crypto::Exception::Transaction->raise(
224 7 ▶ 'serialized block data is corrupted'
Branch: 1 branch
BranchTrueFalseTotal
if not $partial and $pos != length $serialized 0 7 7
Condition66%2/3
not $partial and $pos != length $serialized
!ll&&!rl&&r
340
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
225 ) if !$partial && $pos != length $serialized;
226  
227 7 ▶ ${$args->{pos}} = $pos
Branch: 1 branch
BranchTrueFalseTotal
if $partial 3 4 7
228 if $partial;
229  
230 7 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
unless @transactions > 0 and $transactions[0]->is_coinbase 0 7 7
Condition33%1/3
@transactions > 0 and $transactions[0]->is_coinbase
!ll&&!rl&&r
007
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
231 'block requires a coinbase transaction'
232 ) unless @transactions > 0 && $transactions[0]->is_coinbase;
233  
234 7 my $block = $class->new(
235 version => $version,
236 prev_block_hash => $prev_block_hash,
237 timestamp => $timestamp,
238 bits => $bits,
239 nonce => $nonce,
240 );
241  
242 7 @{$block->transactions} = @transactions;
243  
244 7 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
if $block->merkle_root ne $merkle_root 0 7 7
245 'serialized block merkle root is incorrect'
246 ) if $block->merkle_root ne $merkle_root;
247  
248 7 foreach my $tx (@transactions) {
249 46 $tx->set_block($block);
250 }
251  
252 7 return $block;
253 }
254  
255 sub get_hash
256 8 ▶{
Subroutine get_hash: called CC=1 SCAR=0.0
Pod documented
257 8 my ($self) = @_;
258 8 return scalar reverse hash256($self->get_header);
259 }
260  
261 sub get_header
262 24 ▶{
Subroutine get_header: called CC=1 SCAR=0.0
Pod documented
263 24 my ($self) = @_;
264  
265 # Return just the 80-byte block header
266 24 return pack 'Va32a32VVV',
267 $self->version,
268 scalar(reverse $self->prev_block_hash),
269 scalar(reverse $self->merkle_root),
270 $self->timestamp,
271 $self->bits,
272 $self->nonce,
273 ;
274 }
275  
276 sub _trigger_previous
277 20 ▶{
Subroutine _trigger_previous: called CC=2 SCAR=8.1
278 20 my ($self) = @_;
279  
280 20 ▶ return unless $self->previous->has_transactions;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->previous->has_transactions 20 0 20
281  
282 0 $self->set_prev_block_hash($self->previous->get_hash);
283 }
284  
285 sub _build_merkle_root
286 9 ▶{
Subroutine _build_merkle_root: called CC=2 SCAR=6.9
287 9 my ($self) = @_;
288  
289 9 my @txs = map { $_->to_serialized(witness => 0) } @{$self->transactions};
290  
291 9 ▶ Bitcoin::Crypto::Exception::Block->raise(
Branch: 1 branch
BranchTrueFalseTotal
unless @txs > 0 1 8 9
292 'cannot calculate merkle root for empty block'
293 ) unless @txs > 0;
294  
295 8 return scalar reverse Bitcoin::Crypto::Util::Internal::merkle_root(\@txs);
296 }
297  
298 sub median_time_past
299 13 ▶{
Subroutine median_time_past: called CC=3 SCAR=11.0
Pod documented
300 13 my ($self) = @_;
301  
302 13 my @stamps;
303  
304 13 my $current = $self;
305 13 for my $count (1 .. 11) {
306 28 push @stamps, $current->timestamp;
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 28 ▶ last unless $current->has_previous;
Branch: 1 branch
BranchTrueFalseTotal
unless $current->has_previous 12 16 28
313 16 $current = $current->previous;
314 }
315  
316 13 @stamps = sort { $a <=> $b } @stamps;
317 13 return $stamps[int(@stamps / 2)];
318 }
319  
320 sub size
321 4 ▶{
Subroutine size: called CC=1 SCAR=0.0
Pod documented
322 4 my ($self) = @_;
323 4 return length $self->to_serialized;
324 }
325  
326 sub weight
327 4 ▶{
Subroutine weight: called CC=1 SCAR=0.0
Pod documented
328 4 my ($self) = @_;
329  
330 4 my $base_size = length $self->to_serialized(witness => 0);
331 4 my $total_size = length $self->to_serialized(witness => 1);
332  
333 # non-witness data is 4 times heavier than witness data
334 4 return $base_size * 3 + $total_size;
335 }
336  
337 8 signature_for verify => (
338 method => !!1,
339 named => [
340 ],
341 bless => !!0,
342 );
343  
344 # TODO: placeholder for actual block verification method. Not very usable and
345 # not documented yet.
346 sub verify
347 {
348 my ($self, $args) = @_;
349  
350 # TODO: version 2 blocks with no coinbase height are only invalid if version 2
351 # blocks are super-majority. There should be a consensus class to track that
352 if ($self->version >= 2) {
353 $self->clear_height;
354 Bitcoin::Crypto::Exception::Block->raise(
355 'coinbase transaction of version 2 block should contain height'
356 ) unless $self->has_height;
357 }
358  
359 # TODO: to verify:
360 # - block version
361 # - block hex vs difficulty
362 # - each transaction
363 # - block subsidy
364 # - BIP141 commitment structure in coinbase transaction
365 # - probably more
366 #
367 # these verifications only make sense in full chain context though
368 }
369  
370 sub dump
371 0 ▶{
Subroutine dump: not called CC=3 SCAR=24.8
Pod documented
372 0 my ($self) = @_;
373  
374 0 ▶ my $height_str = $self->has_height ? $self->height : 'unknown';
Branch: 1 branch
BranchTrueFalseTotal
$self->has_height ? : 0 0 0
375  
376 0 my @result;
377 0 push @result, 'Block ' . to_format [hex => $self->get_hash];
378 0 push @result, 'height: ' . $height_str;
379 0 push @result, 'version: ' . $self->version;
380 0 push @result, 'previous: ' . to_format [hex => $self->prev_block_hash];
381 0 push @result, 'merkle root: ' . to_format [hex => $self->merkle_root];
382 0 push @result, 'timestamp: ' . $self->timestamp . ' (' . scalar(localtime($self->timestamp)) . ')';
383 0 push @result, 'bits: 0x' . sprintf('%08x', $self->bits);
384 0 push @result, 'nonce: ' . $self->nonce;
385 0 push @result, 'size: ' . $self->size . ' bytes, ' . $self->weight . ' WU';
386 0 push @result, '';
387  
388 0 push @result, @{$self->transactions} . ' transactions:';
389 0 foreach my $tx (@{$self->transactions}) {
390 0 push @result, $tx->dump;
391 0 push @result, '';
392 }
393  
394 0 return join "\n", @result;
395 }
396  
397 8 1;
398  
399 __END__
« Crypto/Transaction/AutoSigner.pm ↑ Summary Crypto/Script/Runner.pm »