Point::cmp()   A
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 12
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 21
rs 9.2222
1
<?php
2
declare(strict_types=1);
3
4
namespace Mdanter\Ecc\Primitives;
5
6
use Mdanter\Ecc\Exception\PointException;
7
use Mdanter\Ecc\Exception\PointNotOnCurveException;
8
use Mdanter\Ecc\Math\GmpMathInterface;
9
use Mdanter\Ecc\Math\ModularArithmetic;
10
11
/**
12
 * *********************************************************************
13
 * Copyright (C) 2012 Matyas Danter
14
 *
15
 * Permission is hereby granted, free of charge, to any person obtaining
16
 * a copy of this software and associated documentation files (the "Software"),
17
 * to deal in the Software without restriction, including without limitation
18
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
19
 * and/or sell copies of the Software, and to permit persons to whom the
20
 * Software is furnished to do so, subject to the following conditions:
21
 *
22
 * The above copyright notice and this permission notice shall be included
23
 * in all copies or substantial portions of the Software.
24
 *
25
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
29
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
30
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
31
 * OTHER DEALINGS IN THE SOFTWARE.
32
 * ***********************************************************************
33
 */
34
35
/**
36
 * This class is where the elliptic curve arithmetic takes place.
37
 * The important methods are:
38
 * - add: adds two points according to ec arithmetic
39
 * - double: doubles a point on the ec field mod p
40
 * - mul: uses double and add to achieve multiplication The rest of the methods are there for supporting the ones above.
41
 */
42
class Point implements PointInterface
43
{
44
    /**
45
     * @var CurveFpInterface
46
     */
47
    private $curve;
48
49
    /**
50
     * @var GmpMathInterface
51
     */
52
    private $adapter;
53
54
    /**
55
     * @var ModularArithmetic
56
     */
57
    private $modAdapter;
58
59
    /**
60
     * @var \GMP
61
     */
62
    private $x;
63
64
    /**
65
     * @var \GMP
66
     */
67
    private $y;
68
69
    /**
70
     * @var \GMP
71
     */
72
    private $order;
73
74
    /**
75
     * @var bool
76
     */
77
    private $infinity = false;
78
79
    /**
80
     * Initialize a new instance
81
     *
82
     * @param GmpMathInterface     $adapter
83
     * @param CurveFpInterface     $curve
84
     * @param \GMP                 $x
85
     * @param \GMP                 $y
86
     * @param \GMP                 $order
87
     * @param bool                 $infinity
88
     *
89
     * @throws \RuntimeException    when either the curve does not contain the given coordinates or
90
     *                                      when order is not null and P(x, y) * order is not equal to infinity.
91
     */
92
    public function __construct(GmpMathInterface $adapter, CurveFpInterface $curve, \GMP $x, \GMP $y, \GMP $order = null, bool $infinity = false)
93
    {
94
        $this->adapter    = $adapter;
95
        $this->modAdapter = $curve->getModAdapter();
96
        $this->curve      = $curve;
97
        $this->x          = $x;
98
        $this->y          = $y;
99
        $this->order      = $order !== null ? $order : gmp_init(0, 10);
0 ignored issues
show
Documentation Bug introduced by
It seems like $order !== null ? $order : gmp_init(0, 10) can also be of type resource. However, the property $order is declared as type GMP. 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...
100
        $this->infinity   = (bool) $infinity;
101
        if (! $infinity && ! $curve->contains($x, $y)) {
102
            throw new PointNotOnCurveException($x, $y, $curve);
103
        }
104
105
        if (!is_null($order)) {
106
            $mul = $this->mul($order);
107
            if (!$mul->isInfinity()) {
108
                throw new PointException("SELF * ORDER MUST EQUAL INFINITY. (" . (string)$mul . " found instead)");
109
            }
110
        }
111
    }
112
113
    /**
114
     * @return GmpMathInterface
115
     */
116
    public function getAdapter(): GmpMathInterface
117
    {
118
        return $this->adapter;
119
    }
120
121
    /**
122
     * {@inheritDoc}
123
     * @see \Mdanter\Ecc\Primitives\PointInterface::isInfinity()
124
     */
125
    public function isInfinity(): bool
126
    {
127
        return (bool) $this->infinity;
128
    }
129
130
    /**
131
     * {@inheritDoc}
132
     * @see \Mdanter\Ecc\Primitives\PointInterface::getCurve()
133
     */
134
    public function getCurve(): CurveFpInterface
135
    {
136
        return $this->curve;
137
    }
138
139
    /**
140
     * {@inheritDoc}
141
     * @see \Mdanter\Ecc\Primitives\PointInterface::getOrder()
142
     */
143
    public function getOrder(): \GMP
144
    {
145
        return $this->order;
146
    }
147
148
    /**
149
     * {@inheritDoc}
150
     * @see \Mdanter\Ecc\Primitives\PointInterface::getX()
151
     */
152
    public function getX(): \GMP
153
    {
154
        return $this->x;
155
    }
156
157
    /**
158
     * {@inheritDoc}
159
     * @see \Mdanter\Ecc\Primitives\PointInterface::getY()
160
     */
161
    public function getY(): \GMP
162
    {
163
        return $this->y;
164
    }
165
166
    /**
167
     * {@inheritDoc}
168
     * @see \Mdanter\Ecc\Primitives\PointInterface::add()
169
     * @return self
170
     */
171
    public function add(PointInterface $addend): PointInterface
172
    {
173
        if (! $this->curve->equals($addend->getCurve())) {
174
            throw new \RuntimeException("The Elliptic Curves do not match.");
175
        }
176
177
        if ($addend->isInfinity()) {
178
            return clone $this;
179
        }
180
181
        if ($this->isInfinity()) {
182
            return clone $addend;
183
        }
184
185
        $math = $this->adapter;
186
        $modMath = $this->modAdapter;
187
188
        if ($math->equals($addend->getX(), $this->x)) {
189
            if ($math->equals($addend->getY(), $this->y)) {
190
                return $this->getDouble();
191
            } else {
192
                return $this->curve->getInfinity();
193
            }
194
        }
195
196
        $slope = $modMath->div(
197
            $math->sub($addend->getY(), $this->y),
198
            $math->sub($addend->getX(), $this->x)
199
        );
200
201
        $xR = $modMath->sub(
202
            $math->sub($math->pow($slope, 2), $this->x),
203
            $addend->getX()
204
        );
205
206
        $yR = $modMath->sub(
207
            $math->mul($slope, $math->sub($this->x, $xR)),
208
            $this->y
209
        );
210
211
        return $this->curve->getPoint($xR, $yR, $this->order);
212
    }
213
214
    /**
215
     * {@inheritDoc}
216
     * @see \Mdanter\Ecc\Primitives\PointInterface::cmp()
217
     */
218
    public function cmp(PointInterface $other): int
219
    {
220
        if ($other->isInfinity() && $this->isInfinity()) {
221
            return 0;
222
        }
223
224
        if ($other->isInfinity() || $this->isInfinity()) {
225
            return 1;
226
        }
227
228
        $math = $this->adapter;
229
        $equal = ($math->equals($this->x, $other->getX()));
230
        $equal &= ($math->equals($this->y, $other->getY()));
231
        $equal &= $this->isInfinity() == $other->isInfinity();
232
        $equal &= $this->curve->equals($other->getCurve());
233
234
        if ($equal) {
235
            return 0;
236
        }
237
238
        return 1;
239
    }
240
241
    /**
242
     * {@inheritDoc}
243
     * @see \Mdanter\Ecc\Primitives\PointInterface::equals()
244
     */
245
    public function equals(PointInterface $other): bool
246
    {
247
        return $this->cmp($other) == 0;
248
    }
249
250
    /**
251
     * {@inheritDoc}
252
     * @see \Mdanter\Ecc\Primitives\PointInterface::mul()
253
     */
254
    public function mul(\GMP $n): PointInterface
255
    {
256
        if ($this->isInfinity()) {
257
            return $this->curve->getInfinity();
258
        }
259
260
        $zero = gmp_init(0, 10);
261
        if ($this->adapter->cmp($this->order, $zero) > 0) {
0 ignored issues
show
Bug introduced by
It seems like $zero can also be of type resource; however, parameter $other of Mdanter\Ecc\Math\GmpMathInterface::cmp() does only seem to accept GMP, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

261
        if ($this->adapter->cmp($this->order, /** @scrutinizer ignore-type */ $zero) > 0) {
Loading history...
262
            $n = $this->adapter->mod($n, $this->order);
263
        }
264
265
        if ($this->adapter->equals($n, $zero)) {
0 ignored issues
show
Bug introduced by
It seems like $zero can also be of type resource; however, parameter $other of Mdanter\Ecc\Math\GmpMathInterface::equals() does only seem to accept GMP, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

265
        if ($this->adapter->equals($n, /** @scrutinizer ignore-type */ $zero)) {
Loading history...
266
            return $this->curve->getInfinity();
267
        }
268
269
        /** @var Point[] $r */
270
        $r = [
271
            $this->curve->getInfinity(),
272
            clone $this
273
        ];
274
275
        $k = $this->curve->getSize();
276
        $n = str_pad($this->adapter->baseConvert($this->adapter->toString($n), 10, 2), $k, '0', STR_PAD_LEFT);
277
278
        for ($i = 0; $i < $k; $i++) {
279
            $j = $n[$i];
280
281
            $this->cswap($r[0], $r[1], $j ^ 1, $k);
282
283
            $r[0] = $r[0]->add($r[1]);
284
            $r[1] = $r[1]->getDouble();
285
286
            $this->cswap($r[0], $r[1], $j ^ 1, $k);
287
        }
288
289
        $r[0]->validate();
290
291
        return $r[0];
292
    }
293
294
    /**
295
     * @param Point $a
296
     * @param Point $b
297
     * @param int $cond
298
     * @param int $curveSize
299
     */
300
    private function cswap(self $a, self $b, int $cond, int $curveSize)
301
    {
302
        $this->cswapValue($a->x, $b->x, $cond, $curveSize);
303
        $this->cswapValue($a->y, $b->y, $cond, $curveSize);
304
        $this->cswapValue($a->order, $b->order, $cond, $curveSize);
305
        $this->cswapValue($a->infinity, $b->infinity, $cond, 8);
306
    }
307
308
    /**
309
     * @param bool|\GMP $a
310
     * @param bool|\GMP $b
311
     * @param int $cond
312
     * @param int $maskBitSize
313
     */
314
    public function cswapValue(& $a, & $b, int $cond, int $maskBitSize)
315
    {
316
        $isGMP = is_object($a) && $a instanceof \GMP;
317
318
        $sa = $isGMP ? $a : gmp_init(intval($a), 10);
319
        $sb = $isGMP ? $b : gmp_init(intval($b), 10);
320
321
        $mask = str_pad('', $maskBitSize, (string) (1 - intval($cond)), STR_PAD_LEFT);
322
        $mask = gmp_init($mask, 2);
323
324
        $taA = $this->adapter->bitwiseAnd($sa, $mask);
0 ignored issues
show
Bug introduced by
It seems like $sa can also be of type resource; however, parameter $first of Mdanter\Ecc\Math\GmpMathInterface::bitwiseAnd() does only seem to accept GMP, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

324
        $taA = $this->adapter->bitwiseAnd(/** @scrutinizer ignore-type */ $sa, $mask);
Loading history...
Bug introduced by
It seems like $mask can also be of type resource; however, parameter $other of Mdanter\Ecc\Math\GmpMathInterface::bitwiseAnd() does only seem to accept GMP, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

324
        $taA = $this->adapter->bitwiseAnd($sa, /** @scrutinizer ignore-type */ $mask);
Loading history...
325
        $taB = $this->adapter->bitwiseAnd($sb, $mask);
0 ignored issues
show
Bug introduced by
It seems like $sb can also be of type boolean and resource; however, parameter $first of Mdanter\Ecc\Math\GmpMathInterface::bitwiseAnd() does only seem to accept GMP, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

325
        $taB = $this->adapter->bitwiseAnd(/** @scrutinizer ignore-type */ $sb, $mask);
Loading history...
326
327
        $sa = $this->adapter->bitwiseXor($this->adapter->bitwiseXor($sa, $sb), $taB);
0 ignored issues
show
Bug introduced by
It seems like $sa can also be of type resource; however, parameter $first of Mdanter\Ecc\Math\GmpMathInterface::bitwiseXor() does only seem to accept GMP, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

327
        $sa = $this->adapter->bitwiseXor($this->adapter->bitwiseXor(/** @scrutinizer ignore-type */ $sa, $sb), $taB);
Loading history...
Bug introduced by
It seems like $sb can also be of type boolean and resource; however, parameter $other of Mdanter\Ecc\Math\GmpMathInterface::bitwiseXor() does only seem to accept GMP, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

327
        $sa = $this->adapter->bitwiseXor($this->adapter->bitwiseXor($sa, /** @scrutinizer ignore-type */ $sb), $taB);
Loading history...
328
        $sb = $this->adapter->bitwiseXor($this->adapter->bitwiseXor($sa, $sb), $taA);
329
        $sa = $this->adapter->bitwiseXor($this->adapter->bitwiseXor($sa, $sb), $taB);
330
331
        $a = $isGMP ? $sa : (bool) gmp_strval($sa, 10);
332
        $b = $isGMP ? $sb : (bool) gmp_strval($sb, 10);
333
    }
334
335
    /**
336
     *
337
     */
338
    private function validate()
339
    {
340
        if (! $this->infinity && ! $this->curve->contains($this->x, $this->y)) {
341
            throw new \RuntimeException('Invalid point');
342
        }
343
    }
344
345
    /**
346
     * {@inheritDoc}
347
     * @see \Mdanter\Ecc\Primitives\PointInterface::getDouble()
348
     * @return self
349
     */
350
    public function getDouble(): PointInterface
351
    {
352
        if ($this->isInfinity()) {
353
            return $this->curve->getInfinity();
354
        }
355
356
        $math = $this->adapter;
357
        $modMath = $this->modAdapter;
358
359
        $a = $this->curve->getA();
360
        $threeX2 = $math->mul(gmp_init(3, 10), $math->pow($this->x, 2));
0 ignored issues
show
Bug introduced by
It seems like gmp_init(3, 10) can also be of type resource; however, parameter $multiplier of Mdanter\Ecc\Math\GmpMathInterface::mul() does only seem to accept GMP, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

360
        $threeX2 = $math->mul(/** @scrutinizer ignore-type */ gmp_init(3, 10), $math->pow($this->x, 2));
Loading history...
361
362
        $tangent = $modMath->div(
363
            $math->add($threeX2, $a),
364
            $math->mul(gmp_init(2, 10), $this->y)
365
        );
366
367
        $x3 = $modMath->sub(
368
            $math->pow($tangent, 2),
369
            $math->mul(gmp_init(2, 10), $this->x)
370
        );
371
372
        $y3 = $modMath->sub(
373
            $math->mul($tangent, $math->sub($this->x, $x3)),
374
            $this->y
375
        );
376
377
        return $this->curve->getPoint($x3, $y3, $this->order);
378
    }
379
380
    /**
381
     * {@inheritDoc}
382
     * @see \Mdanter\Ecc\Primitives\PointInterface::__toString()
383
     */
384
    public function __toString(): string
385
    {
386
        if ($this->infinity) {
387
            return '[ (infinity) on ' . (string) $this->curve . ' ]';
388
        }
389
390
        return "[ (" . $this->adapter->toString($this->x) . "," . $this->adapter->toString($this->y) . ') on ' . (string) $this->curve . ' ]';
391
    }
392
393
    /**
394
     * @return array
395
     */
396
    public function __debugInfo(): array
397
    {
398
        $info = [
399
            'x' => $this->adapter->toString($this->x),
400
            'y' => $this->adapter->toString($this->y),
401
            'z' => $this->adapter->toString($this->order),
402
            'curve' => $this->curve
403
        ];
404
405
        if ($this->infinity) {
406
            $info['x'] = 'inf (' . $info['x'] . ')';
407
            $info['y'] = 'inf (' . $info['y'] . ')';
408
            $info['z'] = 'inf (' . $info['z'] . ')';
409
        }
410
411
        return $info;
412
    }
413
}
414