spec/crypto/secp256k1/field.bend
bend-collections-laws-crypto@1.0.0.0 · 91 lines · 16 definitions
1import Base
2import bend-collections-laws-crypto@1.0.0.0/spec/lib/common.bend as C
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19def digits(+one: Nat, ds: List<&2, Nat>) -> Nat:
20 match ds:
21 case Nil{}:
22 0n
23 case d <> dt:
24 Nat.add(Nat.mul(one, d), C.shift(16n, digits(one, dt)))
25
26
27def w256(+one: Nat) -> Nat:
28 C.shift(256n, one)
29
30
31def cp(+one: Nat) -> Nat:
32 digits(one, [977n, 0n, 1n])
33
34def prime(+one: Nat) -> Nat:
35 Nat.sub(w256(one), cp(one))
36
37
38def cn(+one: Nat) -> Nat:
39 digits(one, [48831n, 12233n, 41331n, 16429n, 24516n, 20663n, 8985n, 17745n, 1n])
40
41def order(+one: Nat) -> Nat:
42 Nat.sub(w256(one), cn(one))
43
44
45
46def madd(+m: Nat, a: Nat, b: Nat) -> Nat:
47 Nat.mod(Nat.add(a, b), m)
48
49
50def msub(+m: Nat, a: Nat, b: Nat) -> Nat:
51 Nat.mod(Nat.sub(Nat.add(a, m), Nat.mod(b, m)), m)
52
53def mneg(+m: Nat, a: Nat) -> Nat:
54 msub(m, 0n, a)
55
56def mmul(+m: Nat, a: Nat, b: Nat) -> Nat:
57 Nat.mod(Nat.mul(a, b), m)
58
59def mpow(+m: Nat, a: Nat, e: Nat) -> Nat:
60 Nat.mod(Nat.pow(a, e), m)
61
62
63def minv(+m: Nat, a: Nat) -> Nat:
64 mpow(m, a, Nat.sub(m, 2n))
65
66
67
68def fsqrt(+m: Nat, a: Nat) -> Nat:
69 mpow(m, a, Nat.div(Nat.add(m, 1n), 4n))
70
71
72
73
74def value(+one: Nat, xs: List<&2, Nat>) -> Nat:
75 digits(one, xs)
76
77
78def limbs16(+one: Nat, n: Nat, xs: List<&2, Nat>) -> Bool:
79 match n xs:
80 case 0n Nil{}:
81 True{}
82 case 0n x <> t:
83 False{}
84 case 1n+k Nil{}:
85 False{}
86 case 1n+k x <> t:
87 Bool.and(Nat.is_lt(x, C.shift(16n, one)), limbs16(one, k, t))
88
89
90def reduced(+one: Nat, +m: Nat, +xs: List<&2, Nat>) -> Bool:
91 Bool.and(limbs16(one, 16n, xs), Nat.is_lt(value(one, xs), m))