Completed
Pull Request — master (#331)
by thomas
34:30
created

Number::getInt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 10
ccs 2
cts 2
cp 1
crap 1
rs 9.4285
1
<?php
2
3
namespace BitWasp\Bitcoin\Script\Interpreter;
4
5
use BitWasp\Bitcoin\Bitcoin;
6
use BitWasp\Bitcoin\Math\Math;
7
use BitWasp\Bitcoin\Serializable;
8
use BitWasp\Buffertools\Buffer;
9
use BitWasp\Buffertools\BufferInterface;
10
11
class Number extends Serializable
12
{
13
    const MAX_NUM_SIZE = 4;
14
    const MAX = 2**31-1;
15
    const MIN = -2**31+1;
16
17
    /**
18
     * @var Math
19
     */
20
    private $math;
21
22
    /**
23
     * @var int
24
     */
25
    private $number;
26
27
    /**
28
     * Number constructor.
29
     * @param int $number
30
     * @param Math $math
31
     */
32 2604
    public function __construct($number, Math $math)
33
    {
34 2604
        $this->number = $number;
35 2604
        $this->math = $math;
36 2604
    }
37
38
    /**
39
     * @param int $number
40
     * @param Math|null $math
41
     * @return self
42
     */
43 2463
    public static function int($number, Math $math = null)
44
    {
45 2463
        return new self(
46 1642
            $number,
47 2463
            $math ?: Bitcoin::getMath()
48 1642
        );
49
    }
50
51
    /**
52
     * @param \GMP $number
53
     * @param Math|null $math
54
     * @return self
55
     */
56
    public static function gmp(\GMP $number, Math $math = null)
57
    {
58
        return new self(
59
            gmp_strval($number, 10),
60
            $math ?: Bitcoin::getMath()
61
        );
62
    }
63
64
    /**
65
     * @param BufferInterface $vch
66
     * @param bool $fRequireMinimal
67
     * @param int $maxNumSize
68
     * @param Math|null $math
69
     * @return self
70
     */
71 1263
    public static function buffer(BufferInterface $vch, $fRequireMinimal, $maxNumSize = self::MAX_NUM_SIZE, Math $math = null)
72
    {
73 1263
        $size = $vch->getSize();
74 1263
        if ($size > $maxNumSize) {
75 33
            throw new \RuntimeException('Script number overflow');
76
        }
77
78 1236
        if ($fRequireMinimal && $size > 0) {
79 165
            $binary = $vch->getBinary();
80
81 165
            if ((ord($binary[$size - 1]) & 0x7f) === 0) {
82 165
                if ($size <= 1 || (ord($binary[$size - 2]) & 0x80) === 0) {
83 165
                    throw new \RuntimeException('Non-minimally encoded script number');
84
                }
85
            }
86 2
        }
87
88 1125
        $math = $math ?: Bitcoin::getMath();
89 1125
        $number = new self(0, $math);
90 1125
        $number->number = $number->parseBuffer($vch);
0 ignored issues
show
Documentation Bug introduced by
The property $number was declared of type integer, but $number->parseBuffer($vch) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
91 1125
        return $number;
92
    }
93
94
    /**
95
     * @param BufferInterface $buffer
96
     * @return int
97
     */
98 1125
    private function parseBuffer(BufferInterface $buffer)
99
    {
100 1125
        $size = $buffer->getSize();
101 1125
        if ($size === 0) {
102 612
            return '0';
103
        }
104
105 931
        $chars = array_values(unpack("C*", $buffer->getBinary()));
106
107 931
        $result = gmp_init(0);
108 931
        for ($i = 0; $i < $size; $i++) {
109 931
            $byte = $this->math->leftShift(gmp_init($chars[$i], 10), $i * 8);
110 931
            $result = $this->math->bitwiseOr($result, $byte);
111 620
        }
112
113 931
        if ($chars[count($chars)-1] & 0x80) {
114 156
            $mask = gmp_com($this->math->leftShift(gmp_init(0x80), (8 * ($size - 1))));
115 156
            $result = $this->math->sub(gmp_init(0), $this->math->bitwiseAnd($result, $mask));
116 104
        }
117 931
        return gmp_strval($result, 10);
118
    }
119
120
    /**
121
     * @return BufferInterface
122
     */
123 2463
    private function serialize()
124
    {
125 2463
        if ($this->number == 0) {
126 396
            return new Buffer('', 0);
127
        }
128
129 2333
        $zero = gmp_init(0);
130
        // Using array of integers instead of bytes
131 2333
        $result = [];
132 2333
        $negative = $this->math->cmp(gmp_init($this->number), $zero) < 0;
133 2333
        $abs = $negative ? $this->math->sub($zero, gmp_init($this->number, 10)) : gmp_init($this->number, 10);
134 2333
        $mask = gmp_init(0xff);
135 2333
        while ($this->math->cmp($abs, $zero) > 0) {
0 ignored issues
show
Bug introduced by
It seems like $abs defined by $negative ? $this->math-...init($this->number, 10) on line 133 can also be of type resource; however, Mdanter\Ecc\Math\GmpMath::cmp() does only seem to accept object<GMP>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
136 2333
            $result[] = (int) gmp_strval($this->math->bitwiseAnd($abs, $mask), 10);
0 ignored issues
show
Bug introduced by
It seems like $abs defined by $negative ? $this->math-...init($this->number, 10) on line 133 can also be of type resource; however, Mdanter\Ecc\Math\GmpMath::bitwiseAnd() does only seem to accept object<GMP>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
137 2333
            $abs = $this->math->rightShift($abs, 8);
0 ignored issues
show
Bug introduced by
It seems like $abs can also be of type resource; however, Mdanter\Ecc\Math\GmpMath::rightShift() does only seem to accept object<GMP>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
138 1556
        }
139
140 2333
        if ($result[count($result) - 1] & 0x80) {
141 24
            $result[] = $negative ? 0x80 : 0;
142 2327
        } else if ($negative) {
143 39
            $result[count($result) - 1] |= 0x80;
144 26
        }
145
146 2333
        $s = '';
147 2333
        foreach ($result as $i) {
148 2333
            $s .= chr($i);
149 1556
        }
150
151 2333
        return new Buffer($s, null, $this->math);
152
153
    }
154
155
    /**
156
     * @return BufferInterface
157
     */
158 2463
    public function getBuffer()
159
    {
160 2463
        return $this->serialize();
161
    }
162
163
    /**
164
     * @return int
165
     */
166 453
    public function getInt()
167
    {
168
        /*if ($this->math->cmp(gmp_init($this->number, 10), gmp_init(self::MAX)) > 0) {
169
            return self::MAX;
170
        } else if ($this->math->cmp(gmp_init($this->number, 10), gmp_init(self::MIN)) < 0) {
171
            return self::MIN;
172
        }*/
173
174 453
        return $this->number;
175
    }
176
177
    /**
178
     * @return \GMP
179
     */
180 696
    public function getGmp()
181
    {
182 696
        return gmp_init($this->number, 10);
183
    }
184
}
185