From 6d12cb9a74a3f03521063e648304ee68fd8a15dc Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Fri, 18 May 2018 14:38:32 +1200 Subject: [PATCH] Extract LEOS2IP and I2LEOSP functions --- sapling_jubjub.py | 13 +++++-------- sapling_pedersen.py | 8 +++----- sapling_utils.py | 10 ++++++++++ 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/sapling_jubjub.py b/sapling_jubjub.py index 1e70df2..bc4529c 100644 --- a/sapling_jubjub.py +++ b/sapling_jubjub.py @@ -1,7 +1,5 @@ #!/usr/bin/env python3 -from sapling_utils import i2lebsp - -ENDIANNESS = 'little' +from sapling_utils import i2lebsp, leos2ip, i2leosp q_j = 52435875175126190479447740508185965837690552500527637822603658699938581184513 r_j = 6554484396890773809930967563523245729705921265872317281365359162392183254199 @@ -49,7 +47,8 @@ class FieldElement(object): return i2lebsp(l, self.s) def __bytes__(self): - return self.s.to_bytes(32, byteorder=ENDIANNESS) + # TODO: Check length + return i2leosp(256, self.s) def __eq__(self, a): return self.s == a.s @@ -59,8 +58,7 @@ class FieldElement(object): class Fq(FieldElement): @staticmethod def from_bytes(buf): - s = int.from_bytes(buf, byteorder=ENDIANNESS) - return Fq(s) + return Fq(leos2ip(buf)) def __init__(self, s): FieldElement.__init__(self, Fq, s, q_j) @@ -111,8 +109,7 @@ class Fq(FieldElement): class Fr(FieldElement): @staticmethod def from_bytes(buf): - s = int.from_bytes(buf, byteorder=ENDIANNESS) - return Fr(s) + return Fr(leos2ip(buf)) def __init__(self, s): FieldElement.__init__(self, Fr, s, r_j) diff --git a/sapling_pedersen.py b/sapling_pedersen.py index e11ea5c..6ca1721 100644 --- a/sapling_pedersen.py +++ b/sapling_pedersen.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 from sapling_generators import find_group_hash, NOTE_POSITION_BASE, WINDOWED_PEDERSEN_RANDOMNESS_BASE -from sapling_jubjub import ENDIANNESS, Fr +from sapling_jubjub import Fr +from sapling_utils import cldiv, i2leosp # @@ -8,7 +9,7 @@ from sapling_jubjub import ENDIANNESS, Fr # def I_D_i(D, i): - return find_group_hash(D, (i - 1).to_bytes(4, byteorder=ENDIANNESS)) + return find_group_hash(D, i2leosp(32, i - 1)) def encode_chunk(mj): (s0, s1, s2) = mj @@ -20,9 +21,6 @@ def encode_segment(Mi): assert(len(Michunks) == ki) return Fr(sum([encode_chunk(Michunks[j-1]) * 2**(4*(j-1)) for j in range(1, ki + 1)])) -def cldiv(n, divisor): - return (n + (divisor - 1)) // divisor - c = 63 def pedersen_hash_to_point(D, M): diff --git a/sapling_utils.py b/sapling_utils.py index 0a32dff..dea7215 100644 --- a/sapling_utils.py +++ b/sapling_utils.py @@ -1,4 +1,14 @@ #!/usr/bin/env python3 +def cldiv(n, divisor): + return (n + (divisor - 1)) // divisor + def i2lebsp(l, x): return [int(c) for c in format(x, '0%sb' % l)[::-1]] + +def leos2ip(S): + return int.from_bytes(S, byteorder='little') + +# This should be equivalent to LEBS2OSP(I2LEBSP(l, x)) +def i2leosp(l, x): + return x.to_bytes(cldiv(l, 8), byteorder='little')