Skip to content

Replace secp256k1 code patching with C code. #50

@sergey-shandar

Description

@sergey-shandar

Currently, we patch the secp256k1 code immediately after downloading it (see source).

To avoid patching the secp256k1 code directly, we can create new C files for our modifications. This way, we can maintain our changes separately from the original library. Here's how to achieve this:

### Tasks
- [ ] https://github.com/Trust-Machines/p256k1/issues/52
- [ ] https://github.com/Trust-Machines/p256k1/issues/53

Case 1: Remove static to make the code visible

For example, replace this code:

SECP256K1_INLINE static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a) {

with this:

static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a) {

Alternative: Generate a new function from a list of signatures

// secp256k1_extension.h
#include <secp256k1.h>
SECP256K1_API void p256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a);
// secp256k1_extension.c
#include "secp256k1_extension.h"
void p256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a) {
    secp256k1_fe_add(r, a);
}

Case 2: Replace a function

For example, the original function:

void secp256k1_ge_set_gej(secp256k1_ge *r, secp256k1_gej *a) {
    secp256k1_fe z2, z3;
    r->infinity = a->infinity;
    secp256k1_fe_inv(&a->z, &a->z);
    secp256k1_fe_sqr(&z2, &a->z);
    secp256k1_fe_mul(&z3, &a->z, &z2);
    secp256k1_fe_mul(&a->x, &a->x, &z2);
    secp256k1_fe_mul(&a->y, &a->y, &z3);
    secp256k1_fe_set_int(&a->z, 1);
    r->x = a->x;
    r->y = a->y;
}

was replaced with:

void secp256k1_ge_set_gej(secp256k1_ge *r, const secp256k1_gej *a) {
    secp256k1_fe z2, z3, az, ax, ay;
    r->infinity = a->infinity;
    secp256k1_fe_inv(&az, &a->z);
    secp256k1_fe_sqr(&z2, &az);
    secp256k1_fe_mul(&z3, &az, &z2);
    secp256k1_fe_mul(&ax, &a->x, &z2);
    secp256k1_fe_mul(&ay, &a->y, &z3);
    secp256k1_fe_set_int(&az, 1);
    r->x = ax;
    r->y = ay;
}

Alternative: Write a new function

void p256k1_ge_set_gej(secp256k1_ge *r, const secp256k1_gej *a) {
    secp256k1_fe z2, z3, az, ax, ay;
    r->infinity = a->infinity;
    secp256k1_fe_inv(&az, &a->z);
    secp256k1_fe_sqr(&z2, &az);
    secp256k1_fe_mul(&z3, &az, &z2);
    secp256k1_fe_mul(&ax, &a->x, &z2);
    secp256k1_fe_mul(&ay, &a->y, &z3);
    secp256k1_fe_set_int(&az, 1);
    r->x = ax;
    r->y = ay;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    Status

    ⚙️ WIP - Design

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions