Completed
Push — master ( c42b07...45cd31 )
by thomas
21:37
created

MerkleRoot::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace BitWasp\Bitcoin\Block;
4
5
use BitWasp\Bitcoin\Exceptions\MerkleTreeEmpty;
6
use BitWasp\Bitcoin\Math\Math;
7
use BitWasp\Bitcoin\Transaction\TransactionInterface;
8
use BitWasp\Buffertools\Buffer;
9
use BitWasp\Buffertools\BufferInterface;
10
use Pleo\Merkle\FixedSizeTree;
11
12
class MerkleRoot
13
{
14
    /**
15
     * @var TransactionInterface[]
16
     */
17
    private $transactions;
18
19
    /**
20
     * @var Math
21
     */
22
    private $math;
23
24
    /**
25
     * @var BufferInterface
26
     */
27
    private $lastHash;
28
29
    /**
30
     * Instantiate the class when given a block
31
     *
32
     * @param Math $math
33
     * @param TransactionInterface[] $txCollection
34
     */
35 16
    public function __construct(Math $math, array $txCollection)
36
    {
37 16
        $this->math = $math;
38 16
        $this->transactions = $txCollection;
39 16
    }
40
41
    /**
42
     * @param callable|null $hashFunction
43
     * @return BufferInterface
44
     * @throws MerkleTreeEmpty
45
     */
46 16
    public function calculateHash(callable $hashFunction = null)
47
    {
48 16
        if ($this->lastHash instanceof BufferInterface) {
49
            return $this->lastHash;
50
        }
51
52 16
        $hashFxn = $hashFunction ?: function ($value) {
53 14
            return hash('sha256', hash('sha256', $value, true), true);
54 16
        };
55
56
        $txCount = count($this->transactions);
57
        if ($txCount === 0) {
58
            // TODO: Probably necessary. Should always have a coinbase at least.
59
            throw new MerkleTreeEmpty('Cannot compute Merkle root of an empty tree');
60
        }
61
62
        if ($txCount === 1) {
63
            $binary = $hashFxn($this->transactions[0]->getBinary());
64
        } else {
65
            // Create a fixed size Merkle Tree
66
            $tree = new FixedSizeTree($txCount + ($txCount % 2), $hashFxn);
67
68
            // Compute hash of each transaction
69
            $last = '';
70
            foreach ($this->transactions as $i => $transaction) {
71
                $last = $transaction->getBinary();
72
                $tree->set($i, $last);
73
            }
74
75
            // Check if we need to repeat the last hash (odd number of transactions)
76
            if (!($txCount % 2 === 0)) {
77
                $tree->set($txCount, $last);
78
            }
79
80
            $binary = $tree->hash();
81
        }
82
83
        $this->lastHash = (new Buffer($binary))->flip();
0 ignored issues
show
Documentation Bug introduced by
It seems like (new \BitWasp\Buffertool...uffer($binary))->flip() can also be of type string. However, the property $lastHash is declared as type object<BitWasp\Buffertools\BufferInterface>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
84
        return $this->lastHash;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->lastHash; of type BitWasp\Buffertools\Buffer|string adds the type string to the return on line 84 which is incompatible with the return type documented by BitWasp\Bitcoin\Block\MerkleRoot::calculateHash of type BitWasp\Buffertools\BufferInterface.
Loading history...
85
    }
86
}
87