Completed
Pull Request — master (#334)
by thomas
147:16 queued 143:27
created

Number::getBuffer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 2592
    public function __construct($number, Math $math)
33
    {
34 2592
        $this->number = $number;
35 2592
        $this->math = $math;
36 2592
    }
37
38
    /**
39
     * @param int $number
40
     * @param Math|null $math
41
     * @return self
42
     */
43 2451
    public static function int($number, Math $math = null)
44
    {
45 2451
        return new self(
46 817
            $number,
47 2451
            $math ?: Bitcoin::getMath()
48 817
        );
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 1251
    public static function buffer(BufferInterface $vch, $fRequireMinimal, $maxNumSize = self::MAX_NUM_SIZE, Math $math = null)
72
    {
73 1251
        $size = $vch->getSize();
74 1251
        if ($size > $maxNumSize) {
75 36
            throw new \RuntimeException('Script number overflow');
76
        }
77
78 1224
        if ($fRequireMinimal && $size > 0) {
79 165
            $binary = $vch->getBinary();
80 165
            if ((ord($binary[$size - 1]) & 0x7f) == 0) {
81 165
                if ($size <= 1 || (ord($binary[$size - 2]) & 0x80) == 0) {
82 165
                    throw new \RuntimeException('Non-minimally encoded script number');
83
                }
84
            }
85 1
        }
86
87 1113
        $math = $math ?: Bitcoin::getMath();
88 1113
        $number = new self(0, $math);
89 1113
        $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...
90 1113
        return $number;
91
    }
92
93
    /**
94
     * @param BufferInterface $buffer
95
     * @return int
96
     */
97 1113
    private function parseBuffer(BufferInterface $buffer)
98
    {
99 1113
        $size = $buffer->getSize();
100 1113
        if ($size === 0) {
101 597
            return '0';
102
        }
103
104 921
        $chars = $buffer->getBinary();
105
106 921
        $result = gmp_init(0);
107 921
        for ($i = 0; $i < $size; $i++) {
108 921
            $mul = $i * 8;
109 921
            $byte = $this->math->leftShift(gmp_init(ord($chars[$i]), 10), $mul);
110 921
            $result = $this->math->bitwiseOr($result, $byte);
111 307
        }
112
113 921
        if ($chars[count($chars)-1] & 0x80) {
114
            $mask = gmp_com($this->math->leftShift(gmp_init(0x80), (8 * ($size - 1))));
115
            $result = $this->math->sub(gmp_init(0), $this->math->bitwiseAnd($result, $mask));
116
        }
117
118 921
        return gmp_strval($result, 10);
119
    }
120
121
    /**
122
     * @return BufferInterface
123
     */
124 2451
    private function serialize()
125
    {
126 2451
        if ($this->number == 0) {
127 438
            return new Buffer('', 0);
128
        }
129
130 2280
        $zero = gmp_init(0);
131
        // Using array of integers instead of bytes
132 2280
        $result = [];
133 2280
        $negative = $this->math->cmp(gmp_init($this->number), $zero) < 0;
134 2280
        $abs = $negative ? $this->math->sub($zero, gmp_init($this->number, 10)) : gmp_init($this->number, 10);
135 2280
        $mask = gmp_init(0xff);
136 2280
        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 134 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...
137 2280
            $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 134 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...
138 2280
            $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...
139 760
        }
140
141 2280
        if ($result[count($result) - 1] & 0x80) {
142 39
            $result[] = $negative ? 0x80 : 0;
143 2258
        } else if ($negative) {
144 24
            $result[count($result) - 1] |= 0x80;
145 8
        }
146
147 2280
        $s = '';
148 2280
        foreach ($result as $i) {
149 2280
            $s .= chr($i);
150 760
        }
151
152 2280
        return new Buffer($s, null, $this->math);
153
154
    }
155
156
    /**
157
     * @return BufferInterface
158
     */
159 2451
    public function getBuffer()
160
    {
161 2451
        return $this->serialize();
162
    }
163
164
    /**
165
     * @return int
166
     */
167 351
    public function getInt()
168
    {
169 351
        if ($this->math->cmp(gmp_init($this->number, 10), gmp_init(self::MAX)) > 0) {
170 3
            return self::MAX;
171 348
        } else if ($this->math->cmp(gmp_init($this->number, 10), gmp_init(self::MIN)) < 0) {
172
            return self::MIN;
173
        }
174
175 348
        return $this->number;
176
    }
177
178
    /**
179
     * @return \GMP
180
     */
181 786
    public function getGmp()
182
    {
183 786
        return gmp_init($this->number, 10);
184
    }
185
}
186