static int ec_guess_cofactor(EC_GROUP *group) {
    int ret = 0;
    BN_CTX *ctx = NULL;
    BIGNUM *q = NULL;

    /*-
     * If the cofactor is too large, we cannot guess it.
     * The RHS of below is a strict overestimate of lg(4 * sqrt(q))
     */
    if (BN_num_bits(group->order) <= (BN_num_bits(group->field) + 1) / 2 + 3) {
        /* default to 0 */
        BN_zero(group->cofactor);
        /* return success */
        return 1;
    }

    if ((ctx = BN_CTX_new()) == NULL)
        return 0;

    BN_CTX_start(ctx);
    if ((q = BN_CTX_get(ctx)) == NULL)
        goto err;

    /* set q = 2**m for binary fields; q = p otherwise */
    if (group->meth->field_type == NID_X9_62_characteristic_two_field) {
        BN_zero(q);
        if (!BN_set_bit(q, BN_num_bits(group->field) - 1))
            goto err;
    } else {
        if (!BN_copy(q, group->field))
            goto err;
    }

    /* compute h = \lfloor (q + 1)/n \rceil = \lfloor (q + 1 + n/2)/n \rfloor */
    if (!BN_rshift1(group->cofactor, group->order) /* n/2 */
        || !BN_add(group->cofactor, group->cofactor, q) /* q + n/2 */
        /* q + 1 + n/2 */
        || !BN_add(group->cofactor, group->cofactor, BN_value_one())
        /* (q + 1 + n/2)/n */
        || !BN_div(group->cofactor, NULL, group->cofactor, group->order, ctx))
        goto err;
    ret = 1;
 err:
    BN_CTX_end(ctx);
    BN_CTX_free(ctx);
    return ret;
}
static int ec_guess_cofactor(EC_GROUP *group) {
    int ret = 0;
    BN_CTX *ctx = NULL;
    BIGNUM *q = NULL;

     
    if (BN_num_bits(group->order) <= (BN_num_bits(group->field) + 1) / 2 + 3) {
         
        BN_zero(group->cofactor);
         
        return 1;
    }

    if ((ctx = BN_CTX_new()) == NULL)
        return 0;

    BN_CTX_start(ctx);
    if ((q = BN_CTX_get(ctx)) == NULL)
        goto err;

     
    if (group->meth->field_type == NID_X9_62_characteristic_two_field) {
        BN_zero(q);
        if (!BN_set_bit(q, BN_num_bits(group->field) - 1))
            goto err;
    } else {
        if (!BN_copy(q, group->field))
            goto err;
    }

     
    if (!BN_rshift1(group->cofactor, group->order)  
        || !BN_add(group->cofactor, group->cofactor, q)  
         
        || !BN_add(group->cofactor, group->cofactor, BN_value_one())
         
        || !BN_div(group->cofactor, NULL, group->cofactor, group->order, ctx))
        goto err;
    ret = 1;
 err:
    BN_CTX_end(ctx);
    BN_CTX_free(ctx);
    return ret;
}