Esempio n. 1
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]
Esempio n. 2
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]
Esempio n. 3
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
Esempio n. 4
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)
Esempio n. 5
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
Esempio n. 6
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
Esempio n. 7
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
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
Esempio n. 9
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
Esempio n. 10
0
File: bkz3.py Progetto: malb/yolo
    def __call__(self, params, min_row=0, max_row=-1):
        """Run the BKZ algorithm with parameters `param`.

        :param params: BKZ parameters
        :param min_row: start processing in this row
        :param max_row: stop processing in this row (exclusive)

        """
        self.ith_block = 0
        tracer = BKZTreeTracer(self, verbosity=params.bkz_param.flags & BKZ.VERBOSE, start_clocks=True)
        self.params = params

        self.lll_objs = 20*[None]
        for i in range(20):
            eta = etas[i]
            self.lll_objs[i] = LLL.Reduction(self.M, flags=LLL.DEFAULT, eta=eta)

        cputime_start = time.clock()

        self.M.discover_all_rows()
        with tracer.context("lll"):
            for i in range(20):
                self.lll_objs[i]()

        if params.rampup:
            with tracer.context("rampup", -1):
                self.preprocessing(params.bkz_param.block_size, min_row, max_row, start=10, step=1, tracer=tracer)

        i = 0
        self.ith_tour = 0
        while True:
            with tracer.context("tour", i):
                self.ith_block = 0
                self.ith_tour += 1
                clean = self.tour(params.bkz_param, min_row, max_row, tracer=tracer, top_level=True)
            print "proba %.4f" % self.tuners[params.bkz_param.block_size].proba
            # for x in sorted(self.tuners[params.bkz_param.block_size].data.keys()):
            #    try:
            #        print x, "\t %d \t %.2f " % (self.tuners[params.bkz_param.block_size].counts[x], self.tuners[params.bkz_param.block_size].data[x])
            #    except:
            #        pass
            print
            i += 1
            if (not clean) or params.bkz_param.block_size >= self.A.nrows:
                break
            if (params.bkz_param.flags & BKZ.AUTO_ABORT) and auto_abort.test_abort():
                break
            if (params.bkz_param.flags & BKZ.MAX_LOOPS) and i >= params.bkz_param.max_loops:
                break
            if (params.bkz_param.flags & BKZ.MAX_TIME) and time.clock() - cputime_start >= params.bkz_param.max_time:
                break

        self.trace = tracer.trace
        return clean
Esempio n. 11
0
def iterated_sub_sieve(A, goal):
    n = A.nrows
    M = GSO.Mat(A)
    lll = LLL.Reduction(M)
    lll()
    n = M.d
    d = n / 4
    while M.get_r(0, 0) > goal:
        sub_sieve_plus(lll, d)
        d -= 1
    return d + 1
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
Esempio n. 13
0
def test_lll_lll():
    for m, n in dimensions:
        A = make_integer_matrix(m, n)
        b00 = []
        for float_type in float_types:
            B = copy(A)
            M = GSO.Mat(B, float_type=float_type)
            lll = LLL.Reduction(M)
            lll()
            if (m, n) == (0, 0):
                continue
            b00.append(B[0, 0])
        for i in range(1, len(b00)):
            assert b00[0] == b00[i]
Esempio n. 14
0
File: yolosvp.py Progetto: malb/yolo
def test():
    for n in ns:
        print
        print "++++ Dim ", n
        A = make_integer_matrix(n)
        M = GSO.Mat(A, flags=GSO.ROW_EXPO)
        lll_obj = LLL.Reduction(M, flags=LLL.DEFAULT)
        lll_obj()

        t_start = time()
        B = copy(A)
        timer = Timer()
        proudly_parrallel(3, yolo_hsvp, (n, B, 1.05**2))

        print "time: %.1f sec" % (time() - t_start)
Esempio n. 15
0
def test_bkz_bkz():
    for m, n in dimensions:
        if m < 2 or n < 2:
            continue
        A = make_integer_matrix(m, n)
        b00 = []
        for float_type in float_types:
            B = copy(A)
            M = GSO.Mat(B, float_type=float_type)
            lll_obj = LLL.Reduction(M)
            param = BKZ.Param(block_size=min(m, 40), strategies="default.json")
            bkz = BKZ.Reduction(M, lll_obj, param)
            bkz()
            b00.append(B[0, 0])
        for i in range(1, len(b00)):
            assert b00[0] == b00[i]
Esempio n. 16
0
    def __init__(self, A):
        """Construct a new BKZ reduction instance.

        :param A: Integer matrix to reduce.

        """
        if not isinstance(A, IntegerMatrix):
            raise TypeError("Matrix must be IntegerMatrix but got type '%s'" %
                            type(A))

        # run LLL first
        wrapper = LLL.Wrapper(A)
        wrapper()

        self.A = A
        self.m = GSO.Mat(A, flags=GSO.ROW_EXPO)
        self.lll_obj = LLL.Reduction(self.m)
Esempio n. 17
0
def compare():
    tuners = [Tuner(b) for b in range(100)]
    recycled_tuners = [Tuner(b) for b in range(100)]

    A = make_integer_matrix(n)
    M = GSO.Mat(A, flags=GSO.ROW_EXPO)
    lll_obj = LLL.Reduction(M, flags=LLL.DEFAULT)
    lll_obj()

    for n in ns:
        params = fplll_bkz.Param(block_size=bs,
                                 max_loops=tours,
                                 flags=fplll_bkz.VERBOSE | fplll_bkz.GH_BND,
                                 strategies="default.json")

        print
        print "======"
        print "dim ", n
        print "======"

        # print
        # print "yoloBKZ"
        # B = copy(A)
        # YoloBKZ(B, tuners=tuners, recycle=False)(b=bs, tours=tours)

        print
        print "Recycled yoloBKZ"
        # B = copy(A)
        # YoloBKZ(B, tuners=recycled_tuners)(b=bs, tours=1)
        # print
        # print "Restart"
        # print

        B = copy(A)
        timer = Timer()
        YoloBKZ(B, tuners=recycled_tuners)(b=bs, tours=tours)
        print "Total: %.3f" % timer.elapsed()
Esempio n. 18
0
    def __call__(self, solver=None, flavor="plain", worst_case=False, sample=True, **kwds):
        """
        Solve the HNP instance.

        :param solver: a uSVP with predicate solver or ``None`` for letting ``usvp_pred_solve`` decide.
        :param sample: if ``True`` a fresh basis is sampled
        :param worst_case: if ``True`` the target norm is chosen to match the maximum of the target, this will be slow.

        """
        if sample:
            self.M = self.gen_lattice()

        tau = max([2 ** (klen - 1) for klen in self.klen_list])

        def predicate(v, standard_basis=True):
            G_powers, A0, A1 = self._data_for_test()
            w = 2 ** (self.klen_list[0] - 1)
            f = Integer((2 ** (max(self.klen_list) - 1)) / w)

            if standard_basis:
                nz = v[-1]
            else:
                nz = sum(round(v[i]) * A1[i] for i in range(len(A1)))  # the last coefficient must be non-zero

            if abs(nz) != tau:
                return False

            if standard_basis:
                kG = G_powers[v[0] // f]
            else:
                kG = sum(round(v[i]) * G_powers[A0[i]] for i in range(len(A0)))

            r = self.r_list[0]
            if (kG + G_powers[w]).xy()[0] == r:
                return True
            elif (-kG + G_powers[w]).xy()[0] == r:
                return True
            else:
                return False

        def invalidate_cache():
            self._data_for_test.clear_cache()

        if worst_case:
            target_norm = self.mvf(self.m, max(self.klen_list), prec=self.ecdsa.nbits // 2)
        else:
            target_norm = self.evf(self.m, max(self.klen_list), prec=self.ecdsa.nbits // 2)

        LLL.Reduction(self.M)()
        invalidate_cache()

        res = flavors[flavor](
            self.M,
            predicate,
            squared_target_norm=target_norm ** 2,
            invalidate_cache=invalidate_cache,
            threads=self.threads,
            solver=solver,
            **kwds
        )

        if res.success:
            key = self.recover_key(res.solution)
        else:
            key = False

        return key, res
Esempio n. 19
0
    def svp_reduction_mpi(self,
                          kappa,
                          block_size,
                          params,
                          tracer=dummy_tracer):
        # time
        start_time = time()

        # max preprocessing block size
        bs_diff = BS_DIFF
        bs_max = block_size - bs_diff

        # set goal
        self.M.update_gso()

        # current vector
        #kappa_length = self.M.get_r(kappa, kappa) * self.lll_obj.delta
        kappa_length = self.M.get_r(kappa, kappa)

        # gh length
        r = [self.M.get_r(i, i) for i in range(kappa, kappa + block_size)]
        #gh_length = gaussian_heuristic(r) * params.gh_factor
        gh_length = gaussian_heuristic(r) * 1.1

        goal = gh_length
        if (kappa_length <= goal):
            if (rank == 0 and block_size >= BOUND_SINGLE):
                print "# [rank %d] kappa = %d bs = %d, goal = %d, r = %d (already achieved -- pass)" % \
                  (rank, kappa, block_size, goal, r[0])
                print "gh_factor: ", params.gh_factor
            return 1
        """
        goal = (goal + kappa_length) / 2
        if (goal < r[0] * 0.95):
            goal = r[0] * 0.95
        """

        # info
        #"""
        if (rank == 0 and block_size >= BOUND_SINGLE):
            print "# [rank %d] kappa = %d bs = %d, goal = %d, r = %d" % \
              (rank, kappa, block_size, goal, r[0])

        #"""
        # set matrices
        n = self.A.nrows
        trials = self.ncores * [0]
        As = self.ncores * [None]
        POOL_SIZE = 8 * self.ncores
        POOL_COPIES = 1 + self.ncores / 4

        # randomization matrices
        for i in range(self.ncores):
            As[i] = self.copy_to_IntegerMatrix_long(self.A)
            M = GSO.Mat(As[i], float_type=TYPE)
            bkz = BKZ2_SUB(M)
            bkz.randomize_block(kappa,
                                kappa + block_size,
                                density=block_size / 3)
            del bkz
            del M

        # setup share pools
        sv_pool = SVPool(POOL_SIZE, copies=POOL_COPIES)
        sv_pool.data = []
        workers = self.ncores * [None]
        over = False

        #print "####################################################"
        #print "### Process", rank, " starts cores ", self.ncores

        # list of queues
        list_queue = [Queue() for i in xrange(self.ncores)]
        fail_list = [0 for i in xrange(self.ncores)]
        break_flag = [0 for i in xrange(self.ncores)]
        terminated_by_other = 0
        filenames = ["b" + str(n) + "_n" + str(rank) + \
                    "-c" + str(i) for i in xrange(self.ncores)]

        while not over:

            state = MPI.Status()
            okay = comm.iprobe(source=MPI.ANY_SOURCE, tag=99, status=state)
            if (okay):
                node = state.Get_source()
                data = comm.recv(source=node, tag=99)
                #print "# [rank %d] receive exit signal from rank %d " % (rank, node)
                if (data == 1):
                    terminated_by_other = 1
                    self.A = As[0]  # need improve
                    self.M = GSO.Mat(self.A, float_type=TYPE)
                    self.lll_obj = LLL.Reduction(self.M, flags=LLL.DEFAULT)
                    for i in range(self.ncores):
                        self.insert_in_IntegerMatrix(self.A, As[i][kappa],
                                                     kappa, block_size)
                    break

            sleep(0.01)

            for i in range(self.ncores):

                if workers[i] is None:
                    v = sv_pool.pop()
                    if v is not None:
                        self.insert_in_IntegerMatrix(As[i], v, kappa,
                                                     block_size)

                    bsi = bs_max - 30
                    bsi += min(20, 2 *
                               trials[i])  # about 10 trials to go up to bs_max
                    bsi -= random.randint(0, 3)

                    norm = self.M.get_r(kappa, kappa)
                    pickle.dump((As[i], norm, False), open(filenames[i], 'wb'))

                    # just use current bsi
                    if (fail_list[i] <= 0):
                        workers[i] = Process(
                            target=self.svp_reduction_mpi_trial,
                            args=(As[i], kappa, block_size, bsi, list_queue[i],
                                  filenames[i]))

                    # increase blocksize bsi
                    elif (fail_list[i] > 0
                          and fail_list[i] <= THRESHOLD_LEVEL1):
                        bsi = min(bs_max, bsi + fail_list[i])
                        workers[i] = Process(
                            target=self.svp_reduction_mpi_trial,
                            args=(As[i], kappa, block_size, bsi, list_queue[i],
                                  filenames[i]))
                    # stablize bsi; but rerandomization
                    elif (fail_list[i] <= THRESHOLD_LEVEL2):
                        M = GSO.Mat(As[i], float_type=TYPE)
                        bkz = BKZ2_SUB(M)
                        bkz.randomize_block(kappa,
                                            kappa + block_size,
                                            density=block_size / 3)
                        del bkz
                        del M
                        workers[i] = Process(
                            target=self.svp_reduction_mpi_trial,
                            args=(As[i], kappa, block_size, bsi, list_queue[i],
                                  filenames[i]))
                    else:
                        workers[i] = Process(
                            target=self.svp_reduction_mpi_trial,
                            args=(As[i], kappa, block_size, bsi, list_queue[i],
                                  filenames[i]))
                        break_flag[i] = True

                    # start woker
                    t = workers[i].start()

                if (workers[i] is not None) and (not workers[i].is_alive()):

                    # get and insert
                    As[i], norm, success = pickle.load(open(
                        filenames[i], 'rb'))
                    """
                    success = list_queue[i].get()
                    norm = list_queue[i].get()
                    j = 0
                    # buffer read for queue
                    while True:
                        if (j >= block_size):
                            break
                        try:
                            v = list_queue[i].get()
                        except Queue.Empty:
                            break
                        for k in range(As[i].ncols):
                            As[i][kappa+j, k] = v[k]
                        j += 1
                    #for j in xrange(THRESHOLD_SEND):
                    #    self.insert_in_IntegerMatrix(As[i], mat[j], kappa, block_size)
                    """

                    # break
                    if (break_flag[i]):
                        workers[i] = None
                        self.A = As[i]
                        self.M = GSO.Mat(self.A, float_type=TYPE)
                        self.lll_obj = LLL.Reduction(self.M, flags=LLL.DEFAULT)
                        over = True
                        break

                    # found smaller norm than goal
                    if norm < goal:
                        #print "# SVP-", n, "SOLUTION :", As[i][kappa]
                        #print "#   [rank %d] found SVP-%d, norm %d < goal %d" % (rank,
                        #            block_size, norm, goal)
                        self.A = As[i]
                        self.M = GSO.Mat(self.A, float_type=TYPE)
                        self.lll_obj = LLL.Reduction(self.M, flags=LLL.DEFAULT)
                        over = True
                        break
                    # found smaller norm but larger than goal
                    if (success):
                        sv_pool.push([x for x in As[i][kappa]], norm)
                        fail_list[i] = 0
                    else:
                        norm = 1e100
                        fail_list[i] += 1

                    # done update
                    workers[i] = None
                    trials[i] += 1

        for w in [w for w in workers if w is not None]:
            w.terminate()

        # terminated by this process -- signal others MPI's to stop
        if (terminated_by_other == 0):
            for i in range(size):
                if (i != rank):
                    comm.isend(1, i, tag=99)

        # sending data to master node
        self.M.update_gso()
        if (rank != 0):
            send_vec = []
            #for i in range(block_size/10):
            #    send_vec.append(list(self.A[kappa+i]))
            send_vec.append(list(self.A[kappa]))
            # self.M.update_gso()
            norm = self.M.get_r(kappa, kappa)
            comm.isend(send_vec, dest=0, tag=11)

        # master node receiving data
        if (rank == 0):
            num = 0
            while (1):
                if (num >= size - 1):
                    break
                sleep(.01)
                state = MPI.Status()
                okay = comm.iprobe(source=MPI.ANY_SOURCE, tag=11, status=state)
                if (okay):
                    num += 1
                    node = state.Get_source()
                    vectors = comm.recv(source=node, tag=11)
                    for i in range(len(vectors)):
                        self.insert_in_IntegerMatrix(self.A, vectors[i], kappa,
                                                     block_size)
                    self.M = GSO.Mat(self.A, float_type=TYPE)
                    self.M.update_gso()
                    self.lll_obj = LLL.Reduction(self.M, flags=LLL.DEFAULT)
                    norm = self.M.get_r(kappa, kappa)

        # message
        self.M.update_gso()
        kappa_length = self.M.get_r(kappa, kappa)
        if (rank == 0 and block_size >= BOUND_SINGLE):
            print "# [rank %d] kappa %d, bs %d, r %d (gh %d), time %s, trials %s " % \
            (rank, kappa, block_size, kappa_length, goal, time()-start_time, trials)

        # check processes
        while True:
            sleep(.01)
            some_alive = False
            for w in [w for w in workers if w is not None]:
                some_alive |= w.is_alive()
            if not some_alive:
                return 1
Esempio n. 20
0
    def svp_reduction_single(self,
                             kappa,
                             block_size,
                             params,
                             tracer=dummy_tracer):
        """
        :param kappa:
        :param block_size:
        :param params:
        :param tracer:
        """
        print self.lll_obj.delta
        verbose = 0

        if (params.flags & BKZ.DUMP_GSO):
            verbose = 1

        if (verbose):
            start_time = time()
        self.M.update_gso()
        r = [self.M.get_r(i, i) for i in range(kappa, kappa + block_size)]
        gh_length = gaussian_heuristic(r)
        kappa_length = self.M.get_r(kappa, kappa)
        goal = min(kappa_length, gh_length)

        self.lll_obj.size_reduction(0, kappa + 1)
        old_first, old_first_expo = self.M.get_r_exp(kappa, kappa)
        remaining_probability = 1.0
        rerandomize = False
        trials = 0
        sub_solutions = block_size > SUBSOL_BLOCKSIZE

        # copy old lattice
        if (params.flags & BKZ.DUMP_GSO):
            A_backup = self.copy_to_IntegerMatrix_long(self.A)
            v_old = A_backup[kappa]
            r_old = [
                log(self.M.get_r(i, i))
                for i in range(kappa, kappa + block_size)
            ]

        # main loop
        while remaining_probability > 1. - params.min_success_probability:

            # 1. preprocessing
            preproc_start = time()

            with tracer.context("preprocessing"):
                #self.M.update_gso()
                self.svp_preprocessing(kappa,
                                       block_size,
                                       params,
                                       trials,
                                       tracer=tracer)
            preproc_cost = time() - preproc_start

            with tracer.context("pruner"):
                target = 1 - ((1. - params.min_success_probability) /
                              remaining_probability)

                radius, pruning = self.get_pruning(kappa, block_size, params,
                                                   target * 1.01, preproc_cost,
                                                   tracer)

            # 2. enum
            enum_obj = Enumeration(self.M, sub_solutions=sub_solutions)
            try:
                with tracer.context("enumeration",
                                    enum_obj=enum_obj,
                                    probability=pruning.expectation,
                                    full=block_size == params.block_size):
                    max_dist, solution = enum_obj.enumerate(
                        kappa,
                        kappa + block_size,
                        radius,
                        0,
                        pruning=pruning.coefficients)[0]

                # 3. post processing
                with tracer.context("postprocessing"):
                    preproc_start = time(
                    )  # Include post_processing time as the part of the next pre_processing

                    if not sub_solutions:
                        self.svp_postprocessing(kappa,
                                                block_size,
                                                solution,
                                                tracer=tracer)
                    if sub_solutions:
                        self.insert_sub_solutions(
                            kappa, block_size,
                            enum_obj.sub_solutions[:1 + block_size / 4])
                    self.M.update_gso()

            except EnumerationError:
                preproc_start = time()

            remaining_probability *= (1 - pruning.expectation)

            trials += 1

        # recover basis
        if (params.flags & BKZ.DUMP_GSO):
            r_new = [
                self.M.get_r(i, i) for i in range(kappa, kappa + block_size)
            ]
            current = self.copy_to_vector_long(self.A[kappa])
            # update
            self.copy_from_IntegerMatrix_long(A_backup)
            self.M = GSO.Mat(self.A, float_type=TYPE)
            self.M.update_gso()
            self.lll_obj = LLL.Reduction(self.M, flags=LLL.DEFAULT)
            self.insert_in_IntegerMatrix(self.A, current, kappa, block_size)
            # update again for safe
            self.M = GSO.Mat(self.A, float_type=TYPE)
            self.M.update_gso()
            self.M = GSO.Mat(self.A, float_type=TYPE)
            self.M = GSO.Mat(self.A, float_type=TYPE)
            self.M.update_gso()
            self.lll_obj = LLL.Reduction(self.M, flags=LLL.DEFAULT)
            if (not self.check_compare(A_backup, self.A, kappa, block_size)):
                print "# error exit"
                sys.exit(1)

        self.M.update_gso()
        new_first, new_first_expo = self.M.get_r_exp(kappa, kappa)
        clean = old_first <= new_first * 2**(new_first_expo - old_first_expo)

        if (params.flags & BKZ.DUMP_GSO):
            global stat_update_gh
            r_new = self.M.get_r(kappa, kappa)
            r_newlog = [
                log(self.M.get_r(i, i))
                for i in range(kappa, kappa + block_size)
            ]
            stat_update_gh[stat_tours - 1].append(
                float(sqrt(r_new / gh_length)))

        if (verbose):
            if (rank == 0):
                kappa_length = r_new
                print "# [rank %d] kappa %d, bs %d, r %d (gh %d), time %s, trials %s " % \
                  (rank, kappa, block_size, kappa_length, goal, time()-start_time, trials)

                det_n = float(sum(r_old) / block_size)
                normalized_old = [(r_old[i] - det_n)
                                  for i in range(0, block_size)]
                normalized_new = [(r_newlog[i] - det_n)
                                  for i in range(0, block_size)]
                global stat_old_norm
                global stat_new_norm

                if (block_size == params.block_size):
                    for i in range(block_size):
                        stat_old_norm[i] = stat_old_norm[i] + normalized_old[i]
                        stat_new_norm[i] = stat_new_norm[i] + normalized_new[i]

        return clean
Esempio n. 21
0
def prepare(n):
    A = IntegerMatrix.random(n, "qary", bits=n / 2, k=n / 2)
    M = GSO.Mat(A)
    L = LLL.Reduction(M)
    L()
    return M
Esempio n. 22
0
#print(gpoly(1,0))

indrow = 0
A = IntegerMatrix(w, w)
for v in range(m + 1):
    for u in range(e):
        coeff_vector = gpoly(u, v)
        #print(v,u,coeff_vector)
        for icol in range(len(coeff_vector)):
            A[indrow,
              icol] = int(coeff_vector[len(coeff_vector) - icol - 1])  #.item()
        indrow += 1

print(A)

FPLLL.set_precision(120)
M = GSO.Mat(A, float_type="mpfr")
M.update_gso()
print('before LLL:', A[0].norm(), M.get_r(0, 0))

L = LLL.Reduction(M, delta=0.9999, eta=0.5001)
L()
print('after LLL:', A[0].norm(), M.get_r(0, 0))
print(A[0])
A0rev = list(A[0])[::-1]

hpoly = np.poly1d(A0rev)
print('hpoly:', hpoly)
print('eval at 2 = ', np.polyval(hpoly, 2) % (N ^ 3))
print(hpoly.r)