예제 #1
0
def test_gso_int_gram_enabled():
    for int_type in int_types:
        for m, n in dimensions:
            A = make_integer_matrix(m, n, int_type=int_type)
            for float_type in float_types:
                M = GSO.Mat(copy(A), float_type=float_type)
                assert M.int_gram_enabled is False
                assert M.transform_enabled is False

                M = GSO.Mat(copy(A), float_type=float_type, flags=GSO.INT_GRAM)
                assert M.int_gram_enabled is True
                assert M.transform_enabled is False

                if m and n:
                    U = IntegerMatrix(m, m, int_type=int_type)
                    M = GSO.Mat(copy(A), U=U, float_type=float_type)
                    assert M.transform_enabled is True
                    assert M.inverse_transform_enabled is False

                    UinvT = IntegerMatrix(m, m, int_type=int_type)
                    M = GSO.Mat(copy(A),
                                U=U,
                                UinvT=UinvT,
                                float_type=float_type)
                    assert M.transform_enabled is True
                    assert M.inverse_transform_enabled is True
예제 #2
0
def test_bkz_gram_bkz_coherence():
    """
        Test if BKZ is coherent if it is given a matrix A or its associated
        Gram matrix A*A^T

        We should have Gram(BKZ_basis(A)) = BKZ_Gram(Gram(A)).
    """

    for m, n in dimensions:
        if m < 2 or n < 2:
            continue

        for float_type in float_types:
            A = make_integer_matrix(m, n)
            G = tools.compute_gram(A)

            GSO_A = GSO.Mat(A, float_type=float_type)
            GSO_G = GSO.Mat(G, float_type=float_type, gram=True)

            lll_obj_a = LLL.Reduction(GSO_A)
            lll_obj_g = LLL.Reduction(GSO_G)

            param = BKZ.Param(block_size=min(m, 40), strategies=BKZ.DEFAULT_STRATEGY)
            bkz_a = BKZ.Reduction(GSO_A, lll_obj_a, param)
            bkz_g = BKZ.Reduction(GSO_G, lll_obj_g, param)

            bkz_a()
            bkz_g()

            G_updated = tools.compute_gram(A)
            for i in range(m):
                for j in range(i + 1):
                    assert G_updated[i, j] == G[i, j]
예제 #3
0
def main(n=150,
         block_size=60,
         float_type="d",
         logq=40,
         verbose=False,
         seed=0xdeadbeef):
    print "= n: %3d, β: %2d, bits: %3d, float_type: %s, seed: 0x%08x =" % (
        n, block_size, logq, float_type, seed)
    print
    set_random_seed(seed)
    A = IntegerMatrix.random(n, "qary", k=n // 2, bits=logq)
    A = LLL.reduction(A)

    params = BKZ.Param(block_size=block_size,
                       max_loops=4,
                       strategies=BKZ.DEFAULT_STRATEGY,
                       flags=BKZ.MAX_LOOPS | BKZ.VERBOSE)
    bkz = BKZReduction(GSO.Mat(copy.copy(A), float_type=float_type))
    bkz(params)

    print bkz.trace

    bkz2 = BKZ2(GSO.Mat(copy.copy(A), float_type=float_type))
    bkz2(params)

    print bkz2.trace

    if verbose:
        print
        print bkz.trace.report()
예제 #4
0
def test_enum_gram_coherence():
    """
        Test if the enumeration algorithm is consistent with the Gram matrices
        The vectors returned by the enumeration should be the same wether a
        lattice is given by its basis or by its Gram matrix
    """

    dimensions = ((3, 3), (10, 10), (20, 20), (25, 25))

    for m, n in dimensions:
        for int_type in int_types:
            A = make_integer_matrix(m, n, int_type=int_type)
            LLL.reduction(A)
            G = tools.compute_gram(A)
            for float_type in float_types:
                M_A = GSO.Mat(copy(A), float_type=float_type, gram=False)
                M_G = GSO.Mat(copy(G), float_type=float_type, gram=True)

                M_A.update_gso()
                M_G.update_gso()

                enum_obj_a = Enumeration(M_A, nr_solutions=min(m, 5))
                shortest_vectors_a = enum_obj_a.enumerate(
                    0, M_A.d, M_A.get_r(0, 0), 0)

                enum_obj_g = Enumeration(M_G, nr_solutions=min(m, 5))
                shortest_vectors_g = enum_obj_g.enumerate(
                    0, M_G.d, M_G.get_r(0, 0), 0)

                for i in range(len(shortest_vectors_a)):
                    assert shortest_vectors_a[i] == shortest_vectors_g[i]
예제 #5
0
def sample_r(d, lattice_type="qary", run_lll=False):
    """
    Sample squared Gram-Schmidt norms of an LLL reduced lattice in dimension d.

    :param d: lattice dimension
    :param lattice_type: see module level documentation
    :param run_lll: if ``True`` sample a matrix and run LLL

    """
    if run_lll:
        A = sample_matrix(d=d, lattice_type=lattice_type)

        if d < 160:
            M = GSO.Mat(A, float_type="d")
        elif d < 320:
            M = GSO.Mat(A, float_type="dd")
        else:
            M = GSO.Mat(A, float_type="qd")
        M.update_gso()

        return M.r()
    else:
        if lattice_type == "qary":
            q = 2**30
        elif lattice_type == "qary-lv":
            q = 2**(10 * d)
        else:
            raise ValueError("Lattice type '%s' not supported." % lattice_type)
        return [1.0219**(2 * (d - 2 * i - 1)) * q for i in range(d)]
예제 #6
0
def test_lll_gram_lll_coherence():
    """
        Test if LLL is coherent if it is given a matrix A or its associated
        Gram matrix A*A^T

        We should have Gram(LLL_basis(A)) = LLL_Gram(Gram(A)).
    """

    for m, n in dimensions:
        for int_type in int_types:
            A = make_integer_matrix(m, n)
            G = tools.compute_gram(A)

            for float_type in float_types:
                M_A = GSO.Mat(A, float_type=float_type, gram=False)
                lll_A = LLL.Reduction(M_A)

                M_G = GSO.Mat(G, float_type=float_type, gram=True)
                lll_G = LLL.Reduction(M_G)

                # A modified in place
                lll_A()
                # G modified in place
                lll_G()

                G_updated = tools.compute_gram(A)

                if (m, n) == (0, 0):
                    continue
                for i in range(m):
                    for j in range(i + 1):
                        assert G_updated[i, j] == G[i, j]
예제 #7
0
파일: util.py 프로젝트: cr-marcstevens/g6k
def load_matrix_file(filepath,
                     randomize=False,
                     seed=None,
                     float_type="double"):
    """
    Load matrix from file, LLL reduce (and randomize).

    :param filepath: Load matrix from this file
    :param randomize: Randomize the basis
    :param seed: Seed for randomization
    :returns: lattice basis and BKZ object

    """
    A = IntegerMatrix.from_file(filepath)
    A = LLL.reduction(A)
    A = IntegerMatrix.from_matrix(A, int_type="long")

    M = GSO.Mat(A, float_type=float_type)
    bkz = BKZReduction(M)

    if seed is not None:
        FPLLL.set_random_seed(seed)

    if randomize:
        bkz.randomize_block(0, A.nrows, density=A.ncols // 4)
        LLL.reduction(A)
        M = GSO.Mat(A, float_type=float_type)
        bkz = BKZReduction(M)

    bkz.lll_obj()  # to initialize bkz.M etc

    return A, bkz
def main_pruning(filename, bs, cores):

    try:
        with open(filename, "rb") as f:
            mat = pickle.load(f)
            #print "len(mat)", len(mat)
            #if (len(mat) > 1):
            #   mat = mat[0]
        if isinstance(mat, IntegerMatrix):
            Ainput = mat
        else:
            Ainput = IntegerMatrix.from_matrix(mat)
    except:
        Ainput = IntegerMatrix.from_file(filename)

    Ainput_M = GSO.Mat(Ainput, float_type='double')
    Ainput_M.update_gso()
    r = [Ainput_M.get_r(i, i) for i in range(0, Ainput.nrows)]
    L_Ainput_M = LLL.Reduction(Ainput_M)
    L_Ainput_M()
    #print r

    A = IntegerMatrix.from_matrix(L_Ainput_M.M.B, int_type="long")
    M = GSO.Mat(A, float_type="double")
    bkzobj = BKZ2(M)
    bkzobj.M.update_gso()
    block_size = bs
    r = [M.get_r(i, i) for i in range(0, block_size)]
    radius = r[0] * 0.99
    preproc_cost = 5000**(rank + 1)

    pr0 = Pruning.run(radius,
                      NPS[block_size] * preproc_cost, [r],
                      0.1,
                      metric="probability",
                      float_type="double",
                      flags=Pruning.GRADIENT | Pruning.NELDER_MEAD)

    print pr0.coefficients
    """
    pruning = prune(radius, NPS[block_size] * preproc_cost, [r], 0.01,
                        metric="probability", float_type="double",
                        flags=Pruning.GRADIENT|Pruning.NELDER_MEAD)
    cost = sum(pruning.detailed_cost) / NPS[block_size]
    print "# [rank %d] cost %.1f, precost %.1f " % (rank, cost, preproc_cost)
    """

    pr0_linear = pr0.LinearPruningParams(block_size, block_size - 2)
    print pr0_linear.coefficients

    return
예제 #9
0
def test_gso_init():
    for m, n in dimensions:
        A = make_integer_matrix(m, n)
        for float_type in float_types:
            M = GSO.Mat(copy(A), float_type=float_type)
            del M

            U = IntegerMatrix(m, m)
            M = GSO.Mat(copy(A), U=U, float_type=float_type)
            del M

            UinvT = IntegerMatrix(m, m)
            M = GSO.Mat(copy(A), U=U, UinvT=UinvT, float_type=float_type)
            del M
예제 #10
0
def svp_time(seed, params, return_queue=None):
    """Run SVP reduction of AutoBKZ on ``A`` using ``params``.

    :param A: a matrix
    :param params: AutoBKZ parameters
    :param queue: if not ``None``, the result is put on this queue.

    """
    FPLLL.set_random_seed(seed)
    A = IntegerMatrix.random(params.block_size, "qary", bits=30,
                             k=params.block_size//2, int_type="long")

    M = GSO.Mat(A)
    bkz = BKZ2(M)
    tracer = BKZTreeTracer(bkz, start_clocks=True)

    with tracer.context(("tour", 0)):
        bkz.svp_reduction(0, params.block_size, params, tracer)
        bkz.M.update_gso()

    tracer.exit()

    tracer.trace.data["|A_0|"] = A[0].norm()

    if return_queue:
        return_queue.put(tracer.trace)
    else:
        return tracer.trace
예제 #11
0
def test_gso_d():
    for int_type in int_types:
        for m, n in dimensions:
            A = make_integer_matrix(m, n, int_type=int_type)
            for float_type in float_types:
                M = GSO.Mat(copy(A), float_type=float_type)
                assert M.d == m
예제 #12
0
def svp_time(seed, params, return_queue=None):
    """Run SVP reduction of AutoBKZ on ``A`` using ``params``.

    :param A: a matrix
    :param params: AutoBKZ parameters
    :param queue: if not ``None``, the result is put on this queue.

    """
    FPLLL.set_random_seed(seed)
    FPLLL.set_threads(params["threads"])
    q = 33554393
    k = params.block_size // 2
    A = IntegerMatrix.random(params.block_size,
                             "qary",
                             q=q,
                             k=k,
                             int_type="long")

    M = GSO.Mat(A)
    bkz = BKZ2(M)
    tracer = BKZTreeTracer(bkz, start_clocks=True)

    with tracer.context(("tour", 0)):
        bkz.svp_reduction(0, params.block_size, params, tracer)
        bkz.M.update_gso()

    tracer.exit()

    log_delta = (log(A[0].norm()) - log(q) *
                 (k / float(params.block_size))) / float(params.block_size)
    tracer.trace.data["delta"] = exp(log_delta)
    if return_queue:
        return_queue.put(tracer.trace)
    else:
        return tracer.trace
예제 #13
0
def test_lll_init():
    for m, n in dimensions:
        A = make_integer_matrix(m, n)
        for float_type in float_types:
            M = GSO.Mat(copy(A), float_type=float_type)
            lll = LLL.Reduction(M)
            del lll
예제 #14
0
    def estimate(cls, M, squared_target_norm, max_loops=8):
        """

        :param M:
        :param squared_target_norm:
        :param target_prob:
        :returns: cost in CPU cycles

        """
        try:
            (_, d) = M
        except TypeError:
            try:
                M.update_gso()
            except AttributeError:
                M = GSO.Mat(M)
                M.update_gso()
            d = M.d

        _, block_size = USVPPredBKZEnum.estimate(M, squared_target_norm)
        if block_size:
            # TODO: this seems way too much
            cost = max_loops * d * 2**float(
                0.38191949470057696 * block_size -
                32.71092701524247) * 3600 * 2 * 10**9
            return cost, block_size
        else:
            return None, False
예제 #15
0
def osvp_time(seed, params, return_queue=None):
    """Run oSVP reduction on ``A`` using ``params``.

    :param seed: random seed for matrix creation
    :param params: BKZ parameters
    :param return_queue: if not ``None``, the result is put on this queue.

    """
    from cost import sample_matrix

    A = sample_matrix(ceil(params.block_size * (1 + params["c"])), seed=seed)
    M = GSO.Mat(A)
    bkz = OBKZ(M, c=params["c"])
    tracer = BKZTreeTracer(bkz, start_clocks=True)

    with tracer.context(("tour", 0)):
        bkz.svp_reduction(0, params.block_size, params, tracer)
        bkz.M.update_gso()

    tracer.exit()

    tracer.trace.data["|A_0|"] = A[0].norm()
    ppbs = params.strategies[params.block_size].preprocessing_block_sizes
    tracer.trace.data["preprocessing_block_size"] = ppbs[0] if ppbs else 2

    if return_queue:
        return_queue.put(tracer.trace)
    else:
        return tracer.trace
예제 #16
0
def test_multisol():
    A = make_integer_matrix()
    m = GSO.Mat(A)
    lll_obj = LLL.Reduction(m)
    lll_obj()

    solutions = []
    solutions = Enumeration(m, nr_solutions=200).enumerate(0, 27, 48.5, 0)
    assert len(solutions) == 126 / 2
    for _, sol in solutions:
        sol = IntegerMatrix.from_iterable(1, A.nrows,
                                          map(lambda x: int(round(x)), sol))
        sol = tuple((sol * A)[0])
        dist = sum([x**2 for x in sol])
        assert dist == 48

    solutions = []
    solutions = Enumeration(m, nr_solutions=126 / 2).enumerate(0, 27, 100., 0)
    assert len(solutions) == 126 / 2
    for _, sol in solutions:
        sol = IntegerMatrix.from_iterable(1, A.nrows,
                                          map(lambda x: int(round(x)), sol))
        sol = tuple((sol * A)[0])
        dist = sum([x**2 for x in sol])
        assert dist == 48
예제 #17
0
def test_enum_init():
    for int_type in int_types:
        A = make_integer_matrix(20, 20, int_type=int_type)
        for float_type in float_types:
            M = GSO.Mat(copy(A), float_type=float_type)
            enum_obj = Enumeration(M)
            del enum_obj
예제 #18
0
def worker_process(seed, params, queue=None):
    """
    This function is called to collect statistics.

    :param A: basis
    :param params: BKZ parameters
    :param queue: queue used for communication

    """
    FPLLL.set_random_seed(seed)
    A = IntegerMatrix.random(params.block_size,
                             "qary",
                             bits=30,
                             k=params.block_size // 2,
                             int_type="long")

    M = GSO.Mat(A)
    bkz = CallbackBKZ(M)  # suppresses initial LLL call
    tracer = BKZTreeTracer(bkz, start_clocks=True)

    with tracer.context(("tour", 0)):
        bkz.svp_reduction(0, params.block_size, params, tracer)
        M.update_gso()

    tracer.exit()
    try:
        # close connection
        params.strategies[params.block_size].connection.send(None)
    except AttributeError:
        pass
    if queue:
        queue.put(tracer.trace)
    else:
        return tracer.trace
예제 #19
0
    def __init__(self, A):
        """Construct a new instance of the BKZ algorithm.

        :param A: an integer matrix, a GSO object or an LLL object

        """
        if isinstance(A, GSO.Mat):
            L = None
            M = A
            A = M.B
        elif isinstance(A, LLL.Reduction):
            L = A
            M = L.M
            A = M.B
        elif isinstance(A, IntegerMatrix):
            L = None
            M = None
            A = A
        else:
            raise TypeError("Matrix must be IntegerMatrix but got type '%s'"%type(A))

        if M is None and L is None:
            # run LLL first, but only if a matrix was passed
            wrapper = LLL.Wrapper(A)
            wrapper()

        self.A = A
        if M is None:
            self.M = GSO.Mat(A, flags=GSO.ROW_EXPO)
        else:
            self.M = M
        if L is None:
            self.lll_obj = LLL.Reduction(self.M, flags=LLL.DEFAULT)
        else:
            self.lll_obj = L
예제 #20
0
def test_callback_enum(d=40):

    FPLLL.set_random_seed(0x1337)
    A = LLL.reduction(IntegerMatrix.random(100, "qary", k=50, q=7681))
    M = GSO.Mat(A)
    M.update_gso()

    # we are not imposing a constraint
    enum_obj = Enumeration(M)
    solutions = enum_obj.enumerate(0, d, 0.99*M.get_r(0, 0), 0)
    max_dist, sol = solutions[0]
    assert(A.multiply_left(sol)[0] != 2)

    # now we do
    def callback(new_sol_coord):
        if A.multiply_left(new_sol_coord)[0] == 2:
            return True
        else:
            return False

    enum_obj = Enumeration(M, callbackf=callback)
    solutions = enum_obj.enumerate(0, d, 0.99*M.get_r(0, 0), 0)
    max_dist, sol = solutions[0]

    assert(A.multiply_left(sol)[0] == 2)
예제 #21
0
def solve_hnp(samples):
    d = len(samples)
    q = order

    B = IntegerMatrix(d + 2, d + 2)
    for i in range(d):
        t, u, v = samples[i]
        scale = q / v
        B[i, i] = q * scale
        B[d, i] = t * scale
        B[d + 1, i] = u * scale
    B[d, d] = 1
    B[d + 1, d + 1] = q

    M = GSO.Mat(B)
    L_red = LLL.Reduction(M)
    bkzparam = BKZ.Param(block_size=20)
    B_red = BKZ.Reduction(M, L_red, bkzparam)
    B_red()

    if B[1, d + 1] > 0:
        x = -1 * B[1, d]
    else:
        x = B[1, d]
    if x < 0:
        x += q

    private_value = 834818473318008049647448379209460658614088501345180055220225408308906924726
    print x == private_value
    priv = ec.derive_private_key(x, pub.curve, OSSL)
    original = ec.derive_private_key(private_value, pub.curve, OSSL)
    return priv, original
예제 #22
0
파일: cvp.py 프로젝트: Se-P3t/lattice_study
def babai_nearest_plane(A, w, **kwds):
    """Return lattice vector close to `v` using Babai's nearest plane algorithm.

    :param A: **reduced** basis, an instance of `list` or `IntegerMatrix`
    :param w: a tuple-like object
    :param int_type: (default: 'mpz') an element of `fpylll.config.int_types`
    :param float_type: (default: 'mpfr') an element of `fpylll.config.float_types`
    :param int_gram: See docs of `GSO.MatGSO`
    :param row_expo: See docs of `GSO.MatGSO`
    """
    int_type = kwds.get('int_type', 'mpz')
    if isinstance(A, list):
        A = IntegerMatrix.from_matrix(A, int_type=int_type)
    elif not isinstance(A, IntegerMatrix):
        raise TypeError("Matrix `A` type '%s' unknown." % type(A))

    float_type = kwds.get('float_type', 'mpfr')
    flags = GSO.DEFAULT
    if kwds.get('int_gram', False):
        flags |= GSO.INT_GRAM
    elif kwds.get('row_expo', False):
        flags |= GSO.ROW_EXPO

    M = GSO.Mat(A, flags=flags, float_type=float_type, update=True)
    v = M.babai(w, gso=True)

    return v
예제 #23
0
    def __init__(self, A, tuners=None, recycle=True):
        """Construct a new instance of the BKZ algorithm.

        :param A: an integer matrix, a GSO object or an LLL object

        """
        self.recycle = recycle
        if isinstance(A, LLL.Reduction):
            L, M, B = A, A.M, A.M.B
        elif isinstance(A, GSO.Mat):
            L, M, B = None, A, A.B
        elif isinstance(A, IntegerMatrix):
            L, M, B = None, None, A
        else:
            raise TypeError(
                "type of A must be in {IntegerMatrix, GSO.Mat, LLL.Reduction}, but got type '%s'"
                % type(A))

        if M is None and L is None:
            wrapper = LLL.Wrapper(B)
            wrapper()
        if M is None:
            M = GSO.Mat(B, flags=GSO.ROW_EXPO)
        if L is None:
            L = LLL.Reduction(M, flags=LLL.DEFAULT)

        self.lll_obj, self.M, self.A = L, M, B
        self.lll_obj()

        if tuners is None:
            self.tuners = [Tuner(b) for b in range(YOLO_MAX_BLOCK_SIZE)]
        else:
            self.tuners = tuners
        self.tracer = BKZTreeTracer(self, verbosity=True)
예제 #24
0
def osvp_time(seed, params, return_queue=None):
    """Run oSVP reduction on ``A`` using ``params``.

    :param seed: random seed for matrix creation
    :param params: BKZ parameters
    :param return_queue: if not ``None``, the result is put on this queue.

    """
    from cost import sample_matrix

    A = sample_matrix(ceil(params.block_size * (1 + params["c"])), seed=seed)
    M = GSO.Mat(A)
    bkz = ProcrastinatingBKZSimulation(M)
    tracer = BKZSimulationTreeTracer(bkz)

    with tracer.context(("tour", 0)):
        bkz.svp_reduction(0, params.block_size, params, tracer)

    tracer.exit()
    r = tuple([2 ** (r_) for r_ in bkz.r])

    tracer.trace.data["|A_0|"] = r[0]
    ppbs = params.strategies[params.block_size].preprocessing_block_sizes
    tracer.trace.data["preprocessing_block_size"] = ppbs[0] if ppbs else 2

    if return_queue:
        return_queue.put(tracer.trace)
    else:
        return tracer.trace
예제 #25
0
    def __init__(self, A, preprocessing_levels=1, preprocessing_cutoff=45):
        """
        Create a new BKZ Simulation object.

        :param A: An integer matrix, a GSO object or a list of squared Gram-Schmidt norms.
        :param preprocessing_levels: how many levels of preprocessing to simulate (slow!)

        .. note :: Our internal representation is log2 norms of Gram-Schmidt vectors (not squared).

        """
        if isinstance(A, GSO.Mat):
            A.update_gso()
            r = A.r()
            self.r = [log(r_, 2) / 2.0 for r_ in r]
        elif isinstance(A, LLL.Reduction):
            A.M.update_gso()
            r = A.M.r()
            self.r = [log(r_, 2) / 2.0 for r_ in r]
        elif isinstance(A, IntegerMatrix):
            M = GSO.Mat(LLL.reduction(A))
            M.update_gso()
            r = M.r()
            self.r = [log(r_, 2) / 2.0 for r_ in r]
        else:
            try:
                self.r = [log(r_, 2) / 2.0 for r_ in A]
            except TypeError:
                raise TypeError("Unsupported type '%s'" % type(A))
        self.preprocessing_levels = preprocessing_levels
        self.preprocessing_cutoff = preprocessing_cutoff
예제 #26
0
def test_gso_coherence_gram_matrix():
    """
        Test if the GSO is coherent if it is given a matrix A or its associated
        Gram matrix A*A^T
    """

    EPSILON = 0.0001

    for m, n in dimensions:
        for int_type in int_types:
            # long is not tested for high dimensions because of integer overflow
            if m > 20 and int_type == "long":
                continue

            A = make_integer_matrix(m, n, int_type=int_type).transpose()
            G = tools.compute_gram(A)

            for float_type in float_types:
                M_A = GSO.Mat(copy(A),
                              float_type=float_type,
                              gram=False,
                              flags=GSO.INT_GRAM)
                M_A.update_gso()

                M_G = GSO.Mat(copy(G),
                              float_type=float_type,
                              gram=True,
                              flags=GSO.INT_GRAM)
                M_G.update_gso()

                # Check that the gram matrix coincide
                for i in range(m):
                    for j in range(i):
                        assert M_A.get_int_gram(i, j) == G[i, j]

                # Check if computations coincide
                for i in range(m):
                    M_A.get_r(i, i) == pytest.approx(M_G.get_r(i, j),
                                                     rel=EPSILON)

                    for j in range(i):
                        assert (M_A.get_r(i,
                                          j) == pytest.approx(M_G.get_r(i, j),
                                                              rel=EPSILON))
                        assert (M_A.get_mu(i, j) == pytest.approx(M_G.get_mu(
                            i, j),
                                                                  rel=EPSILON))
예제 #27
0
def load_svp_challenge_r(d, seed=0):
    """
    Load SVP Challenge in dimension `d` and ``seed``

    :param d: dimension
    :param seed: random seed

    """
    A = load_svp_challenge(d, seed=seed)
    if d < 160:
        M = GSO.Mat(A, float_type="d")
    elif d < 320:
        M = GSO.Mat(A, float_type="dd")
    else:
        M = GSO.Mat(A, float_type="qd")
    M.update_gso()
    return M.r()
예제 #28
0
    def insert_in_IntegerMatrix(self, A, v, kappa, block_size):
        if (list(A[kappa]) == list(v)):
            return
        n = A.nrows
        l = A.ncols

        AA = IntegerMatrix(n + 1, l, int_type="long")
        for i in xrange(kappa):
            for j in xrange(l):
                AA[i, j] = A[i, j]
        for j in xrange(l):
            AA[kappa, j] = v[j]
        for i in xrange(kappa + 1, n + 1):
            for j in xrange(l):
                AA[i, j] = A[i - 1, j]

        M = GSO.Mat(AA, float_type=TYPE)
        M.update_gso()
        bkz = BKZ2(M)
        try:
            bkz.lll_obj(kappa, kappa,
                        kappa + block_size + 1)  # longer: 1 more row
        except:
            pass

        index = 0
        for i in range(kappa, kappa + block_size + 1):
            if (AA[i].is_zero()):
                index = i - kappa
                break

        for i in xrange(kappa + index):
            for j in xrange(l):
                A[i, j] = AA[i, j]
        for i in xrange(kappa + index + 1, n + 1):
            for j in xrange(l):
                A[i - 1, j] = AA[i, j]
        """
        for i in range(n):
            bad = 0
            for j in range(l):
                if (A[i][j] == 0):
                    bad = bad + 1
                if (bad == n):
                    print " inserting ", v
                    print " <<<<<<<<<<<<<<<<<<<<<< WRONG HERE at ", kappa, block_size, i
                    print A
                    print "old A is "
                    print AA_old
                    print "old A after lll is "                    
                    print AA                    
                    sys.exit(1)
        """

        del bkz
        del AA
        del M
        return
def main_cleanbkz_mpi_master(filename, bs, cores):

    try:
        with open(filename, "rb") as f:
            mat = pickle.load(f)
            #print "len(mat)", len(mat)
            #if (len(mat) > 1):
            #   mat = mat[0]
        if isinstance(mat, IntegerMatrix):
            Ainput = mat
        else:
            Ainput = IntegerMatrix.from_matrix(mat)
    except:
        Ainput = IntegerMatrix.from_file(filename)

    Ainput_M = GSO.Mat(Ainput, float_type='double')
    Ainput_M.update_gso()
    r = [Ainput_M.get_r(i, i) for i in range(0, Ainput.nrows)]
    L_Ainput_M = LLL.Reduction(Ainput_M)
    L_Ainput_M()

    print r

    A = IntegerMatrix.from_matrix(L_Ainput_M.M.B, int_type="long")

    cleanbkz_mpi = CLEANBKZ_MPI(A, cores)
    #cleanbkz_mpi = BKZ2(A)
    cleanbkz_mpi.lll_obj()
    cleanbkz_mpi.M.update_gso()
    r = [
        log(cleanbkz_mpi.M.get_r(i, i)) for i in range(0, cleanbkz_mpi.A.nrows)
    ]
    print "# starting r "
    print r

    params = BKZ.Param(
        block_size=bs,
        max_loops=5000,
        min_success_probability=.01,
        flags=BKZ.BOUNDED_LLL,  #|BKZ.DUMP_GSO,
        dump_gso_filename="gso_output.file",
        strategies="default.json")
    cleanbkz_mpi(params=params, min_row=0)
    #print "# done. found sv", cleanbkz_mpi.M.B[0]

    # done send last end signal
    for i in range(1, size):
        comm.send(1, i, tag=999)  # *** changed to send

    cleanbkz_mpi.M.update_gso()
    r2 = [
        log(cleanbkz_mpi.M.get_r(i, i)) for i in range(0, cleanbkz_mpi.A.nrows)
    ]
    print cleanbkz_mpi.A[0]
    print "# ending r"
    print r2

    return
예제 #30
0
def test_bkz_init():
    for m, n in dimensions:
        A = make_integer_matrix(m, n)
        for float_type in float_types:
            M = GSO.Mat(copy(A), float_type=float_type)
            lll_obj = LLL.Reduction(M)
            param = BKZ.Param(block_size=3, strategies=BKZ.DEFAULT_STRATEGY)
            bkz = BKZ.Reduction(M, lll_obj, param)
            del bkz