mhw0 / libethc

Open-source Ethereum C library
https://mhw0.github.io/libethc/
MIT License
46 stars 8 forks source link

Loading account from a private key #43

Closed talentlessguy closed 1 month ago

talentlessguy commented 1 month ago

Hi, I'm a total noob in C but I wanted to run a quick experiment so I need libethc for this.

Could you please provide an example (and if possible, add it to the docs) of how you could create an account instance from a private key? Private key being a hexademical string, not a uint8 array.

#include <stdio.h>
#include <stdlib.h>
#include <ethc/account.h>

int main() {
    // Example hex string
    const char *hexstr = getenv("PK"); // 0x9ef...

    struct eth_account acc;

    set_pk(hexstr, &acc); // how would this function look like?

    char *addr;
    eth_account_address_get(addr, &acc);

    return 0;
}

Thanks in advance!

mhw0 commented 1 month ago

Hello @talentlessguy!

Look at these two eth_hex_to_bytes, eth_account_from_privkey and this test

#include <stdio.h>
#include <stdlib.h>
#include <ethc/account.h>

int main() {
    // Example hex string
    const char *hexstr = getenv("PK"); // 0x9ef...
    const uint8_t *privkey;

    struct eth_account acc;

    eth_hex_from_bytes(&privkey, hexstr);
    eth_account_from_privkey(&account, &privkey);

    char *addr;
    eth_account_address_get(addr, &acc);

    return 0;
}

didn't test, but should work.

talentlessguy commented 1 month ago

This code worked, thanks a lot for the help!

#include <stdio.h>
#include <stdlib.h>
#include <ethc/account.h>
#include <ethc/hex.h>
#include <string.h>

int main() {
    // Example hex string
    const char *hexstr = getenv("PK"); // 0x9ef...
    uint8_t *privkey;

    struct eth_account acc;

    // Call the function with the correct parameters
    eth_hex_to_bytes(&privkey, hexstr, strlen(hexstr));
    eth_account_from_privkey(&acc, privkey);

    char addr[40];
    eth_account_address_get(&addr, &acc);

    printf("%s", &addr);

    return 0;
}